language-service.umd.js 2.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579
  1. /**
  2. * @license Angular v8.1.3
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. var $reflect = {defineMetadata: function() {}, getOwnMetadata: function() {}};
  7. var Reflect = (typeof global !== 'undefined' ? global : {})['Reflect'] || {};
  8. Object.keys($reflect).forEach(function(key) { Reflect[key] = Reflect[key] || $reflect[key]; });
  9. var $deferred, $resolved, $provided;
  10. function $getModule(name) { return $provided[name] || require(name); }
  11. function define(modules, cb) { $deferred = { modules: modules, cb: cb }; }
  12. module.exports = function(provided) {
  13. if ($resolved) return $resolved;
  14. var result = {};
  15. $provided = Object.assign({'reflect-metadata': $reflect}, provided || {}, { exports: result });
  16. $deferred.cb.apply(this, $deferred.modules.map($getModule));
  17. $resolved = result;
  18. return result;
  19. }
  20. define(['exports', 'path', 'typescript', 'fs'], function (exports, path, ts, fs) { 'use strict';
  21. /*! *****************************************************************************
  22. Copyright (c) Microsoft Corporation. All rights reserved.
  23. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  24. this file except in compliance with the License. You may obtain a copy of the
  25. License at http://www.apache.org/licenses/LICENSE-2.0
  26. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  28. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  29. MERCHANTABLITY OR NON-INFRINGEMENT.
  30. See the Apache Version 2.0 License for specific language governing permissions
  31. and limitations under the License.
  32. ***************************************************************************** */
  33. /* global Reflect, Promise */
  34. var extendStatics = function(d, b) {
  35. extendStatics = Object.setPrototypeOf ||
  36. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  37. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  38. return extendStatics(d, b);
  39. };
  40. function __extends(d, b) {
  41. extendStatics(d, b);
  42. function __() { this.constructor = d; }
  43. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  44. }
  45. var __assign = function() {
  46. __assign = Object.assign || function __assign(t) {
  47. for (var s, i = 1, n = arguments.length; i < n; i++) {
  48. s = arguments[i];
  49. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  50. }
  51. return t;
  52. };
  53. return __assign.apply(this, arguments);
  54. };
  55. function __decorate(decorators, target, key, desc) {
  56. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  57. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  58. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  59. return c > 3 && r && Object.defineProperty(target, key, r), r;
  60. }
  61. function __param(paramIndex, decorator) {
  62. return function (target, key) { decorator(target, key, paramIndex); }
  63. }
  64. function __metadata(metadataKey, metadataValue) {
  65. if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
  66. }
  67. function __values(o) {
  68. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  69. if (m) return m.call(o);
  70. return {
  71. next: function () {
  72. if (o && i >= o.length) o = void 0;
  73. return { value: o && o[i++], done: !o };
  74. }
  75. };
  76. }
  77. function __read(o, n) {
  78. var m = typeof Symbol === "function" && o[Symbol.iterator];
  79. if (!m) return o;
  80. var i = m.call(o), r, ar = [], e;
  81. try {
  82. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  83. }
  84. catch (error) { e = { error: error }; }
  85. finally {
  86. try {
  87. if (r && !r.done && (m = i["return"])) m.call(i);
  88. }
  89. finally { if (e) throw e.error; }
  90. }
  91. return ar;
  92. }
  93. function __spread() {
  94. for (var ar = [], i = 0; i < arguments.length; i++)
  95. ar = ar.concat(__read(arguments[i]));
  96. return ar;
  97. }
  98. /**
  99. * @license
  100. * Copyright Google Inc. All Rights Reserved.
  101. *
  102. * Use of this source code is governed by an MIT-style license that can be
  103. * found in the LICENSE file at https://angular.io/license
  104. */
  105. var TagContentType;
  106. (function (TagContentType) {
  107. TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
  108. TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
  109. TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
  110. })(TagContentType || (TagContentType = {}));
  111. function splitNsName(elementName) {
  112. if (elementName[0] != ':') {
  113. return [null, elementName];
  114. }
  115. var colonIndex = elementName.indexOf(':', 1);
  116. if (colonIndex == -1) {
  117. throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\"");
  118. }
  119. return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
  120. }
  121. // `<ng-container>` tags work the same regardless the namespace
  122. function isNgContainer(tagName) {
  123. return splitNsName(tagName)[1] === 'ng-container';
  124. }
  125. // `<ng-content>` tags work the same regardless the namespace
  126. function isNgContent(tagName) {
  127. return splitNsName(tagName)[1] === 'ng-content';
  128. }
  129. // `<ng-template>` tags work the same regardless the namespace
  130. function isNgTemplate(tagName) {
  131. return splitNsName(tagName)[1] === 'ng-template';
  132. }
  133. function getNsPrefix(fullName) {
  134. return fullName === null ? null : splitNsName(fullName)[0];
  135. }
  136. function mergeNsAndName(prefix, localName) {
  137. return prefix ? ":" + prefix + ":" + localName : localName;
  138. }
  139. // see http://www.w3.org/TR/html51/syntax.html#named-character-references
  140. // see https://html.spec.whatwg.org/multipage/entities.json
  141. // This list is not exhaustive to keep the compiler footprint low.
  142. // The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
  143. // exist.
  144. var NAMED_ENTITIES = {
  145. 'Aacute': '\u00C1',
  146. 'aacute': '\u00E1',
  147. 'Acirc': '\u00C2',
  148. 'acirc': '\u00E2',
  149. 'acute': '\u00B4',
  150. 'AElig': '\u00C6',
  151. 'aelig': '\u00E6',
  152. 'Agrave': '\u00C0',
  153. 'agrave': '\u00E0',
  154. 'alefsym': '\u2135',
  155. 'Alpha': '\u0391',
  156. 'alpha': '\u03B1',
  157. 'amp': '&',
  158. 'and': '\u2227',
  159. 'ang': '\u2220',
  160. 'apos': '\u0027',
  161. 'Aring': '\u00C5',
  162. 'aring': '\u00E5',
  163. 'asymp': '\u2248',
  164. 'Atilde': '\u00C3',
  165. 'atilde': '\u00E3',
  166. 'Auml': '\u00C4',
  167. 'auml': '\u00E4',
  168. 'bdquo': '\u201E',
  169. 'Beta': '\u0392',
  170. 'beta': '\u03B2',
  171. 'brvbar': '\u00A6',
  172. 'bull': '\u2022',
  173. 'cap': '\u2229',
  174. 'Ccedil': '\u00C7',
  175. 'ccedil': '\u00E7',
  176. 'cedil': '\u00B8',
  177. 'cent': '\u00A2',
  178. 'Chi': '\u03A7',
  179. 'chi': '\u03C7',
  180. 'circ': '\u02C6',
  181. 'clubs': '\u2663',
  182. 'cong': '\u2245',
  183. 'copy': '\u00A9',
  184. 'crarr': '\u21B5',
  185. 'cup': '\u222A',
  186. 'curren': '\u00A4',
  187. 'dagger': '\u2020',
  188. 'Dagger': '\u2021',
  189. 'darr': '\u2193',
  190. 'dArr': '\u21D3',
  191. 'deg': '\u00B0',
  192. 'Delta': '\u0394',
  193. 'delta': '\u03B4',
  194. 'diams': '\u2666',
  195. 'divide': '\u00F7',
  196. 'Eacute': '\u00C9',
  197. 'eacute': '\u00E9',
  198. 'Ecirc': '\u00CA',
  199. 'ecirc': '\u00EA',
  200. 'Egrave': '\u00C8',
  201. 'egrave': '\u00E8',
  202. 'empty': '\u2205',
  203. 'emsp': '\u2003',
  204. 'ensp': '\u2002',
  205. 'Epsilon': '\u0395',
  206. 'epsilon': '\u03B5',
  207. 'equiv': '\u2261',
  208. 'Eta': '\u0397',
  209. 'eta': '\u03B7',
  210. 'ETH': '\u00D0',
  211. 'eth': '\u00F0',
  212. 'Euml': '\u00CB',
  213. 'euml': '\u00EB',
  214. 'euro': '\u20AC',
  215. 'exist': '\u2203',
  216. 'fnof': '\u0192',
  217. 'forall': '\u2200',
  218. 'frac12': '\u00BD',
  219. 'frac14': '\u00BC',
  220. 'frac34': '\u00BE',
  221. 'frasl': '\u2044',
  222. 'Gamma': '\u0393',
  223. 'gamma': '\u03B3',
  224. 'ge': '\u2265',
  225. 'gt': '>',
  226. 'harr': '\u2194',
  227. 'hArr': '\u21D4',
  228. 'hearts': '\u2665',
  229. 'hellip': '\u2026',
  230. 'Iacute': '\u00CD',
  231. 'iacute': '\u00ED',
  232. 'Icirc': '\u00CE',
  233. 'icirc': '\u00EE',
  234. 'iexcl': '\u00A1',
  235. 'Igrave': '\u00CC',
  236. 'igrave': '\u00EC',
  237. 'image': '\u2111',
  238. 'infin': '\u221E',
  239. 'int': '\u222B',
  240. 'Iota': '\u0399',
  241. 'iota': '\u03B9',
  242. 'iquest': '\u00BF',
  243. 'isin': '\u2208',
  244. 'Iuml': '\u00CF',
  245. 'iuml': '\u00EF',
  246. 'Kappa': '\u039A',
  247. 'kappa': '\u03BA',
  248. 'Lambda': '\u039B',
  249. 'lambda': '\u03BB',
  250. 'lang': '\u27E8',
  251. 'laquo': '\u00AB',
  252. 'larr': '\u2190',
  253. 'lArr': '\u21D0',
  254. 'lceil': '\u2308',
  255. 'ldquo': '\u201C',
  256. 'le': '\u2264',
  257. 'lfloor': '\u230A',
  258. 'lowast': '\u2217',
  259. 'loz': '\u25CA',
  260. 'lrm': '\u200E',
  261. 'lsaquo': '\u2039',
  262. 'lsquo': '\u2018',
  263. 'lt': '<',
  264. 'macr': '\u00AF',
  265. 'mdash': '\u2014',
  266. 'micro': '\u00B5',
  267. 'middot': '\u00B7',
  268. 'minus': '\u2212',
  269. 'Mu': '\u039C',
  270. 'mu': '\u03BC',
  271. 'nabla': '\u2207',
  272. 'nbsp': '\u00A0',
  273. 'ndash': '\u2013',
  274. 'ne': '\u2260',
  275. 'ni': '\u220B',
  276. 'not': '\u00AC',
  277. 'notin': '\u2209',
  278. 'nsub': '\u2284',
  279. 'Ntilde': '\u00D1',
  280. 'ntilde': '\u00F1',
  281. 'Nu': '\u039D',
  282. 'nu': '\u03BD',
  283. 'Oacute': '\u00D3',
  284. 'oacute': '\u00F3',
  285. 'Ocirc': '\u00D4',
  286. 'ocirc': '\u00F4',
  287. 'OElig': '\u0152',
  288. 'oelig': '\u0153',
  289. 'Ograve': '\u00D2',
  290. 'ograve': '\u00F2',
  291. 'oline': '\u203E',
  292. 'Omega': '\u03A9',
  293. 'omega': '\u03C9',
  294. 'Omicron': '\u039F',
  295. 'omicron': '\u03BF',
  296. 'oplus': '\u2295',
  297. 'or': '\u2228',
  298. 'ordf': '\u00AA',
  299. 'ordm': '\u00BA',
  300. 'Oslash': '\u00D8',
  301. 'oslash': '\u00F8',
  302. 'Otilde': '\u00D5',
  303. 'otilde': '\u00F5',
  304. 'otimes': '\u2297',
  305. 'Ouml': '\u00D6',
  306. 'ouml': '\u00F6',
  307. 'para': '\u00B6',
  308. 'permil': '\u2030',
  309. 'perp': '\u22A5',
  310. 'Phi': '\u03A6',
  311. 'phi': '\u03C6',
  312. 'Pi': '\u03A0',
  313. 'pi': '\u03C0',
  314. 'piv': '\u03D6',
  315. 'plusmn': '\u00B1',
  316. 'pound': '\u00A3',
  317. 'prime': '\u2032',
  318. 'Prime': '\u2033',
  319. 'prod': '\u220F',
  320. 'prop': '\u221D',
  321. 'Psi': '\u03A8',
  322. 'psi': '\u03C8',
  323. 'quot': '\u0022',
  324. 'radic': '\u221A',
  325. 'rang': '\u27E9',
  326. 'raquo': '\u00BB',
  327. 'rarr': '\u2192',
  328. 'rArr': '\u21D2',
  329. 'rceil': '\u2309',
  330. 'rdquo': '\u201D',
  331. 'real': '\u211C',
  332. 'reg': '\u00AE',
  333. 'rfloor': '\u230B',
  334. 'Rho': '\u03A1',
  335. 'rho': '\u03C1',
  336. 'rlm': '\u200F',
  337. 'rsaquo': '\u203A',
  338. 'rsquo': '\u2019',
  339. 'sbquo': '\u201A',
  340. 'Scaron': '\u0160',
  341. 'scaron': '\u0161',
  342. 'sdot': '\u22C5',
  343. 'sect': '\u00A7',
  344. 'shy': '\u00AD',
  345. 'Sigma': '\u03A3',
  346. 'sigma': '\u03C3',
  347. 'sigmaf': '\u03C2',
  348. 'sim': '\u223C',
  349. 'spades': '\u2660',
  350. 'sub': '\u2282',
  351. 'sube': '\u2286',
  352. 'sum': '\u2211',
  353. 'sup': '\u2283',
  354. 'sup1': '\u00B9',
  355. 'sup2': '\u00B2',
  356. 'sup3': '\u00B3',
  357. 'supe': '\u2287',
  358. 'szlig': '\u00DF',
  359. 'Tau': '\u03A4',
  360. 'tau': '\u03C4',
  361. 'there4': '\u2234',
  362. 'Theta': '\u0398',
  363. 'theta': '\u03B8',
  364. 'thetasym': '\u03D1',
  365. 'thinsp': '\u2009',
  366. 'THORN': '\u00DE',
  367. 'thorn': '\u00FE',
  368. 'tilde': '\u02DC',
  369. 'times': '\u00D7',
  370. 'trade': '\u2122',
  371. 'Uacute': '\u00DA',
  372. 'uacute': '\u00FA',
  373. 'uarr': '\u2191',
  374. 'uArr': '\u21D1',
  375. 'Ucirc': '\u00DB',
  376. 'ucirc': '\u00FB',
  377. 'Ugrave': '\u00D9',
  378. 'ugrave': '\u00F9',
  379. 'uml': '\u00A8',
  380. 'upsih': '\u03D2',
  381. 'Upsilon': '\u03A5',
  382. 'upsilon': '\u03C5',
  383. 'Uuml': '\u00DC',
  384. 'uuml': '\u00FC',
  385. 'weierp': '\u2118',
  386. 'Xi': '\u039E',
  387. 'xi': '\u03BE',
  388. 'Yacute': '\u00DD',
  389. 'yacute': '\u00FD',
  390. 'yen': '\u00A5',
  391. 'yuml': '\u00FF',
  392. 'Yuml': '\u0178',
  393. 'Zeta': '\u0396',
  394. 'zeta': '\u03B6',
  395. 'zwj': '\u200D',
  396. 'zwnj': '\u200C',
  397. };
  398. // The &ngsp; pseudo-entity is denoting a space. see:
  399. // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
  400. var NGSP_UNICODE = '\uE500';
  401. NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
  402. /**
  403. * @license
  404. * Copyright Google Inc. All Rights Reserved.
  405. *
  406. * Use of this source code is governed by an MIT-style license that can be
  407. * found in the LICENSE file at https://angular.io/license
  408. */
  409. var HtmlTagDefinition = /** @class */ (function () {
  410. function HtmlTagDefinition(_a) {
  411. var _this = this;
  412. var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? TagContentType.PARSABLE_DATA : _c, _d = _b.closedByParent, closedByParent = _d === void 0 ? false : _d, _e = _b.isVoid, isVoid = _e === void 0 ? false : _e, _f = _b.ignoreFirstLf, ignoreFirstLf = _f === void 0 ? false : _f;
  413. this.closedByChildren = {};
  414. this.closedByParent = false;
  415. this.canSelfClose = false;
  416. if (closedByChildren && closedByChildren.length > 0) {
  417. closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
  418. }
  419. this.isVoid = isVoid;
  420. this.closedByParent = closedByParent || isVoid;
  421. this.implicitNamespacePrefix = implicitNamespacePrefix || null;
  422. this.contentType = contentType;
  423. this.ignoreFirstLf = ignoreFirstLf;
  424. }
  425. HtmlTagDefinition.prototype.isClosedByChild = function (name) {
  426. return this.isVoid || name.toLowerCase() in this.closedByChildren;
  427. };
  428. return HtmlTagDefinition;
  429. }());
  430. var _DEFAULT_TAG_DEFINITION;
  431. // see http://www.w3.org/TR/html51/syntax.html#optional-tags
  432. // This implementation does not fully conform to the HTML5 spec.
  433. var TAG_DEFINITIONS;
  434. function getHtmlTagDefinition(tagName) {
  435. if (!TAG_DEFINITIONS) {
  436. _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
  437. TAG_DEFINITIONS = {
  438. 'base': new HtmlTagDefinition({ isVoid: true }),
  439. 'meta': new HtmlTagDefinition({ isVoid: true }),
  440. 'area': new HtmlTagDefinition({ isVoid: true }),
  441. 'embed': new HtmlTagDefinition({ isVoid: true }),
  442. 'link': new HtmlTagDefinition({ isVoid: true }),
  443. 'img': new HtmlTagDefinition({ isVoid: true }),
  444. 'input': new HtmlTagDefinition({ isVoid: true }),
  445. 'param': new HtmlTagDefinition({ isVoid: true }),
  446. 'hr': new HtmlTagDefinition({ isVoid: true }),
  447. 'br': new HtmlTagDefinition({ isVoid: true }),
  448. 'source': new HtmlTagDefinition({ isVoid: true }),
  449. 'track': new HtmlTagDefinition({ isVoid: true }),
  450. 'wbr': new HtmlTagDefinition({ isVoid: true }),
  451. 'p': new HtmlTagDefinition({
  452. closedByChildren: [
  453. 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
  454. 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
  455. 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
  456. 'p', 'pre', 'section', 'table', 'ul'
  457. ],
  458. closedByParent: true
  459. }),
  460. 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
  461. 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
  462. 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
  463. 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
  464. 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  465. 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  466. 'col': new HtmlTagDefinition({ isVoid: true }),
  467. 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
  468. 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
  469. 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
  470. 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
  471. 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
  472. 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  473. 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  474. 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
  475. 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  476. 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
  477. 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
  478. 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
  479. 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
  480. 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
  481. 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
  482. 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }),
  483. 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
  484. };
  485. }
  486. return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION;
  487. }
  488. /**
  489. * @license
  490. * Copyright Google Inc. All Rights Reserved.
  491. *
  492. * Use of this source code is governed by an MIT-style license that can be
  493. * found in the LICENSE file at https://angular.io/license
  494. */
  495. var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + //":not("
  496. '([-\\w]+)|' + // "tag"
  497. '(?:\\.([-\\w]+))|' + // ".class"
  498. // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
  499. '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
  500. // "[name="value"]",
  501. // "[name='value']"
  502. '(\\))|' + // ")"
  503. '(\\s*,\\s*)', // ","
  504. 'g');
  505. /**
  506. * A css selector contains an element name,
  507. * css classes and attribute/value pairs with the purpose
  508. * of selecting subsets out of them.
  509. */
  510. var CssSelector = /** @class */ (function () {
  511. function CssSelector() {
  512. this.element = null;
  513. this.classNames = [];
  514. /**
  515. * The selectors are encoded in pairs where:
  516. * - even locations are attribute names
  517. * - odd locations are attribute values.
  518. *
  519. * Example:
  520. * Selector: `[key1=value1][key2]` would parse to:
  521. * ```
  522. * ['key1', 'value1', 'key2', '']
  523. * ```
  524. */
  525. this.attrs = [];
  526. this.notSelectors = [];
  527. }
  528. CssSelector.parse = function (selector) {
  529. var results = [];
  530. var _addResult = function (res, cssSel) {
  531. if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
  532. cssSel.attrs.length == 0) {
  533. cssSel.element = '*';
  534. }
  535. res.push(cssSel);
  536. };
  537. var cssSelector = new CssSelector();
  538. var match;
  539. var current = cssSelector;
  540. var inNot = false;
  541. _SELECTOR_REGEXP.lastIndex = 0;
  542. while (match = _SELECTOR_REGEXP.exec(selector)) {
  543. if (match[1]) {
  544. if (inNot) {
  545. throw new Error('Nesting :not is not allowed in a selector');
  546. }
  547. inNot = true;
  548. current = new CssSelector();
  549. cssSelector.notSelectors.push(current);
  550. }
  551. if (match[2]) {
  552. current.setElement(match[2]);
  553. }
  554. if (match[3]) {
  555. current.addClassName(match[3]);
  556. }
  557. if (match[4]) {
  558. current.addAttribute(match[4], match[6]);
  559. }
  560. if (match[7]) {
  561. inNot = false;
  562. current = cssSelector;
  563. }
  564. if (match[8]) {
  565. if (inNot) {
  566. throw new Error('Multiple selectors in :not are not supported');
  567. }
  568. _addResult(results, cssSelector);
  569. cssSelector = current = new CssSelector();
  570. }
  571. }
  572. _addResult(results, cssSelector);
  573. return results;
  574. };
  575. CssSelector.prototype.isElementSelector = function () {
  576. return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
  577. this.notSelectors.length === 0;
  578. };
  579. CssSelector.prototype.hasElementSelector = function () { return !!this.element; };
  580. CssSelector.prototype.setElement = function (element) {
  581. if (element === void 0) { element = null; }
  582. this.element = element;
  583. };
  584. /** Gets a template string for an element that matches the selector. */
  585. CssSelector.prototype.getMatchingElementTemplate = function () {
  586. var tagName = this.element || 'div';
  587. var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
  588. var attrs = '';
  589. for (var i = 0; i < this.attrs.length; i += 2) {
  590. var attrName = this.attrs[i];
  591. var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
  592. attrs += " " + attrName + attrValue;
  593. }
  594. return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
  595. "<" + tagName + classAttr + attrs + "></" + tagName + ">";
  596. };
  597. CssSelector.prototype.getAttrs = function () {
  598. var result = [];
  599. if (this.classNames.length > 0) {
  600. result.push('class', this.classNames.join(' '));
  601. }
  602. return result.concat(this.attrs);
  603. };
  604. CssSelector.prototype.addAttribute = function (name, value) {
  605. if (value === void 0) { value = ''; }
  606. this.attrs.push(name, value && value.toLowerCase() || '');
  607. };
  608. CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
  609. CssSelector.prototype.toString = function () {
  610. var res = this.element || '';
  611. if (this.classNames) {
  612. this.classNames.forEach(function (klass) { return res += "." + klass; });
  613. }
  614. if (this.attrs) {
  615. for (var i = 0; i < this.attrs.length; i += 2) {
  616. var name_1 = this.attrs[i];
  617. var value = this.attrs[i + 1];
  618. res += "[" + name_1 + (value ? '=' + value : '') + "]";
  619. }
  620. }
  621. this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
  622. return res;
  623. };
  624. return CssSelector;
  625. }());
  626. /**
  627. * Reads a list of CssSelectors and allows to calculate which ones
  628. * are contained in a given CssSelector.
  629. */
  630. var SelectorMatcher = /** @class */ (function () {
  631. function SelectorMatcher() {
  632. this._elementMap = new Map();
  633. this._elementPartialMap = new Map();
  634. this._classMap = new Map();
  635. this._classPartialMap = new Map();
  636. this._attrValueMap = new Map();
  637. this._attrValuePartialMap = new Map();
  638. this._listContexts = [];
  639. }
  640. SelectorMatcher.createNotMatcher = function (notSelectors) {
  641. var notMatcher = new SelectorMatcher();
  642. notMatcher.addSelectables(notSelectors, null);
  643. return notMatcher;
  644. };
  645. SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
  646. var listContext = null;
  647. if (cssSelectors.length > 1) {
  648. listContext = new SelectorListContext(cssSelectors);
  649. this._listContexts.push(listContext);
  650. }
  651. for (var i = 0; i < cssSelectors.length; i++) {
  652. this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
  653. }
  654. };
  655. /**
  656. * Add an object that can be found later on by calling `match`.
  657. * @param cssSelector A css selector
  658. * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
  659. */
  660. SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
  661. var matcher = this;
  662. var element = cssSelector.element;
  663. var classNames = cssSelector.classNames;
  664. var attrs = cssSelector.attrs;
  665. var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
  666. if (element) {
  667. var isTerminal = attrs.length === 0 && classNames.length === 0;
  668. if (isTerminal) {
  669. this._addTerminal(matcher._elementMap, element, selectable);
  670. }
  671. else {
  672. matcher = this._addPartial(matcher._elementPartialMap, element);
  673. }
  674. }
  675. if (classNames) {
  676. for (var i = 0; i < classNames.length; i++) {
  677. var isTerminal = attrs.length === 0 && i === classNames.length - 1;
  678. var className = classNames[i];
  679. if (isTerminal) {
  680. this._addTerminal(matcher._classMap, className, selectable);
  681. }
  682. else {
  683. matcher = this._addPartial(matcher._classPartialMap, className);
  684. }
  685. }
  686. }
  687. if (attrs) {
  688. for (var i = 0; i < attrs.length; i += 2) {
  689. var isTerminal = i === attrs.length - 2;
  690. var name_2 = attrs[i];
  691. var value = attrs[i + 1];
  692. if (isTerminal) {
  693. var terminalMap = matcher._attrValueMap;
  694. var terminalValuesMap = terminalMap.get(name_2);
  695. if (!terminalValuesMap) {
  696. terminalValuesMap = new Map();
  697. terminalMap.set(name_2, terminalValuesMap);
  698. }
  699. this._addTerminal(terminalValuesMap, value, selectable);
  700. }
  701. else {
  702. var partialMap = matcher._attrValuePartialMap;
  703. var partialValuesMap = partialMap.get(name_2);
  704. if (!partialValuesMap) {
  705. partialValuesMap = new Map();
  706. partialMap.set(name_2, partialValuesMap);
  707. }
  708. matcher = this._addPartial(partialValuesMap, value);
  709. }
  710. }
  711. }
  712. };
  713. SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
  714. var terminalList = map.get(name);
  715. if (!terminalList) {
  716. terminalList = [];
  717. map.set(name, terminalList);
  718. }
  719. terminalList.push(selectable);
  720. };
  721. SelectorMatcher.prototype._addPartial = function (map, name) {
  722. var matcher = map.get(name);
  723. if (!matcher) {
  724. matcher = new SelectorMatcher();
  725. map.set(name, matcher);
  726. }
  727. return matcher;
  728. };
  729. /**
  730. * Find the objects that have been added via `addSelectable`
  731. * whose css selector is contained in the given css selector.
  732. * @param cssSelector A css selector
  733. * @param matchedCallback This callback will be called with the object handed into `addSelectable`
  734. * @return boolean true if a match was found
  735. */
  736. SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
  737. var result = false;
  738. var element = cssSelector.element;
  739. var classNames = cssSelector.classNames;
  740. var attrs = cssSelector.attrs;
  741. for (var i = 0; i < this._listContexts.length; i++) {
  742. this._listContexts[i].alreadyMatched = false;
  743. }
  744. result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
  745. result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
  746. result;
  747. if (classNames) {
  748. for (var i = 0; i < classNames.length; i++) {
  749. var className = classNames[i];
  750. result =
  751. this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
  752. result =
  753. this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
  754. result;
  755. }
  756. }
  757. if (attrs) {
  758. for (var i = 0; i < attrs.length; i += 2) {
  759. var name_3 = attrs[i];
  760. var value = attrs[i + 1];
  761. var terminalValuesMap = this._attrValueMap.get(name_3);
  762. if (value) {
  763. result =
  764. this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
  765. }
  766. result =
  767. this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
  768. var partialValuesMap = this._attrValuePartialMap.get(name_3);
  769. if (value) {
  770. result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
  771. }
  772. result =
  773. this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
  774. }
  775. }
  776. return result;
  777. };
  778. /** @internal */
  779. SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
  780. if (!map || typeof name !== 'string') {
  781. return false;
  782. }
  783. var selectables = map.get(name) || [];
  784. var starSelectables = map.get('*');
  785. if (starSelectables) {
  786. selectables = selectables.concat(starSelectables);
  787. }
  788. if (selectables.length === 0) {
  789. return false;
  790. }
  791. var selectable;
  792. var result = false;
  793. for (var i = 0; i < selectables.length; i++) {
  794. selectable = selectables[i];
  795. result = selectable.finalize(cssSelector, matchedCallback) || result;
  796. }
  797. return result;
  798. };
  799. /** @internal */
  800. SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
  801. if (!map || typeof name !== 'string') {
  802. return false;
  803. }
  804. var nestedSelector = map.get(name);
  805. if (!nestedSelector) {
  806. return false;
  807. }
  808. // TODO(perf): get rid of recursion and measure again
  809. // TODO(perf): don't pass the whole selector into the recursion,
  810. // but only the not processed parts
  811. return nestedSelector.match(cssSelector, matchedCallback);
  812. };
  813. return SelectorMatcher;
  814. }());
  815. var SelectorListContext = /** @class */ (function () {
  816. function SelectorListContext(selectors) {
  817. this.selectors = selectors;
  818. this.alreadyMatched = false;
  819. }
  820. return SelectorListContext;
  821. }());
  822. // Store context to pass back selector and context when a selector is matched
  823. var SelectorContext = /** @class */ (function () {
  824. function SelectorContext(selector, cbContext, listContext) {
  825. this.selector = selector;
  826. this.cbContext = cbContext;
  827. this.listContext = listContext;
  828. this.notSelectors = selector.notSelectors;
  829. }
  830. SelectorContext.prototype.finalize = function (cssSelector, callback) {
  831. var result = true;
  832. if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
  833. var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
  834. result = !notMatcher.match(cssSelector, null);
  835. }
  836. if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
  837. if (this.listContext) {
  838. this.listContext.alreadyMatched = true;
  839. }
  840. callback(this.selector, this.cbContext);
  841. }
  842. return result;
  843. };
  844. return SelectorContext;
  845. }());
  846. /**
  847. * @license
  848. * Copyright Google Inc. All Rights Reserved.
  849. *
  850. * Use of this source code is governed by an MIT-style license that can be
  851. * found in the LICENSE file at https://angular.io/license
  852. */
  853. var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); });
  854. var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ngInjectableDef: undefined }); });
  855. var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); });
  856. var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) {
  857. if (data === void 0) { data = {}; }
  858. return (__assign({ selector: selector, first: false, isViewQuery: false, descendants: false }, data));
  859. });
  860. var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) {
  861. if (data === void 0) { data = {}; }
  862. return (__assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data));
  863. });
  864. var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) {
  865. if (data === void 0) { data = {}; }
  866. return (__assign({ selector: selector, first: false, isViewQuery: true, descendants: true }, data));
  867. });
  868. var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) {
  869. return (__assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data));
  870. });
  871. var createDirective = makeMetadataFactory('Directive', function (dir) {
  872. if (dir === void 0) { dir = {}; }
  873. return dir;
  874. });
  875. var ViewEncapsulation;
  876. (function (ViewEncapsulation) {
  877. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  878. ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
  879. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  880. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  881. })(ViewEncapsulation || (ViewEncapsulation = {}));
  882. var ChangeDetectionStrategy;
  883. (function (ChangeDetectionStrategy) {
  884. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  885. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  886. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  887. var createComponent = makeMetadataFactory('Component', function (c) {
  888. if (c === void 0) { c = {}; }
  889. return (__assign({ changeDetection: ChangeDetectionStrategy.Default }, c));
  890. });
  891. var createPipe = makeMetadataFactory('Pipe', function (p) { return (__assign({ pure: true }, p)); });
  892. var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  893. var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  894. var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); });
  895. var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); });
  896. var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; });
  897. var createInjectable = makeMetadataFactory('Injectable', function (injectable) {
  898. if (injectable === void 0) { injectable = {}; }
  899. return injectable;
  900. });
  901. var CUSTOM_ELEMENTS_SCHEMA = {
  902. name: 'custom-elements'
  903. };
  904. var NO_ERRORS_SCHEMA = {
  905. name: 'no-errors-schema'
  906. };
  907. var createOptional = makeMetadataFactory('Optional');
  908. var createSelf = makeMetadataFactory('Self');
  909. var createSkipSelf = makeMetadataFactory('SkipSelf');
  910. var createHost = makeMetadataFactory('Host');
  911. var Type = Function;
  912. var SecurityContext;
  913. (function (SecurityContext) {
  914. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  915. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  916. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  917. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  918. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  919. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  920. })(SecurityContext || (SecurityContext = {}));
  921. var MissingTranslationStrategy;
  922. (function (MissingTranslationStrategy) {
  923. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  924. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  925. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  926. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  927. function makeMetadataFactory(name, props) {
  928. // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
  929. // that works with the static_reflector.ts in the ViewEngine compiler.
  930. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
  931. // new'ed.
  932. function factory() {
  933. var args = [];
  934. for (var _i = 0; _i < arguments.length; _i++) {
  935. args[_i] = arguments[_i];
  936. }
  937. var values = props ? props.apply(void 0, __spread(args)) : {};
  938. return __assign({ ngMetadataName: name }, values);
  939. }
  940. factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; };
  941. factory.ngMetadataName = name;
  942. return factory;
  943. }
  944. function parserSelectorToSimpleSelector(selector) {
  945. var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
  946. [];
  947. var elementName = selector.element && selector.element !== '*' ? selector.element : '';
  948. return __spread([elementName], selector.attrs, classes);
  949. }
  950. function parserSelectorToNegativeSelector(selector) {
  951. var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
  952. [];
  953. if (selector.element) {
  954. return __spread([
  955. 1 /* NOT */ | 4 /* ELEMENT */, selector.element
  956. ], selector.attrs, classes);
  957. }
  958. else if (selector.attrs.length) {
  959. return __spread([1 /* NOT */ | 2 /* ATTRIBUTE */], selector.attrs, classes);
  960. }
  961. else {
  962. return selector.classNames && selector.classNames.length ? __spread([1 /* NOT */ | 8 /* CLASS */], selector.classNames) :
  963. [];
  964. }
  965. }
  966. function parserSelectorToR3Selector(selector) {
  967. var positive = parserSelectorToSimpleSelector(selector);
  968. var negative = selector.notSelectors && selector.notSelectors.length ?
  969. selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) :
  970. [];
  971. return positive.concat.apply(positive, __spread(negative));
  972. }
  973. function parseSelectorToR3Selector(selector) {
  974. return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
  975. }
  976. /**
  977. * @license
  978. * Copyright Google Inc. All Rights Reserved.
  979. *
  980. * Use of this source code is governed by an MIT-style license that can be
  981. * found in the LICENSE file at https://angular.io/license
  982. */
  983. //// Types
  984. var TypeModifier;
  985. (function (TypeModifier) {
  986. TypeModifier[TypeModifier["Const"] = 0] = "Const";
  987. })(TypeModifier || (TypeModifier = {}));
  988. var Type$1 = /** @class */ (function () {
  989. function Type(modifiers) {
  990. if (modifiers === void 0) { modifiers = null; }
  991. this.modifiers = modifiers;
  992. if (!modifiers) {
  993. this.modifiers = [];
  994. }
  995. }
  996. Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  997. return Type;
  998. }());
  999. var BuiltinTypeName;
  1000. (function (BuiltinTypeName) {
  1001. BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
  1002. BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
  1003. BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
  1004. BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
  1005. BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
  1006. BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
  1007. BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
  1008. BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None";
  1009. })(BuiltinTypeName || (BuiltinTypeName = {}));
  1010. var BuiltinType = /** @class */ (function (_super) {
  1011. __extends(BuiltinType, _super);
  1012. function BuiltinType(name, modifiers) {
  1013. if (modifiers === void 0) { modifiers = null; }
  1014. var _this = _super.call(this, modifiers) || this;
  1015. _this.name = name;
  1016. return _this;
  1017. }
  1018. BuiltinType.prototype.visitType = function (visitor, context) {
  1019. return visitor.visitBuiltinType(this, context);
  1020. };
  1021. return BuiltinType;
  1022. }(Type$1));
  1023. var ExpressionType = /** @class */ (function (_super) {
  1024. __extends(ExpressionType, _super);
  1025. function ExpressionType(value, modifiers, typeParams) {
  1026. if (modifiers === void 0) { modifiers = null; }
  1027. if (typeParams === void 0) { typeParams = null; }
  1028. var _this = _super.call(this, modifiers) || this;
  1029. _this.value = value;
  1030. _this.typeParams = typeParams;
  1031. return _this;
  1032. }
  1033. ExpressionType.prototype.visitType = function (visitor, context) {
  1034. return visitor.visitExpressionType(this, context);
  1035. };
  1036. return ExpressionType;
  1037. }(Type$1));
  1038. var ArrayType = /** @class */ (function (_super) {
  1039. __extends(ArrayType, _super);
  1040. function ArrayType(of, modifiers) {
  1041. if (modifiers === void 0) { modifiers = null; }
  1042. var _this = _super.call(this, modifiers) || this;
  1043. _this.of = of;
  1044. return _this;
  1045. }
  1046. ArrayType.prototype.visitType = function (visitor, context) {
  1047. return visitor.visitArrayType(this, context);
  1048. };
  1049. return ArrayType;
  1050. }(Type$1));
  1051. var MapType = /** @class */ (function (_super) {
  1052. __extends(MapType, _super);
  1053. function MapType(valueType, modifiers) {
  1054. if (modifiers === void 0) { modifiers = null; }
  1055. var _this = _super.call(this, modifiers) || this;
  1056. _this.valueType = valueType || null;
  1057. return _this;
  1058. }
  1059. MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); };
  1060. return MapType;
  1061. }(Type$1));
  1062. var DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
  1063. var INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
  1064. var BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
  1065. var INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
  1066. var NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
  1067. var STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
  1068. var FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
  1069. var NONE_TYPE = new BuiltinType(BuiltinTypeName.None);
  1070. ///// Expressions
  1071. var BinaryOperator;
  1072. (function (BinaryOperator) {
  1073. BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
  1074. BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
  1075. BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
  1076. BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
  1077. BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
  1078. BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
  1079. BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
  1080. BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
  1081. BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
  1082. BinaryOperator[BinaryOperator["And"] = 9] = "And";
  1083. BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
  1084. BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
  1085. BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
  1086. BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
  1087. BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
  1088. BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
  1089. })(BinaryOperator || (BinaryOperator = {}));
  1090. function nullSafeIsEquivalent(base, other) {
  1091. if (base == null || other == null) {
  1092. return base == other;
  1093. }
  1094. return base.isEquivalent(other);
  1095. }
  1096. function areAllEquivalent(base, other) {
  1097. var len = base.length;
  1098. if (len !== other.length) {
  1099. return false;
  1100. }
  1101. for (var i = 0; i < len; i++) {
  1102. if (!base[i].isEquivalent(other[i])) {
  1103. return false;
  1104. }
  1105. }
  1106. return true;
  1107. }
  1108. var Expression = /** @class */ (function () {
  1109. function Expression(type, sourceSpan) {
  1110. this.type = type || null;
  1111. this.sourceSpan = sourceSpan || null;
  1112. }
  1113. Expression.prototype.prop = function (name, sourceSpan) {
  1114. return new ReadPropExpr(this, name, null, sourceSpan);
  1115. };
  1116. Expression.prototype.key = function (index, type, sourceSpan) {
  1117. return new ReadKeyExpr(this, index, type, sourceSpan);
  1118. };
  1119. Expression.prototype.callMethod = function (name, params, sourceSpan) {
  1120. return new InvokeMethodExpr(this, name, params, null, sourceSpan);
  1121. };
  1122. Expression.prototype.callFn = function (params, sourceSpan) {
  1123. return new InvokeFunctionExpr(this, params, null, sourceSpan);
  1124. };
  1125. Expression.prototype.instantiate = function (params, type, sourceSpan) {
  1126. return new InstantiateExpr(this, params, type, sourceSpan);
  1127. };
  1128. Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
  1129. if (falseCase === void 0) { falseCase = null; }
  1130. return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
  1131. };
  1132. Expression.prototype.equals = function (rhs, sourceSpan) {
  1133. return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
  1134. };
  1135. Expression.prototype.notEquals = function (rhs, sourceSpan) {
  1136. return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
  1137. };
  1138. Expression.prototype.identical = function (rhs, sourceSpan) {
  1139. return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
  1140. };
  1141. Expression.prototype.notIdentical = function (rhs, sourceSpan) {
  1142. return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
  1143. };
  1144. Expression.prototype.minus = function (rhs, sourceSpan) {
  1145. return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
  1146. };
  1147. Expression.prototype.plus = function (rhs, sourceSpan) {
  1148. return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
  1149. };
  1150. Expression.prototype.divide = function (rhs, sourceSpan) {
  1151. return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
  1152. };
  1153. Expression.prototype.multiply = function (rhs, sourceSpan) {
  1154. return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
  1155. };
  1156. Expression.prototype.modulo = function (rhs, sourceSpan) {
  1157. return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
  1158. };
  1159. Expression.prototype.and = function (rhs, sourceSpan) {
  1160. return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
  1161. };
  1162. Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) {
  1163. if (parens === void 0) { parens = true; }
  1164. return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
  1165. };
  1166. Expression.prototype.or = function (rhs, sourceSpan) {
  1167. return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
  1168. };
  1169. Expression.prototype.lower = function (rhs, sourceSpan) {
  1170. return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
  1171. };
  1172. Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
  1173. return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
  1174. };
  1175. Expression.prototype.bigger = function (rhs, sourceSpan) {
  1176. return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
  1177. };
  1178. Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
  1179. return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
  1180. };
  1181. Expression.prototype.isBlank = function (sourceSpan) {
  1182. // Note: We use equals by purpose here to compare to null and undefined in JS.
  1183. // We use the typed null to allow strictNullChecks to narrow types.
  1184. return this.equals(TYPED_NULL_EXPR, sourceSpan);
  1185. };
  1186. Expression.prototype.cast = function (type, sourceSpan) {
  1187. return new CastExpr(this, type, sourceSpan);
  1188. };
  1189. Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); };
  1190. return Expression;
  1191. }());
  1192. var BuiltinVar;
  1193. (function (BuiltinVar) {
  1194. BuiltinVar[BuiltinVar["This"] = 0] = "This";
  1195. BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
  1196. BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
  1197. BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
  1198. })(BuiltinVar || (BuiltinVar = {}));
  1199. var ReadVarExpr = /** @class */ (function (_super) {
  1200. __extends(ReadVarExpr, _super);
  1201. function ReadVarExpr(name, type, sourceSpan) {
  1202. var _this = _super.call(this, type, sourceSpan) || this;
  1203. if (typeof name === 'string') {
  1204. _this.name = name;
  1205. _this.builtin = null;
  1206. }
  1207. else {
  1208. _this.name = null;
  1209. _this.builtin = name;
  1210. }
  1211. return _this;
  1212. }
  1213. ReadVarExpr.prototype.isEquivalent = function (e) {
  1214. return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
  1215. };
  1216. ReadVarExpr.prototype.isConstant = function () { return false; };
  1217. ReadVarExpr.prototype.visitExpression = function (visitor, context) {
  1218. return visitor.visitReadVarExpr(this, context);
  1219. };
  1220. ReadVarExpr.prototype.set = function (value) {
  1221. if (!this.name) {
  1222. throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
  1223. }
  1224. return new WriteVarExpr(this.name, value, null, this.sourceSpan);
  1225. };
  1226. return ReadVarExpr;
  1227. }(Expression));
  1228. var TypeofExpr = /** @class */ (function (_super) {
  1229. __extends(TypeofExpr, _super);
  1230. function TypeofExpr(expr, type, sourceSpan) {
  1231. var _this = _super.call(this, type, sourceSpan) || this;
  1232. _this.expr = expr;
  1233. return _this;
  1234. }
  1235. TypeofExpr.prototype.visitExpression = function (visitor, context) {
  1236. return visitor.visitTypeofExpr(this, context);
  1237. };
  1238. TypeofExpr.prototype.isEquivalent = function (e) {
  1239. return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
  1240. };
  1241. TypeofExpr.prototype.isConstant = function () { return this.expr.isConstant(); };
  1242. return TypeofExpr;
  1243. }(Expression));
  1244. var WrappedNodeExpr = /** @class */ (function (_super) {
  1245. __extends(WrappedNodeExpr, _super);
  1246. function WrappedNodeExpr(node, type, sourceSpan) {
  1247. var _this = _super.call(this, type, sourceSpan) || this;
  1248. _this.node = node;
  1249. return _this;
  1250. }
  1251. WrappedNodeExpr.prototype.isEquivalent = function (e) {
  1252. return e instanceof WrappedNodeExpr && this.node === e.node;
  1253. };
  1254. WrappedNodeExpr.prototype.isConstant = function () { return false; };
  1255. WrappedNodeExpr.prototype.visitExpression = function (visitor, context) {
  1256. return visitor.visitWrappedNodeExpr(this, context);
  1257. };
  1258. return WrappedNodeExpr;
  1259. }(Expression));
  1260. var WriteVarExpr = /** @class */ (function (_super) {
  1261. __extends(WriteVarExpr, _super);
  1262. function WriteVarExpr(name, value, type, sourceSpan) {
  1263. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1264. _this.name = name;
  1265. _this.value = value;
  1266. return _this;
  1267. }
  1268. WriteVarExpr.prototype.isEquivalent = function (e) {
  1269. return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
  1270. };
  1271. WriteVarExpr.prototype.isConstant = function () { return false; };
  1272. WriteVarExpr.prototype.visitExpression = function (visitor, context) {
  1273. return visitor.visitWriteVarExpr(this, context);
  1274. };
  1275. WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
  1276. return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
  1277. };
  1278. WriteVarExpr.prototype.toConstDecl = function () { return this.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]); };
  1279. return WriteVarExpr;
  1280. }(Expression));
  1281. var WriteKeyExpr = /** @class */ (function (_super) {
  1282. __extends(WriteKeyExpr, _super);
  1283. function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
  1284. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1285. _this.receiver = receiver;
  1286. _this.index = index;
  1287. _this.value = value;
  1288. return _this;
  1289. }
  1290. WriteKeyExpr.prototype.isEquivalent = function (e) {
  1291. return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1292. this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
  1293. };
  1294. WriteKeyExpr.prototype.isConstant = function () { return false; };
  1295. WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
  1296. return visitor.visitWriteKeyExpr(this, context);
  1297. };
  1298. return WriteKeyExpr;
  1299. }(Expression));
  1300. var WritePropExpr = /** @class */ (function (_super) {
  1301. __extends(WritePropExpr, _super);
  1302. function WritePropExpr(receiver, name, value, type, sourceSpan) {
  1303. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1304. _this.receiver = receiver;
  1305. _this.name = name;
  1306. _this.value = value;
  1307. return _this;
  1308. }
  1309. WritePropExpr.prototype.isEquivalent = function (e) {
  1310. return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
  1311. this.name === e.name && this.value.isEquivalent(e.value);
  1312. };
  1313. WritePropExpr.prototype.isConstant = function () { return false; };
  1314. WritePropExpr.prototype.visitExpression = function (visitor, context) {
  1315. return visitor.visitWritePropExpr(this, context);
  1316. };
  1317. return WritePropExpr;
  1318. }(Expression));
  1319. var BuiltinMethod;
  1320. (function (BuiltinMethod) {
  1321. BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
  1322. BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
  1323. BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
  1324. })(BuiltinMethod || (BuiltinMethod = {}));
  1325. var InvokeMethodExpr = /** @class */ (function (_super) {
  1326. __extends(InvokeMethodExpr, _super);
  1327. function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
  1328. var _this = _super.call(this, type, sourceSpan) || this;
  1329. _this.receiver = receiver;
  1330. _this.args = args;
  1331. if (typeof method === 'string') {
  1332. _this.name = method;
  1333. _this.builtin = null;
  1334. }
  1335. else {
  1336. _this.name = null;
  1337. _this.builtin = method;
  1338. }
  1339. return _this;
  1340. }
  1341. InvokeMethodExpr.prototype.isEquivalent = function (e) {
  1342. return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
  1343. this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
  1344. };
  1345. InvokeMethodExpr.prototype.isConstant = function () { return false; };
  1346. InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
  1347. return visitor.visitInvokeMethodExpr(this, context);
  1348. };
  1349. return InvokeMethodExpr;
  1350. }(Expression));
  1351. var InvokeFunctionExpr = /** @class */ (function (_super) {
  1352. __extends(InvokeFunctionExpr, _super);
  1353. function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) {
  1354. if (pure === void 0) { pure = false; }
  1355. var _this = _super.call(this, type, sourceSpan) || this;
  1356. _this.fn = fn;
  1357. _this.args = args;
  1358. _this.pure = pure;
  1359. return _this;
  1360. }
  1361. InvokeFunctionExpr.prototype.isEquivalent = function (e) {
  1362. return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
  1363. areAllEquivalent(this.args, e.args) && this.pure === e.pure;
  1364. };
  1365. InvokeFunctionExpr.prototype.isConstant = function () { return false; };
  1366. InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
  1367. return visitor.visitInvokeFunctionExpr(this, context);
  1368. };
  1369. return InvokeFunctionExpr;
  1370. }(Expression));
  1371. var InstantiateExpr = /** @class */ (function (_super) {
  1372. __extends(InstantiateExpr, _super);
  1373. function InstantiateExpr(classExpr, args, type, sourceSpan) {
  1374. var _this = _super.call(this, type, sourceSpan) || this;
  1375. _this.classExpr = classExpr;
  1376. _this.args = args;
  1377. return _this;
  1378. }
  1379. InstantiateExpr.prototype.isEquivalent = function (e) {
  1380. return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
  1381. areAllEquivalent(this.args, e.args);
  1382. };
  1383. InstantiateExpr.prototype.isConstant = function () { return false; };
  1384. InstantiateExpr.prototype.visitExpression = function (visitor, context) {
  1385. return visitor.visitInstantiateExpr(this, context);
  1386. };
  1387. return InstantiateExpr;
  1388. }(Expression));
  1389. var LiteralExpr = /** @class */ (function (_super) {
  1390. __extends(LiteralExpr, _super);
  1391. function LiteralExpr(value, type, sourceSpan) {
  1392. var _this = _super.call(this, type, sourceSpan) || this;
  1393. _this.value = value;
  1394. return _this;
  1395. }
  1396. LiteralExpr.prototype.isEquivalent = function (e) {
  1397. return e instanceof LiteralExpr && this.value === e.value;
  1398. };
  1399. LiteralExpr.prototype.isConstant = function () { return true; };
  1400. LiteralExpr.prototype.visitExpression = function (visitor, context) {
  1401. return visitor.visitLiteralExpr(this, context);
  1402. };
  1403. return LiteralExpr;
  1404. }(Expression));
  1405. var ExternalExpr = /** @class */ (function (_super) {
  1406. __extends(ExternalExpr, _super);
  1407. function ExternalExpr(value, type, typeParams, sourceSpan) {
  1408. if (typeParams === void 0) { typeParams = null; }
  1409. var _this = _super.call(this, type, sourceSpan) || this;
  1410. _this.value = value;
  1411. _this.typeParams = typeParams;
  1412. return _this;
  1413. }
  1414. ExternalExpr.prototype.isEquivalent = function (e) {
  1415. return e instanceof ExternalExpr && this.value.name === e.value.name &&
  1416. this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
  1417. };
  1418. ExternalExpr.prototype.isConstant = function () { return false; };
  1419. ExternalExpr.prototype.visitExpression = function (visitor, context) {
  1420. return visitor.visitExternalExpr(this, context);
  1421. };
  1422. return ExternalExpr;
  1423. }(Expression));
  1424. var ConditionalExpr = /** @class */ (function (_super) {
  1425. __extends(ConditionalExpr, _super);
  1426. function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
  1427. if (falseCase === void 0) { falseCase = null; }
  1428. var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
  1429. _this.condition = condition;
  1430. _this.falseCase = falseCase;
  1431. _this.trueCase = trueCase;
  1432. return _this;
  1433. }
  1434. ConditionalExpr.prototype.isEquivalent = function (e) {
  1435. return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
  1436. this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
  1437. };
  1438. ConditionalExpr.prototype.isConstant = function () { return false; };
  1439. ConditionalExpr.prototype.visitExpression = function (visitor, context) {
  1440. return visitor.visitConditionalExpr(this, context);
  1441. };
  1442. return ConditionalExpr;
  1443. }(Expression));
  1444. var NotExpr = /** @class */ (function (_super) {
  1445. __extends(NotExpr, _super);
  1446. function NotExpr(condition, sourceSpan) {
  1447. var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
  1448. _this.condition = condition;
  1449. return _this;
  1450. }
  1451. NotExpr.prototype.isEquivalent = function (e) {
  1452. return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
  1453. };
  1454. NotExpr.prototype.isConstant = function () { return false; };
  1455. NotExpr.prototype.visitExpression = function (visitor, context) {
  1456. return visitor.visitNotExpr(this, context);
  1457. };
  1458. return NotExpr;
  1459. }(Expression));
  1460. var AssertNotNull = /** @class */ (function (_super) {
  1461. __extends(AssertNotNull, _super);
  1462. function AssertNotNull(condition, sourceSpan) {
  1463. var _this = _super.call(this, condition.type, sourceSpan) || this;
  1464. _this.condition = condition;
  1465. return _this;
  1466. }
  1467. AssertNotNull.prototype.isEquivalent = function (e) {
  1468. return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
  1469. };
  1470. AssertNotNull.prototype.isConstant = function () { return false; };
  1471. AssertNotNull.prototype.visitExpression = function (visitor, context) {
  1472. return visitor.visitAssertNotNullExpr(this, context);
  1473. };
  1474. return AssertNotNull;
  1475. }(Expression));
  1476. var CastExpr = /** @class */ (function (_super) {
  1477. __extends(CastExpr, _super);
  1478. function CastExpr(value, type, sourceSpan) {
  1479. var _this = _super.call(this, type, sourceSpan) || this;
  1480. _this.value = value;
  1481. return _this;
  1482. }
  1483. CastExpr.prototype.isEquivalent = function (e) {
  1484. return e instanceof CastExpr && this.value.isEquivalent(e.value);
  1485. };
  1486. CastExpr.prototype.isConstant = function () { return false; };
  1487. CastExpr.prototype.visitExpression = function (visitor, context) {
  1488. return visitor.visitCastExpr(this, context);
  1489. };
  1490. return CastExpr;
  1491. }(Expression));
  1492. var FnParam = /** @class */ (function () {
  1493. function FnParam(name, type) {
  1494. if (type === void 0) { type = null; }
  1495. this.name = name;
  1496. this.type = type;
  1497. }
  1498. FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; };
  1499. return FnParam;
  1500. }());
  1501. var FunctionExpr = /** @class */ (function (_super) {
  1502. __extends(FunctionExpr, _super);
  1503. function FunctionExpr(params, statements, type, sourceSpan, name) {
  1504. var _this = _super.call(this, type, sourceSpan) || this;
  1505. _this.params = params;
  1506. _this.statements = statements;
  1507. _this.name = name;
  1508. return _this;
  1509. }
  1510. FunctionExpr.prototype.isEquivalent = function (e) {
  1511. return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
  1512. areAllEquivalent(this.statements, e.statements);
  1513. };
  1514. FunctionExpr.prototype.isConstant = function () { return false; };
  1515. FunctionExpr.prototype.visitExpression = function (visitor, context) {
  1516. return visitor.visitFunctionExpr(this, context);
  1517. };
  1518. FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
  1519. if (modifiers === void 0) { modifiers = null; }
  1520. return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
  1521. };
  1522. return FunctionExpr;
  1523. }(Expression));
  1524. var BinaryOperatorExpr = /** @class */ (function (_super) {
  1525. __extends(BinaryOperatorExpr, _super);
  1526. function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) {
  1527. if (parens === void 0) { parens = true; }
  1528. var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
  1529. _this.operator = operator;
  1530. _this.rhs = rhs;
  1531. _this.parens = parens;
  1532. _this.lhs = lhs;
  1533. return _this;
  1534. }
  1535. BinaryOperatorExpr.prototype.isEquivalent = function (e) {
  1536. return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
  1537. this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
  1538. };
  1539. BinaryOperatorExpr.prototype.isConstant = function () { return false; };
  1540. BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
  1541. return visitor.visitBinaryOperatorExpr(this, context);
  1542. };
  1543. return BinaryOperatorExpr;
  1544. }(Expression));
  1545. var ReadPropExpr = /** @class */ (function (_super) {
  1546. __extends(ReadPropExpr, _super);
  1547. function ReadPropExpr(receiver, name, type, sourceSpan) {
  1548. var _this = _super.call(this, type, sourceSpan) || this;
  1549. _this.receiver = receiver;
  1550. _this.name = name;
  1551. return _this;
  1552. }
  1553. ReadPropExpr.prototype.isEquivalent = function (e) {
  1554. return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
  1555. this.name === e.name;
  1556. };
  1557. ReadPropExpr.prototype.isConstant = function () { return false; };
  1558. ReadPropExpr.prototype.visitExpression = function (visitor, context) {
  1559. return visitor.visitReadPropExpr(this, context);
  1560. };
  1561. ReadPropExpr.prototype.set = function (value) {
  1562. return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
  1563. };
  1564. return ReadPropExpr;
  1565. }(Expression));
  1566. var ReadKeyExpr = /** @class */ (function (_super) {
  1567. __extends(ReadKeyExpr, _super);
  1568. function ReadKeyExpr(receiver, index, type, sourceSpan) {
  1569. var _this = _super.call(this, type, sourceSpan) || this;
  1570. _this.receiver = receiver;
  1571. _this.index = index;
  1572. return _this;
  1573. }
  1574. ReadKeyExpr.prototype.isEquivalent = function (e) {
  1575. return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1576. this.index.isEquivalent(e.index);
  1577. };
  1578. ReadKeyExpr.prototype.isConstant = function () { return false; };
  1579. ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
  1580. return visitor.visitReadKeyExpr(this, context);
  1581. };
  1582. ReadKeyExpr.prototype.set = function (value) {
  1583. return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
  1584. };
  1585. return ReadKeyExpr;
  1586. }(Expression));
  1587. var LiteralArrayExpr = /** @class */ (function (_super) {
  1588. __extends(LiteralArrayExpr, _super);
  1589. function LiteralArrayExpr(entries, type, sourceSpan) {
  1590. var _this = _super.call(this, type, sourceSpan) || this;
  1591. _this.entries = entries;
  1592. return _this;
  1593. }
  1594. LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); };
  1595. LiteralArrayExpr.prototype.isEquivalent = function (e) {
  1596. return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
  1597. };
  1598. LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
  1599. return visitor.visitLiteralArrayExpr(this, context);
  1600. };
  1601. return LiteralArrayExpr;
  1602. }(Expression));
  1603. var LiteralMapEntry = /** @class */ (function () {
  1604. function LiteralMapEntry(key, value, quoted) {
  1605. this.key = key;
  1606. this.value = value;
  1607. this.quoted = quoted;
  1608. }
  1609. LiteralMapEntry.prototype.isEquivalent = function (e) {
  1610. return this.key === e.key && this.value.isEquivalent(e.value);
  1611. };
  1612. return LiteralMapEntry;
  1613. }());
  1614. var LiteralMapExpr = /** @class */ (function (_super) {
  1615. __extends(LiteralMapExpr, _super);
  1616. function LiteralMapExpr(entries, type, sourceSpan) {
  1617. var _this = _super.call(this, type, sourceSpan) || this;
  1618. _this.entries = entries;
  1619. _this.valueType = null;
  1620. if (type) {
  1621. _this.valueType = type.valueType;
  1622. }
  1623. return _this;
  1624. }
  1625. LiteralMapExpr.prototype.isEquivalent = function (e) {
  1626. return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
  1627. };
  1628. LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); };
  1629. LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
  1630. return visitor.visitLiteralMapExpr(this, context);
  1631. };
  1632. return LiteralMapExpr;
  1633. }(Expression));
  1634. var CommaExpr = /** @class */ (function (_super) {
  1635. __extends(CommaExpr, _super);
  1636. function CommaExpr(parts, sourceSpan) {
  1637. var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
  1638. _this.parts = parts;
  1639. return _this;
  1640. }
  1641. CommaExpr.prototype.isEquivalent = function (e) {
  1642. return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
  1643. };
  1644. CommaExpr.prototype.isConstant = function () { return false; };
  1645. CommaExpr.prototype.visitExpression = function (visitor, context) {
  1646. return visitor.visitCommaExpr(this, context);
  1647. };
  1648. return CommaExpr;
  1649. }(Expression));
  1650. var THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
  1651. var SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
  1652. var CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
  1653. var CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
  1654. var NULL_EXPR = new LiteralExpr(null, null, null);
  1655. var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
  1656. //// Statements
  1657. var StmtModifier;
  1658. (function (StmtModifier) {
  1659. StmtModifier[StmtModifier["Final"] = 0] = "Final";
  1660. StmtModifier[StmtModifier["Private"] = 1] = "Private";
  1661. StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
  1662. StmtModifier[StmtModifier["Static"] = 3] = "Static";
  1663. })(StmtModifier || (StmtModifier = {}));
  1664. var Statement = /** @class */ (function () {
  1665. function Statement(modifiers, sourceSpan) {
  1666. this.modifiers = modifiers || [];
  1667. this.sourceSpan = sourceSpan || null;
  1668. }
  1669. Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1670. return Statement;
  1671. }());
  1672. var DeclareVarStmt = /** @class */ (function (_super) {
  1673. __extends(DeclareVarStmt, _super);
  1674. function DeclareVarStmt(name, value, type, modifiers, sourceSpan) {
  1675. if (modifiers === void 0) { modifiers = null; }
  1676. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1677. _this.name = name;
  1678. _this.value = value;
  1679. _this.type = type || (value && value.type) || null;
  1680. return _this;
  1681. }
  1682. DeclareVarStmt.prototype.isEquivalent = function (stmt) {
  1683. return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
  1684. (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
  1685. };
  1686. DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
  1687. return visitor.visitDeclareVarStmt(this, context);
  1688. };
  1689. return DeclareVarStmt;
  1690. }(Statement));
  1691. var DeclareFunctionStmt = /** @class */ (function (_super) {
  1692. __extends(DeclareFunctionStmt, _super);
  1693. function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) {
  1694. if (modifiers === void 0) { modifiers = null; }
  1695. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1696. _this.name = name;
  1697. _this.params = params;
  1698. _this.statements = statements;
  1699. _this.type = type || null;
  1700. return _this;
  1701. }
  1702. DeclareFunctionStmt.prototype.isEquivalent = function (stmt) {
  1703. return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
  1704. areAllEquivalent(this.statements, stmt.statements);
  1705. };
  1706. DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
  1707. return visitor.visitDeclareFunctionStmt(this, context);
  1708. };
  1709. return DeclareFunctionStmt;
  1710. }(Statement));
  1711. var ExpressionStatement = /** @class */ (function (_super) {
  1712. __extends(ExpressionStatement, _super);
  1713. function ExpressionStatement(expr, sourceSpan) {
  1714. var _this = _super.call(this, null, sourceSpan) || this;
  1715. _this.expr = expr;
  1716. return _this;
  1717. }
  1718. ExpressionStatement.prototype.isEquivalent = function (stmt) {
  1719. return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
  1720. };
  1721. ExpressionStatement.prototype.visitStatement = function (visitor, context) {
  1722. return visitor.visitExpressionStmt(this, context);
  1723. };
  1724. return ExpressionStatement;
  1725. }(Statement));
  1726. var ReturnStatement = /** @class */ (function (_super) {
  1727. __extends(ReturnStatement, _super);
  1728. function ReturnStatement(value, sourceSpan) {
  1729. var _this = _super.call(this, null, sourceSpan) || this;
  1730. _this.value = value;
  1731. return _this;
  1732. }
  1733. ReturnStatement.prototype.isEquivalent = function (stmt) {
  1734. return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
  1735. };
  1736. ReturnStatement.prototype.visitStatement = function (visitor, context) {
  1737. return visitor.visitReturnStmt(this, context);
  1738. };
  1739. return ReturnStatement;
  1740. }(Statement));
  1741. var AbstractClassPart = /** @class */ (function () {
  1742. function AbstractClassPart(type, modifiers) {
  1743. this.modifiers = modifiers;
  1744. if (!modifiers) {
  1745. this.modifiers = [];
  1746. }
  1747. this.type = type || null;
  1748. }
  1749. AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1750. return AbstractClassPart;
  1751. }());
  1752. var ClassField = /** @class */ (function (_super) {
  1753. __extends(ClassField, _super);
  1754. function ClassField(name, type, modifiers, initializer) {
  1755. if (modifiers === void 0) { modifiers = null; }
  1756. var _this = _super.call(this, type, modifiers) || this;
  1757. _this.name = name;
  1758. _this.initializer = initializer;
  1759. return _this;
  1760. }
  1761. ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; };
  1762. return ClassField;
  1763. }(AbstractClassPart));
  1764. var ClassMethod = /** @class */ (function (_super) {
  1765. __extends(ClassMethod, _super);
  1766. function ClassMethod(name, params, body, type, modifiers) {
  1767. if (modifiers === void 0) { modifiers = null; }
  1768. var _this = _super.call(this, type, modifiers) || this;
  1769. _this.name = name;
  1770. _this.params = params;
  1771. _this.body = body;
  1772. return _this;
  1773. }
  1774. ClassMethod.prototype.isEquivalent = function (m) {
  1775. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1776. };
  1777. return ClassMethod;
  1778. }(AbstractClassPart));
  1779. var ClassGetter = /** @class */ (function (_super) {
  1780. __extends(ClassGetter, _super);
  1781. function ClassGetter(name, body, type, modifiers) {
  1782. if (modifiers === void 0) { modifiers = null; }
  1783. var _this = _super.call(this, type, modifiers) || this;
  1784. _this.name = name;
  1785. _this.body = body;
  1786. return _this;
  1787. }
  1788. ClassGetter.prototype.isEquivalent = function (m) {
  1789. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1790. };
  1791. return ClassGetter;
  1792. }(AbstractClassPart));
  1793. var ClassStmt = /** @class */ (function (_super) {
  1794. __extends(ClassStmt, _super);
  1795. function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) {
  1796. if (modifiers === void 0) { modifiers = null; }
  1797. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1798. _this.name = name;
  1799. _this.parent = parent;
  1800. _this.fields = fields;
  1801. _this.getters = getters;
  1802. _this.constructorMethod = constructorMethod;
  1803. _this.methods = methods;
  1804. return _this;
  1805. }
  1806. ClassStmt.prototype.isEquivalent = function (stmt) {
  1807. return stmt instanceof ClassStmt && this.name === stmt.name &&
  1808. nullSafeIsEquivalent(this.parent, stmt.parent) &&
  1809. areAllEquivalent(this.fields, stmt.fields) &&
  1810. areAllEquivalent(this.getters, stmt.getters) &&
  1811. this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
  1812. areAllEquivalent(this.methods, stmt.methods);
  1813. };
  1814. ClassStmt.prototype.visitStatement = function (visitor, context) {
  1815. return visitor.visitDeclareClassStmt(this, context);
  1816. };
  1817. return ClassStmt;
  1818. }(Statement));
  1819. var IfStmt = /** @class */ (function (_super) {
  1820. __extends(IfStmt, _super);
  1821. function IfStmt(condition, trueCase, falseCase, sourceSpan) {
  1822. if (falseCase === void 0) { falseCase = []; }
  1823. var _this = _super.call(this, null, sourceSpan) || this;
  1824. _this.condition = condition;
  1825. _this.trueCase = trueCase;
  1826. _this.falseCase = falseCase;
  1827. return _this;
  1828. }
  1829. IfStmt.prototype.isEquivalent = function (stmt) {
  1830. return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
  1831. areAllEquivalent(this.trueCase, stmt.trueCase) &&
  1832. areAllEquivalent(this.falseCase, stmt.falseCase);
  1833. };
  1834. IfStmt.prototype.visitStatement = function (visitor, context) {
  1835. return visitor.visitIfStmt(this, context);
  1836. };
  1837. return IfStmt;
  1838. }(Statement));
  1839. var CommentStmt = /** @class */ (function (_super) {
  1840. __extends(CommentStmt, _super);
  1841. function CommentStmt(comment, multiline, sourceSpan) {
  1842. if (multiline === void 0) { multiline = false; }
  1843. var _this = _super.call(this, null, sourceSpan) || this;
  1844. _this.comment = comment;
  1845. _this.multiline = multiline;
  1846. return _this;
  1847. }
  1848. CommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof CommentStmt; };
  1849. CommentStmt.prototype.visitStatement = function (visitor, context) {
  1850. return visitor.visitCommentStmt(this, context);
  1851. };
  1852. return CommentStmt;
  1853. }(Statement));
  1854. var JSDocCommentStmt = /** @class */ (function (_super) {
  1855. __extends(JSDocCommentStmt, _super);
  1856. function JSDocCommentStmt(tags, sourceSpan) {
  1857. if (tags === void 0) { tags = []; }
  1858. var _this = _super.call(this, null, sourceSpan) || this;
  1859. _this.tags = tags;
  1860. return _this;
  1861. }
  1862. JSDocCommentStmt.prototype.isEquivalent = function (stmt) {
  1863. return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString();
  1864. };
  1865. JSDocCommentStmt.prototype.visitStatement = function (visitor, context) {
  1866. return visitor.visitJSDocCommentStmt(this, context);
  1867. };
  1868. JSDocCommentStmt.prototype.toString = function () { return serializeTags(this.tags); };
  1869. return JSDocCommentStmt;
  1870. }(Statement));
  1871. var TryCatchStmt = /** @class */ (function (_super) {
  1872. __extends(TryCatchStmt, _super);
  1873. function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) {
  1874. var _this = _super.call(this, null, sourceSpan) || this;
  1875. _this.bodyStmts = bodyStmts;
  1876. _this.catchStmts = catchStmts;
  1877. return _this;
  1878. }
  1879. TryCatchStmt.prototype.isEquivalent = function (stmt) {
  1880. return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
  1881. areAllEquivalent(this.catchStmts, stmt.catchStmts);
  1882. };
  1883. TryCatchStmt.prototype.visitStatement = function (visitor, context) {
  1884. return visitor.visitTryCatchStmt(this, context);
  1885. };
  1886. return TryCatchStmt;
  1887. }(Statement));
  1888. var ThrowStmt = /** @class */ (function (_super) {
  1889. __extends(ThrowStmt, _super);
  1890. function ThrowStmt(error, sourceSpan) {
  1891. var _this = _super.call(this, null, sourceSpan) || this;
  1892. _this.error = error;
  1893. return _this;
  1894. }
  1895. ThrowStmt.prototype.isEquivalent = function (stmt) {
  1896. return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
  1897. };
  1898. ThrowStmt.prototype.visitStatement = function (visitor, context) {
  1899. return visitor.visitThrowStmt(this, context);
  1900. };
  1901. return ThrowStmt;
  1902. }(Statement));
  1903. var AstTransformer = /** @class */ (function () {
  1904. function AstTransformer() {
  1905. }
  1906. AstTransformer.prototype.transformExpr = function (expr, context) { return expr; };
  1907. AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; };
  1908. AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); };
  1909. AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) {
  1910. return this.transformExpr(ast, context);
  1911. };
  1912. AstTransformer.prototype.visitTypeofExpr = function (expr, context) {
  1913. return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1914. };
  1915. AstTransformer.prototype.visitWriteVarExpr = function (expr, context) {
  1916. return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1917. };
  1918. AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) {
  1919. return this.transformExpr(new WriteKeyExpr(expr.receiver.visitExpression(this, context), expr.index.visitExpression(this, context), expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1920. };
  1921. AstTransformer.prototype.visitWritePropExpr = function (expr, context) {
  1922. return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1923. };
  1924. AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) {
  1925. var method = ast.builtin || ast.name;
  1926. return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1927. };
  1928. AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) {
  1929. return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1930. };
  1931. AstTransformer.prototype.visitInstantiateExpr = function (ast, context) {
  1932. return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1933. };
  1934. AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); };
  1935. AstTransformer.prototype.visitExternalExpr = function (ast, context) {
  1936. return this.transformExpr(ast, context);
  1937. };
  1938. AstTransformer.prototype.visitConditionalExpr = function (ast, context) {
  1939. return this.transformExpr(new ConditionalExpr(ast.condition.visitExpression(this, context), ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1940. };
  1941. AstTransformer.prototype.visitNotExpr = function (ast, context) {
  1942. return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1943. };
  1944. AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) {
  1945. return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1946. };
  1947. AstTransformer.prototype.visitCastExpr = function (ast, context) {
  1948. return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1949. };
  1950. AstTransformer.prototype.visitFunctionExpr = function (ast, context) {
  1951. return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
  1952. };
  1953. AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) {
  1954. return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1955. };
  1956. AstTransformer.prototype.visitReadPropExpr = function (ast, context) {
  1957. return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
  1958. };
  1959. AstTransformer.prototype.visitReadKeyExpr = function (ast, context) {
  1960. return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1961. };
  1962. AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) {
  1963. return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
  1964. };
  1965. AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) {
  1966. var _this = this;
  1967. var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
  1968. var mapType = new MapType(ast.valueType, null);
  1969. return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
  1970. };
  1971. AstTransformer.prototype.visitCommaExpr = function (ast, context) {
  1972. return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
  1973. };
  1974. AstTransformer.prototype.visitAllExpressions = function (exprs, context) {
  1975. var _this = this;
  1976. return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
  1977. };
  1978. AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) {
  1979. var value = stmt.value && stmt.value.visitExpression(this, context);
  1980. return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1981. };
  1982. AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  1983. return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1984. };
  1985. AstTransformer.prototype.visitExpressionStmt = function (stmt, context) {
  1986. return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
  1987. };
  1988. AstTransformer.prototype.visitReturnStmt = function (stmt, context) {
  1989. return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
  1990. };
  1991. AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) {
  1992. var _this = this;
  1993. var parent = stmt.parent.visitExpression(this, context);
  1994. var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
  1995. var ctorMethod = stmt.constructorMethod &&
  1996. new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
  1997. var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
  1998. return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
  1999. };
  2000. AstTransformer.prototype.visitIfStmt = function (stmt, context) {
  2001. return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
  2002. };
  2003. AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) {
  2004. return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
  2005. };
  2006. AstTransformer.prototype.visitThrowStmt = function (stmt, context) {
  2007. return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
  2008. };
  2009. AstTransformer.prototype.visitCommentStmt = function (stmt, context) {
  2010. return this.transformStmt(stmt, context);
  2011. };
  2012. AstTransformer.prototype.visitJSDocCommentStmt = function (stmt, context) {
  2013. return this.transformStmt(stmt, context);
  2014. };
  2015. AstTransformer.prototype.visitAllStatements = function (stmts, context) {
  2016. var _this = this;
  2017. return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
  2018. };
  2019. return AstTransformer;
  2020. }());
  2021. var RecursiveAstVisitor = /** @class */ (function () {
  2022. function RecursiveAstVisitor() {
  2023. }
  2024. RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; };
  2025. RecursiveAstVisitor.prototype.visitExpression = function (ast, context) {
  2026. if (ast.type) {
  2027. ast.type.visitType(this, context);
  2028. }
  2029. return ast;
  2030. };
  2031. RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); };
  2032. RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) {
  2033. var _this = this;
  2034. type.value.visitExpression(this, context);
  2035. if (type.typeParams !== null) {
  2036. type.typeParams.forEach(function (param) { return _this.visitType(param, context); });
  2037. }
  2038. return this.visitType(type, context);
  2039. };
  2040. RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); };
  2041. RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); };
  2042. RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) { return ast; };
  2043. RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) { return this.visitExpression(ast, context); };
  2044. RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2045. return this.visitExpression(ast, context);
  2046. };
  2047. RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) {
  2048. ast.value.visitExpression(this, context);
  2049. return this.visitExpression(ast, context);
  2050. };
  2051. RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) {
  2052. ast.receiver.visitExpression(this, context);
  2053. ast.index.visitExpression(this, context);
  2054. ast.value.visitExpression(this, context);
  2055. return this.visitExpression(ast, context);
  2056. };
  2057. RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) {
  2058. ast.receiver.visitExpression(this, context);
  2059. ast.value.visitExpression(this, context);
  2060. return this.visitExpression(ast, context);
  2061. };
  2062. RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) {
  2063. ast.receiver.visitExpression(this, context);
  2064. this.visitAllExpressions(ast.args, context);
  2065. return this.visitExpression(ast, context);
  2066. };
  2067. RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) {
  2068. ast.fn.visitExpression(this, context);
  2069. this.visitAllExpressions(ast.args, context);
  2070. return this.visitExpression(ast, context);
  2071. };
  2072. RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) {
  2073. ast.classExpr.visitExpression(this, context);
  2074. this.visitAllExpressions(ast.args, context);
  2075. return this.visitExpression(ast, context);
  2076. };
  2077. RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) {
  2078. return this.visitExpression(ast, context);
  2079. };
  2080. RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) {
  2081. var _this = this;
  2082. if (ast.typeParams) {
  2083. ast.typeParams.forEach(function (type) { return type.visitType(_this, context); });
  2084. }
  2085. return this.visitExpression(ast, context);
  2086. };
  2087. RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) {
  2088. ast.condition.visitExpression(this, context);
  2089. ast.trueCase.visitExpression(this, context);
  2090. ast.falseCase.visitExpression(this, context);
  2091. return this.visitExpression(ast, context);
  2092. };
  2093. RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) {
  2094. ast.condition.visitExpression(this, context);
  2095. return this.visitExpression(ast, context);
  2096. };
  2097. RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) {
  2098. ast.condition.visitExpression(this, context);
  2099. return this.visitExpression(ast, context);
  2100. };
  2101. RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) {
  2102. ast.value.visitExpression(this, context);
  2103. return this.visitExpression(ast, context);
  2104. };
  2105. RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) {
  2106. this.visitAllStatements(ast.statements, context);
  2107. return this.visitExpression(ast, context);
  2108. };
  2109. RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) {
  2110. ast.lhs.visitExpression(this, context);
  2111. ast.rhs.visitExpression(this, context);
  2112. return this.visitExpression(ast, context);
  2113. };
  2114. RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) {
  2115. ast.receiver.visitExpression(this, context);
  2116. return this.visitExpression(ast, context);
  2117. };
  2118. RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) {
  2119. ast.receiver.visitExpression(this, context);
  2120. ast.index.visitExpression(this, context);
  2121. return this.visitExpression(ast, context);
  2122. };
  2123. RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2124. this.visitAllExpressions(ast.entries, context);
  2125. return this.visitExpression(ast, context);
  2126. };
  2127. RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2128. var _this = this;
  2129. ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
  2130. return this.visitExpression(ast, context);
  2131. };
  2132. RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) {
  2133. this.visitAllExpressions(ast.parts, context);
  2134. return this.visitExpression(ast, context);
  2135. };
  2136. RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) {
  2137. var _this = this;
  2138. exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
  2139. };
  2140. RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) {
  2141. if (stmt.value) {
  2142. stmt.value.visitExpression(this, context);
  2143. }
  2144. if (stmt.type) {
  2145. stmt.type.visitType(this, context);
  2146. }
  2147. return stmt;
  2148. };
  2149. RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2150. this.visitAllStatements(stmt.statements, context);
  2151. if (stmt.type) {
  2152. stmt.type.visitType(this, context);
  2153. }
  2154. return stmt;
  2155. };
  2156. RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) {
  2157. stmt.expr.visitExpression(this, context);
  2158. return stmt;
  2159. };
  2160. RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) {
  2161. stmt.value.visitExpression(this, context);
  2162. return stmt;
  2163. };
  2164. RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2165. var _this = this;
  2166. stmt.parent.visitExpression(this, context);
  2167. stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
  2168. if (stmt.constructorMethod) {
  2169. this.visitAllStatements(stmt.constructorMethod.body, context);
  2170. }
  2171. stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
  2172. return stmt;
  2173. };
  2174. RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) {
  2175. stmt.condition.visitExpression(this, context);
  2176. this.visitAllStatements(stmt.trueCase, context);
  2177. this.visitAllStatements(stmt.falseCase, context);
  2178. return stmt;
  2179. };
  2180. RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) {
  2181. this.visitAllStatements(stmt.bodyStmts, context);
  2182. this.visitAllStatements(stmt.catchStmts, context);
  2183. return stmt;
  2184. };
  2185. RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) {
  2186. stmt.error.visitExpression(this, context);
  2187. return stmt;
  2188. };
  2189. RecursiveAstVisitor.prototype.visitCommentStmt = function (stmt, context) { return stmt; };
  2190. RecursiveAstVisitor.prototype.visitJSDocCommentStmt = function (stmt, context) { return stmt; };
  2191. RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) {
  2192. var _this = this;
  2193. stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
  2194. };
  2195. return RecursiveAstVisitor;
  2196. }());
  2197. var _ReadVarVisitor = /** @class */ (function (_super) {
  2198. __extends(_ReadVarVisitor, _super);
  2199. function _ReadVarVisitor() {
  2200. var _this = _super !== null && _super.apply(this, arguments) || this;
  2201. _this.varNames = new Set();
  2202. return _this;
  2203. }
  2204. _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2205. // Don't descend into nested functions
  2206. return stmt;
  2207. };
  2208. _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2209. // Don't descend into nested classes
  2210. return stmt;
  2211. };
  2212. _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2213. if (ast.name) {
  2214. this.varNames.add(ast.name);
  2215. }
  2216. return null;
  2217. };
  2218. return _ReadVarVisitor;
  2219. }(RecursiveAstVisitor));
  2220. var _FindExternalReferencesVisitor = /** @class */ (function (_super) {
  2221. __extends(_FindExternalReferencesVisitor, _super);
  2222. function _FindExternalReferencesVisitor() {
  2223. var _this = _super !== null && _super.apply(this, arguments) || this;
  2224. _this.externalReferences = [];
  2225. return _this;
  2226. }
  2227. _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) {
  2228. this.externalReferences.push(e.value);
  2229. return _super.prototype.visitExternalExpr.call(this, e, context);
  2230. };
  2231. return _FindExternalReferencesVisitor;
  2232. }(RecursiveAstVisitor));
  2233. var _ApplySourceSpanTransformer = /** @class */ (function (_super) {
  2234. __extends(_ApplySourceSpanTransformer, _super);
  2235. function _ApplySourceSpanTransformer(sourceSpan) {
  2236. var _this = _super.call(this) || this;
  2237. _this.sourceSpan = sourceSpan;
  2238. return _this;
  2239. }
  2240. _ApplySourceSpanTransformer.prototype._clone = function (obj) {
  2241. var e_1, _a;
  2242. var clone = Object.create(obj.constructor.prototype);
  2243. try {
  2244. for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
  2245. var prop = _c.value;
  2246. clone[prop] = obj[prop];
  2247. }
  2248. }
  2249. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2250. finally {
  2251. try {
  2252. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2253. }
  2254. finally { if (e_1) throw e_1.error; }
  2255. }
  2256. return clone;
  2257. };
  2258. _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
  2259. if (!expr.sourceSpan) {
  2260. expr = this._clone(expr);
  2261. expr.sourceSpan = this.sourceSpan;
  2262. }
  2263. return expr;
  2264. };
  2265. _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
  2266. if (!stmt.sourceSpan) {
  2267. stmt = this._clone(stmt);
  2268. stmt.sourceSpan = this.sourceSpan;
  2269. }
  2270. return stmt;
  2271. };
  2272. return _ApplySourceSpanTransformer;
  2273. }(AstTransformer));
  2274. function variable(name, type, sourceSpan) {
  2275. return new ReadVarExpr(name, type, sourceSpan);
  2276. }
  2277. function importExpr(id, typeParams, sourceSpan) {
  2278. if (typeParams === void 0) { typeParams = null; }
  2279. return new ExternalExpr(id, null, typeParams, sourceSpan);
  2280. }
  2281. function expressionType(expr, typeModifiers, typeParams) {
  2282. if (typeModifiers === void 0) { typeModifiers = null; }
  2283. if (typeParams === void 0) { typeParams = null; }
  2284. return new ExpressionType(expr, typeModifiers, typeParams);
  2285. }
  2286. function typeofExpr(expr) {
  2287. return new TypeofExpr(expr);
  2288. }
  2289. function literalArr(values, type, sourceSpan) {
  2290. return new LiteralArrayExpr(values, type, sourceSpan);
  2291. }
  2292. function literalMap(values, type) {
  2293. if (type === void 0) { type = null; }
  2294. return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null);
  2295. }
  2296. function not(expr, sourceSpan) {
  2297. return new NotExpr(expr, sourceSpan);
  2298. }
  2299. function assertNotNull(expr, sourceSpan) {
  2300. return new AssertNotNull(expr, sourceSpan);
  2301. }
  2302. function fn(params, body, type, sourceSpan, name) {
  2303. return new FunctionExpr(params, body, type, sourceSpan, name);
  2304. }
  2305. function ifStmt(condition, thenClause, elseClause) {
  2306. return new IfStmt(condition, thenClause, elseClause);
  2307. }
  2308. function literal(value, type, sourceSpan) {
  2309. return new LiteralExpr(value, type, sourceSpan);
  2310. }
  2311. function isNull(exp) {
  2312. return exp instanceof LiteralExpr && exp.value === null;
  2313. }
  2314. /*
  2315. * Serializes a `Tag` into a string.
  2316. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
  2317. */
  2318. function tagToString(tag) {
  2319. var out = '';
  2320. if (tag.tagName) {
  2321. out += " @" + tag.tagName;
  2322. }
  2323. if (tag.text) {
  2324. if (tag.text.match(/\/\*|\*\//)) {
  2325. throw new Error('JSDoc text cannot contain "/*" and "*/"');
  2326. }
  2327. out += ' ' + tag.text.replace(/@/g, '\\@');
  2328. }
  2329. return out;
  2330. }
  2331. function serializeTags(tags) {
  2332. var e_2, _a;
  2333. if (tags.length === 0)
  2334. return '';
  2335. var out = '*\n';
  2336. try {
  2337. for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) {
  2338. var tag = tags_1_1.value;
  2339. out += ' *';
  2340. // If the tagToString is multi-line, insert " * " prefixes on subsequent lines.
  2341. out += tagToString(tag).replace(/\n/g, '\n * ');
  2342. out += '\n';
  2343. }
  2344. }
  2345. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  2346. finally {
  2347. try {
  2348. if (tags_1_1 && !tags_1_1.done && (_a = tags_1.return)) _a.call(tags_1);
  2349. }
  2350. finally { if (e_2) throw e_2.error; }
  2351. }
  2352. out += ' ';
  2353. return out;
  2354. }
  2355. /**
  2356. * @license
  2357. * Copyright Google Inc. All Rights Reserved.
  2358. *
  2359. * Use of this source code is governed by an MIT-style license that can be
  2360. * found in the LICENSE file at https://angular.io/license
  2361. */
  2362. var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
  2363. function dashCaseToCamelCase(input) {
  2364. return input.replace(DASH_CASE_REGEXP, function () {
  2365. var m = [];
  2366. for (var _i = 0; _i < arguments.length; _i++) {
  2367. m[_i] = arguments[_i];
  2368. }
  2369. return m[1].toUpperCase();
  2370. });
  2371. }
  2372. function splitAtColon(input, defaultValues) {
  2373. return _splitAt(input, ':', defaultValues);
  2374. }
  2375. function splitAtPeriod(input, defaultValues) {
  2376. return _splitAt(input, '.', defaultValues);
  2377. }
  2378. function _splitAt(input, character, defaultValues) {
  2379. var characterIndex = input.indexOf(character);
  2380. if (characterIndex == -1)
  2381. return defaultValues;
  2382. return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
  2383. }
  2384. function visitValue(value, visitor, context) {
  2385. if (Array.isArray(value)) {
  2386. return visitor.visitArray(value, context);
  2387. }
  2388. if (isStrictStringMap(value)) {
  2389. return visitor.visitStringMap(value, context);
  2390. }
  2391. if (value == null || typeof value == 'string' || typeof value == 'number' ||
  2392. typeof value == 'boolean') {
  2393. return visitor.visitPrimitive(value, context);
  2394. }
  2395. return visitor.visitOther(value, context);
  2396. }
  2397. function isDefined(val) {
  2398. return val !== null && val !== undefined;
  2399. }
  2400. function noUndefined(val) {
  2401. return val === undefined ? null : val;
  2402. }
  2403. var ValueTransformer = /** @class */ (function () {
  2404. function ValueTransformer() {
  2405. }
  2406. ValueTransformer.prototype.visitArray = function (arr, context) {
  2407. var _this = this;
  2408. return arr.map(function (value) { return visitValue(value, _this, context); });
  2409. };
  2410. ValueTransformer.prototype.visitStringMap = function (map, context) {
  2411. var _this = this;
  2412. var result = {};
  2413. Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
  2414. return result;
  2415. };
  2416. ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
  2417. ValueTransformer.prototype.visitOther = function (value, context) { return value; };
  2418. return ValueTransformer;
  2419. }());
  2420. var SyncAsync = {
  2421. assertSync: function (value) {
  2422. if (isPromise(value)) {
  2423. throw new Error("Illegal state: value cannot be a promise");
  2424. }
  2425. return value;
  2426. },
  2427. then: function (value, cb) { return isPromise(value) ? value.then(cb) : cb(value); },
  2428. all: function (syncAsyncValues) {
  2429. return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
  2430. }
  2431. };
  2432. function error(msg) {
  2433. throw new Error("Internal Error: " + msg);
  2434. }
  2435. function syntaxError(msg, parseErrors) {
  2436. var error = Error(msg);
  2437. error[ERROR_SYNTAX_ERROR] = true;
  2438. if (parseErrors)
  2439. error[ERROR_PARSE_ERRORS] = parseErrors;
  2440. return error;
  2441. }
  2442. var ERROR_SYNTAX_ERROR = 'ngSyntaxError';
  2443. var ERROR_PARSE_ERRORS = 'ngParseErrors';
  2444. // Escape characters that have a special meaning in Regular Expressions
  2445. function escapeRegExp(s) {
  2446. return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  2447. }
  2448. var STRING_MAP_PROTO = Object.getPrototypeOf({});
  2449. function isStrictStringMap(obj) {
  2450. return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
  2451. }
  2452. function utf8Encode(str) {
  2453. var encoded = '';
  2454. for (var index = 0; index < str.length; index++) {
  2455. var codePoint = str.charCodeAt(index);
  2456. // decode surrogate
  2457. // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  2458. if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
  2459. var low = str.charCodeAt(index + 1);
  2460. if (low >= 0xdc00 && low <= 0xdfff) {
  2461. index++;
  2462. codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
  2463. }
  2464. }
  2465. if (codePoint <= 0x7f) {
  2466. encoded += String.fromCharCode(codePoint);
  2467. }
  2468. else if (codePoint <= 0x7ff) {
  2469. encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
  2470. }
  2471. else if (codePoint <= 0xffff) {
  2472. encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2473. }
  2474. else if (codePoint <= 0x1fffff) {
  2475. encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2476. }
  2477. }
  2478. return encoded;
  2479. }
  2480. function stringify(token) {
  2481. if (typeof token === 'string') {
  2482. return token;
  2483. }
  2484. if (token instanceof Array) {
  2485. return '[' + token.map(stringify).join(', ') + ']';
  2486. }
  2487. if (token == null) {
  2488. return '' + token;
  2489. }
  2490. if (token.overriddenName) {
  2491. return "" + token.overriddenName;
  2492. }
  2493. if (token.name) {
  2494. return "" + token.name;
  2495. }
  2496. if (!token.toString) {
  2497. return 'object';
  2498. }
  2499. // WARNING: do not try to `JSON.stringify(token)` here
  2500. // see https://github.com/angular/angular/issues/23440
  2501. var res = token.toString();
  2502. if (res == null) {
  2503. return '' + res;
  2504. }
  2505. var newLineIndex = res.indexOf('\n');
  2506. return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
  2507. }
  2508. /**
  2509. * Lazily retrieves the reference value from a forwardRef.
  2510. */
  2511. function resolveForwardRef(type) {
  2512. if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
  2513. return type();
  2514. }
  2515. else {
  2516. return type;
  2517. }
  2518. }
  2519. /**
  2520. * Determine if the argument is shaped like a Promise
  2521. */
  2522. function isPromise(obj) {
  2523. // allow any Promise/A+ compliant thenable.
  2524. // It's up to the caller to ensure that obj.then conforms to the spec
  2525. return !!obj && typeof obj.then === 'function';
  2526. }
  2527. var Version = /** @class */ (function () {
  2528. function Version(full) {
  2529. this.full = full;
  2530. var splits = full.split('.');
  2531. this.major = splits[0];
  2532. this.minor = splits[1];
  2533. this.patch = splits.slice(2).join('.');
  2534. }
  2535. return Version;
  2536. }());
  2537. var __window = typeof window !== 'undefined' && window;
  2538. var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  2539. self instanceof WorkerGlobalScope && self;
  2540. var __global = typeof global !== 'undefined' && global;
  2541. // Check __global first, because in Node tests both __global and __window may be defined and _global
  2542. // should be __global in that case.
  2543. var _global = __global || __window || __self;
  2544. /**
  2545. * @license
  2546. * Copyright Google Inc. All Rights Reserved.
  2547. *
  2548. * Use of this source code is governed by an MIT-style license that can be
  2549. * found in the LICENSE file at https://angular.io/license
  2550. */
  2551. var CONSTANT_PREFIX = '_c';
  2552. /**
  2553. * Context to use when producing a key.
  2554. *
  2555. * This ensures we see the constant not the reference variable when producing
  2556. * a key.
  2557. */
  2558. var KEY_CONTEXT = {};
  2559. /**
  2560. * A node that is a place-holder that allows the node to be replaced when the actual
  2561. * node is known.
  2562. *
  2563. * This allows the constant pool to change an expression from a direct reference to
  2564. * a constant to a shared constant. It returns a fix-up node that is later allowed to
  2565. * change the referenced expression.
  2566. */
  2567. var FixupExpression = /** @class */ (function (_super) {
  2568. __extends(FixupExpression, _super);
  2569. function FixupExpression(resolved) {
  2570. var _this = _super.call(this, resolved.type) || this;
  2571. _this.resolved = resolved;
  2572. _this.original = resolved;
  2573. return _this;
  2574. }
  2575. FixupExpression.prototype.visitExpression = function (visitor, context) {
  2576. if (context === KEY_CONTEXT) {
  2577. // When producing a key we want to traverse the constant not the
  2578. // variable used to refer to it.
  2579. return this.original.visitExpression(visitor, context);
  2580. }
  2581. else {
  2582. return this.resolved.visitExpression(visitor, context);
  2583. }
  2584. };
  2585. FixupExpression.prototype.isEquivalent = function (e) {
  2586. return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
  2587. };
  2588. FixupExpression.prototype.isConstant = function () { return true; };
  2589. FixupExpression.prototype.fixup = function (expression) {
  2590. this.resolved = expression;
  2591. this.shared = true;
  2592. };
  2593. return FixupExpression;
  2594. }(Expression));
  2595. /**
  2596. * A constant pool allows a code emitter to share constant in an output context.
  2597. *
  2598. * The constant pool also supports sharing access to ivy definitions references.
  2599. */
  2600. var ConstantPool = /** @class */ (function () {
  2601. function ConstantPool() {
  2602. this.statements = [];
  2603. this.literals = new Map();
  2604. this.literalFactories = new Map();
  2605. this.injectorDefinitions = new Map();
  2606. this.directiveDefinitions = new Map();
  2607. this.componentDefinitions = new Map();
  2608. this.pipeDefinitions = new Map();
  2609. this.nextNameIndex = 0;
  2610. }
  2611. ConstantPool.prototype.getConstLiteral = function (literal, forceShared) {
  2612. if (literal instanceof LiteralExpr || literal instanceof FixupExpression) {
  2613. // Do no put simple literals into the constant pool or try to produce a constant for a
  2614. // reference to a constant.
  2615. return literal;
  2616. }
  2617. var key = this.keyOf(literal);
  2618. var fixup = this.literals.get(key);
  2619. var newValue = false;
  2620. if (!fixup) {
  2621. fixup = new FixupExpression(literal);
  2622. this.literals.set(key, fixup);
  2623. newValue = true;
  2624. }
  2625. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2626. // Replace the expression with a variable
  2627. var name_1 = this.freshName();
  2628. this.statements.push(variable(name_1).set(literal).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
  2629. fixup.fixup(variable(name_1));
  2630. }
  2631. return fixup;
  2632. };
  2633. ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) {
  2634. if (forceShared === void 0) { forceShared = false; }
  2635. var definitions = this.definitionsOf(kind);
  2636. var fixup = definitions.get(type);
  2637. var newValue = false;
  2638. if (!fixup) {
  2639. var property = this.propertyNameOf(kind);
  2640. fixup = new FixupExpression(ctx.importExpr(type).prop(property));
  2641. definitions.set(type, fixup);
  2642. newValue = true;
  2643. }
  2644. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2645. var name_2 = this.freshName();
  2646. this.statements.push(variable(name_2).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
  2647. fixup.fixup(variable(name_2));
  2648. }
  2649. return fixup;
  2650. };
  2651. ConstantPool.prototype.getLiteralFactory = function (literal$1) {
  2652. // Create a pure function that builds an array of a mix of constant and variable expressions
  2653. if (literal$1 instanceof LiteralArrayExpr) {
  2654. var argumentsForKey = literal$1.entries.map(function (e) { return e.isConstant() ? e : literal(null); });
  2655. var key = this.keyOf(literalArr(argumentsForKey));
  2656. return this._getLiteralFactory(key, literal$1.entries, function (entries) { return literalArr(entries); });
  2657. }
  2658. else {
  2659. var expressionForKey = literalMap(literal$1.entries.map(function (e) { return ({
  2660. key: e.key,
  2661. value: e.value.isConstant() ? e.value : literal(null),
  2662. quoted: e.quoted
  2663. }); }));
  2664. var key = this.keyOf(expressionForKey);
  2665. return this._getLiteralFactory(key, literal$1.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({
  2666. key: literal$1.entries[index].key,
  2667. value: value,
  2668. quoted: literal$1.entries[index].quoted
  2669. }); })); });
  2670. }
  2671. };
  2672. ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) {
  2673. var _this = this;
  2674. var literalFactory = this.literalFactories.get(key);
  2675. var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); }));
  2676. if (!literalFactory) {
  2677. var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); });
  2678. var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); });
  2679. var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
  2680. var name_3 = this.freshName();
  2681. this.statements.push(variable(name_3).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
  2682. StmtModifier.Final
  2683. ]));
  2684. literalFactory = variable(name_3);
  2685. this.literalFactories.set(key, literalFactory);
  2686. }
  2687. return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments };
  2688. };
  2689. /**
  2690. * Produce a unique name.
  2691. *
  2692. * The name might be unique among different prefixes if any of the prefixes end in
  2693. * a digit so the prefix should be a constant string (not based on user input) and
  2694. * must not end in a digit.
  2695. */
  2696. ConstantPool.prototype.uniqueName = function (prefix) { return "" + prefix + this.nextNameIndex++; };
  2697. ConstantPool.prototype.definitionsOf = function (kind) {
  2698. switch (kind) {
  2699. case 2 /* Component */:
  2700. return this.componentDefinitions;
  2701. case 1 /* Directive */:
  2702. return this.directiveDefinitions;
  2703. case 0 /* Injector */:
  2704. return this.injectorDefinitions;
  2705. case 3 /* Pipe */:
  2706. return this.pipeDefinitions;
  2707. }
  2708. error("Unknown definition kind " + kind);
  2709. return this.componentDefinitions;
  2710. };
  2711. ConstantPool.prototype.propertyNameOf = function (kind) {
  2712. switch (kind) {
  2713. case 2 /* Component */:
  2714. return 'ngComponentDef';
  2715. case 1 /* Directive */:
  2716. return 'ngDirectiveDef';
  2717. case 0 /* Injector */:
  2718. return 'ngInjectorDef';
  2719. case 3 /* Pipe */:
  2720. return 'ngPipeDef';
  2721. }
  2722. error("Unknown definition kind " + kind);
  2723. return '<unknown>';
  2724. };
  2725. ConstantPool.prototype.freshName = function () { return this.uniqueName(CONSTANT_PREFIX); };
  2726. ConstantPool.prototype.keyOf = function (expression) {
  2727. return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
  2728. };
  2729. return ConstantPool;
  2730. }());
  2731. /**
  2732. * Visitor used to determine if 2 expressions are equivalent and can be shared in the
  2733. * `ConstantPool`.
  2734. *
  2735. * When the id (string) generated by the visitor is equal, expressions are considered equivalent.
  2736. */
  2737. var KeyVisitor = /** @class */ (function () {
  2738. function KeyVisitor() {
  2739. this.visitWrappedNodeExpr = invalid;
  2740. this.visitWriteVarExpr = invalid;
  2741. this.visitWriteKeyExpr = invalid;
  2742. this.visitWritePropExpr = invalid;
  2743. this.visitInvokeMethodExpr = invalid;
  2744. this.visitInvokeFunctionExpr = invalid;
  2745. this.visitInstantiateExpr = invalid;
  2746. this.visitConditionalExpr = invalid;
  2747. this.visitNotExpr = invalid;
  2748. this.visitAssertNotNullExpr = invalid;
  2749. this.visitCastExpr = invalid;
  2750. this.visitFunctionExpr = invalid;
  2751. this.visitBinaryOperatorExpr = invalid;
  2752. this.visitReadPropExpr = invalid;
  2753. this.visitReadKeyExpr = invalid;
  2754. this.visitCommaExpr = invalid;
  2755. }
  2756. KeyVisitor.prototype.visitLiteralExpr = function (ast) {
  2757. return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value);
  2758. };
  2759. KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2760. var _this = this;
  2761. return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]";
  2762. };
  2763. KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2764. var _this = this;
  2765. var mapKey = function (entry) {
  2766. var quote = entry.quoted ? '"' : '';
  2767. return "" + quote + entry.key + quote;
  2768. };
  2769. var mapEntry = function (entry) {
  2770. return mapKey(entry) + ":" + entry.value.visitExpression(_this, context);
  2771. };
  2772. return "{" + ast.entries.map(mapEntry).join(',');
  2773. };
  2774. KeyVisitor.prototype.visitExternalExpr = function (ast) {
  2775. return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name :
  2776. "EX:" + ast.value.runtime.name;
  2777. };
  2778. KeyVisitor.prototype.visitReadVarExpr = function (node) { return "VAR:" + node.name; };
  2779. KeyVisitor.prototype.visitTypeofExpr = function (node, context) {
  2780. return "TYPEOF:" + node.expr.visitExpression(this, context);
  2781. };
  2782. return KeyVisitor;
  2783. }());
  2784. function invalid(arg) {
  2785. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  2786. }
  2787. function isVariable(e) {
  2788. return e instanceof ReadVarExpr;
  2789. }
  2790. /**
  2791. * @license
  2792. * Copyright Google Inc. All Rights Reserved.
  2793. *
  2794. * Use of this source code is governed by an MIT-style license that can be
  2795. * found in the LICENSE file at https://angular.io/license
  2796. */
  2797. var CORE = '@angular/core';
  2798. var Identifiers = /** @class */ (function () {
  2799. function Identifiers() {
  2800. }
  2801. Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
  2802. name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
  2803. moduleName: CORE,
  2804. };
  2805. Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE };
  2806. Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE };
  2807. Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE };
  2808. Identifiers.ChangeDetectorRef = {
  2809. name: 'ChangeDetectorRef',
  2810. moduleName: CORE,
  2811. };
  2812. Identifiers.QueryList = { name: 'QueryList', moduleName: CORE };
  2813. Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE };
  2814. Identifiers.Renderer2 = { name: 'Renderer2', moduleName: CORE };
  2815. Identifiers.CodegenComponentFactoryResolver = {
  2816. name: 'ɵCodegenComponentFactoryResolver',
  2817. moduleName: CORE,
  2818. };
  2819. Identifiers.ComponentFactoryResolver = {
  2820. name: 'ComponentFactoryResolver',
  2821. moduleName: CORE,
  2822. };
  2823. Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE };
  2824. Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE };
  2825. Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE };
  2826. Identifiers.createModuleFactory = {
  2827. name: 'ɵcmf',
  2828. moduleName: CORE,
  2829. };
  2830. Identifiers.moduleDef = {
  2831. name: 'ɵmod',
  2832. moduleName: CORE,
  2833. };
  2834. Identifiers.moduleProviderDef = {
  2835. name: 'ɵmpd',
  2836. moduleName: CORE,
  2837. };
  2838. Identifiers.RegisterModuleFactoryFn = {
  2839. name: 'ɵregisterModuleFactory',
  2840. moduleName: CORE,
  2841. };
  2842. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE };
  2843. Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
  2844. Identifiers.Injector = { name: 'Injector', moduleName: CORE };
  2845. Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
  2846. Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', moduleName: CORE };
  2847. Identifiers.ViewEncapsulation = {
  2848. name: 'ViewEncapsulation',
  2849. moduleName: CORE,
  2850. };
  2851. Identifiers.ChangeDetectionStrategy = {
  2852. name: 'ChangeDetectionStrategy',
  2853. moduleName: CORE,
  2854. };
  2855. Identifiers.SecurityContext = {
  2856. name: 'SecurityContext',
  2857. moduleName: CORE,
  2858. };
  2859. Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE };
  2860. Identifiers.TRANSLATIONS_FORMAT = {
  2861. name: 'TRANSLATIONS_FORMAT',
  2862. moduleName: CORE,
  2863. };
  2864. Identifiers.inlineInterpolate = {
  2865. name: 'ɵinlineInterpolate',
  2866. moduleName: CORE,
  2867. };
  2868. Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE };
  2869. Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE };
  2870. Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE };
  2871. Identifiers.Renderer = { name: 'Renderer', moduleName: CORE };
  2872. Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE };
  2873. Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE };
  2874. Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE };
  2875. Identifiers.textDef = { name: 'ɵted', moduleName: CORE };
  2876. Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE };
  2877. Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE };
  2878. Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE };
  2879. Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE };
  2880. Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE };
  2881. Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE };
  2882. Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE };
  2883. Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE };
  2884. Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE };
  2885. Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE };
  2886. Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE };
  2887. // type only
  2888. Identifiers.RendererType2 = {
  2889. name: 'RendererType2',
  2890. moduleName: CORE,
  2891. };
  2892. // type only
  2893. Identifiers.ViewDefinition = {
  2894. name: 'ɵViewDefinition',
  2895. moduleName: CORE,
  2896. };
  2897. Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE };
  2898. Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
  2899. return Identifiers;
  2900. }());
  2901. function createTokenForReference(reference) {
  2902. return { identifier: { reference: reference } };
  2903. }
  2904. function createTokenForExternalReference(reflector, reference) {
  2905. return createTokenForReference(reflector.resolveExternalReference(reference));
  2906. }
  2907. /**
  2908. * @license
  2909. * Copyright Google Inc. All Rights Reserved.
  2910. *
  2911. * Use of this source code is governed by an MIT-style license that can be
  2912. * found in the LICENSE file at https://angular.io/license
  2913. */
  2914. /**
  2915. * A token representing the a reference to a static type.
  2916. *
  2917. * This token is unique for a filePath and name and can be used as a hash table key.
  2918. */
  2919. var StaticSymbol = /** @class */ (function () {
  2920. function StaticSymbol(filePath, name, members) {
  2921. this.filePath = filePath;
  2922. this.name = name;
  2923. this.members = members;
  2924. }
  2925. StaticSymbol.prototype.assertNoMembers = function () {
  2926. if (this.members.length) {
  2927. throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + ".");
  2928. }
  2929. };
  2930. return StaticSymbol;
  2931. }());
  2932. /**
  2933. * A cache of static symbol used by the StaticReflector to return the same symbol for the
  2934. * same symbol values.
  2935. */
  2936. var StaticSymbolCache = /** @class */ (function () {
  2937. function StaticSymbolCache() {
  2938. this.cache = new Map();
  2939. }
  2940. StaticSymbolCache.prototype.get = function (declarationFile, name, members) {
  2941. members = members || [];
  2942. var memberSuffix = members.length ? "." + members.join('.') : '';
  2943. var key = "\"" + declarationFile + "\"." + name + memberSuffix;
  2944. var result = this.cache.get(key);
  2945. if (!result) {
  2946. result = new StaticSymbol(declarationFile, name, members);
  2947. this.cache.set(key, result);
  2948. }
  2949. return result;
  2950. };
  2951. return StaticSymbolCache;
  2952. }());
  2953. /**
  2954. * @license
  2955. * Copyright Google Inc. All Rights Reserved.
  2956. *
  2957. * Use of this source code is governed by an MIT-style license that can be
  2958. * found in the LICENSE file at https://angular.io/license
  2959. */
  2960. // group 0: "[prop] or (event) or @trigger"
  2961. // group 1: "prop" from "[prop]"
  2962. // group 2: "event" from "(event)"
  2963. // group 3: "@trigger" from "@trigger"
  2964. var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
  2965. function sanitizeIdentifier(name) {
  2966. return name.replace(/\W/g, '_');
  2967. }
  2968. var _anonymousTypeIndex = 0;
  2969. function identifierName(compileIdentifier) {
  2970. if (!compileIdentifier || !compileIdentifier.reference) {
  2971. return null;
  2972. }
  2973. var ref = compileIdentifier.reference;
  2974. if (ref instanceof StaticSymbol) {
  2975. return ref.name;
  2976. }
  2977. if (ref['__anonymousType']) {
  2978. return ref['__anonymousType'];
  2979. }
  2980. var identifier = stringify(ref);
  2981. if (identifier.indexOf('(') >= 0) {
  2982. // case: anonymous functions!
  2983. identifier = "anonymous_" + _anonymousTypeIndex++;
  2984. ref['__anonymousType'] = identifier;
  2985. }
  2986. else {
  2987. identifier = sanitizeIdentifier(identifier);
  2988. }
  2989. return identifier;
  2990. }
  2991. function viewClassName(compType, embeddedTemplateIndex) {
  2992. return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex;
  2993. }
  2994. function rendererTypeName(compType) {
  2995. return "RenderType_" + identifierName({ reference: compType });
  2996. }
  2997. function hostViewClassName(compType) {
  2998. return "HostView_" + identifierName({ reference: compType });
  2999. }
  3000. function componentFactoryName(compType) {
  3001. return identifierName({ reference: compType }) + "NgFactory";
  3002. }
  3003. var CompileSummaryKind;
  3004. (function (CompileSummaryKind) {
  3005. CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
  3006. CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
  3007. CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
  3008. CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
  3009. })(CompileSummaryKind || (CompileSummaryKind = {}));
  3010. function tokenName(token) {
  3011. return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
  3012. }
  3013. function tokenReference(token) {
  3014. if (token.identifier != null) {
  3015. return token.identifier.reference;
  3016. }
  3017. else {
  3018. return token.value;
  3019. }
  3020. }
  3021. /**
  3022. * Metadata about a stylesheet
  3023. */
  3024. var CompileStylesheetMetadata = /** @class */ (function () {
  3025. function CompileStylesheetMetadata(_a) {
  3026. var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls;
  3027. this.moduleUrl = moduleUrl || null;
  3028. this.styles = _normalizeArray(styles);
  3029. this.styleUrls = _normalizeArray(styleUrls);
  3030. }
  3031. return CompileStylesheetMetadata;
  3032. }());
  3033. /**
  3034. * Metadata regarding compilation of a template.
  3035. */
  3036. var CompileTemplateMetadata = /** @class */ (function () {
  3037. function CompileTemplateMetadata(_a) {
  3038. var encapsulation = _a.encapsulation, template = _a.template, templateUrl = _a.templateUrl, htmlAst = _a.htmlAst, styles = _a.styles, styleUrls = _a.styleUrls, externalStylesheets = _a.externalStylesheets, animations = _a.animations, ngContentSelectors = _a.ngContentSelectors, interpolation = _a.interpolation, isInline = _a.isInline, preserveWhitespaces = _a.preserveWhitespaces;
  3039. this.encapsulation = encapsulation;
  3040. this.template = template;
  3041. this.templateUrl = templateUrl;
  3042. this.htmlAst = htmlAst;
  3043. this.styles = _normalizeArray(styles);
  3044. this.styleUrls = _normalizeArray(styleUrls);
  3045. this.externalStylesheets = _normalizeArray(externalStylesheets);
  3046. this.animations = animations ? flatten(animations) : [];
  3047. this.ngContentSelectors = ngContentSelectors || [];
  3048. if (interpolation && interpolation.length != 2) {
  3049. throw new Error("'interpolation' should have a start and an end symbol.");
  3050. }
  3051. this.interpolation = interpolation;
  3052. this.isInline = isInline;
  3053. this.preserveWhitespaces = preserveWhitespaces;
  3054. }
  3055. CompileTemplateMetadata.prototype.toSummary = function () {
  3056. return {
  3057. ngContentSelectors: this.ngContentSelectors,
  3058. encapsulation: this.encapsulation,
  3059. styles: this.styles,
  3060. animations: this.animations
  3061. };
  3062. };
  3063. return CompileTemplateMetadata;
  3064. }());
  3065. /**
  3066. * Metadata regarding compilation of a directive.
  3067. */
  3068. var CompileDirectiveMetadata = /** @class */ (function () {
  3069. function CompileDirectiveMetadata(_a) {
  3070. var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, hostListeners = _a.hostListeners, hostProperties = _a.hostProperties, hostAttributes = _a.hostAttributes, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
  3071. this.isHost = !!isHost;
  3072. this.type = type;
  3073. this.isComponent = isComponent;
  3074. this.selector = selector;
  3075. this.exportAs = exportAs;
  3076. this.changeDetection = changeDetection;
  3077. this.inputs = inputs;
  3078. this.outputs = outputs;
  3079. this.hostListeners = hostListeners;
  3080. this.hostProperties = hostProperties;
  3081. this.hostAttributes = hostAttributes;
  3082. this.providers = _normalizeArray(providers);
  3083. this.viewProviders = _normalizeArray(viewProviders);
  3084. this.queries = _normalizeArray(queries);
  3085. this.guards = guards;
  3086. this.viewQueries = _normalizeArray(viewQueries);
  3087. this.entryComponents = _normalizeArray(entryComponents);
  3088. this.template = template;
  3089. this.componentViewType = componentViewType;
  3090. this.rendererType = rendererType;
  3091. this.componentFactory = componentFactory;
  3092. }
  3093. CompileDirectiveMetadata.create = function (_a) {
  3094. var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, host = _a.host, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
  3095. var hostListeners = {};
  3096. var hostProperties = {};
  3097. var hostAttributes = {};
  3098. if (host != null) {
  3099. Object.keys(host).forEach(function (key) {
  3100. var value = host[key];
  3101. var matches = key.match(HOST_REG_EXP);
  3102. if (matches === null) {
  3103. hostAttributes[key] = value;
  3104. }
  3105. else if (matches[1] != null) {
  3106. hostProperties[matches[1]] = value;
  3107. }
  3108. else if (matches[2] != null) {
  3109. hostListeners[matches[2]] = value;
  3110. }
  3111. });
  3112. }
  3113. var inputsMap = {};
  3114. if (inputs != null) {
  3115. inputs.forEach(function (bindConfig) {
  3116. // canonical syntax: `dirProp: elProp`
  3117. // if there is no `:`, use dirProp = elProp
  3118. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  3119. inputsMap[parts[0]] = parts[1];
  3120. });
  3121. }
  3122. var outputsMap = {};
  3123. if (outputs != null) {
  3124. outputs.forEach(function (bindConfig) {
  3125. // canonical syntax: `dirProp: elProp`
  3126. // if there is no `:`, use dirProp = elProp
  3127. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  3128. outputsMap[parts[0]] = parts[1];
  3129. });
  3130. }
  3131. return new CompileDirectiveMetadata({
  3132. isHost: isHost,
  3133. type: type,
  3134. isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection,
  3135. inputs: inputsMap,
  3136. outputs: outputsMap,
  3137. hostListeners: hostListeners,
  3138. hostProperties: hostProperties,
  3139. hostAttributes: hostAttributes,
  3140. providers: providers,
  3141. viewProviders: viewProviders,
  3142. queries: queries,
  3143. guards: guards,
  3144. viewQueries: viewQueries,
  3145. entryComponents: entryComponents,
  3146. template: template,
  3147. componentViewType: componentViewType,
  3148. rendererType: rendererType,
  3149. componentFactory: componentFactory,
  3150. });
  3151. };
  3152. CompileDirectiveMetadata.prototype.toSummary = function () {
  3153. return {
  3154. summaryKind: CompileSummaryKind.Directive,
  3155. type: this.type,
  3156. isComponent: this.isComponent,
  3157. selector: this.selector,
  3158. exportAs: this.exportAs,
  3159. inputs: this.inputs,
  3160. outputs: this.outputs,
  3161. hostListeners: this.hostListeners,
  3162. hostProperties: this.hostProperties,
  3163. hostAttributes: this.hostAttributes,
  3164. providers: this.providers,
  3165. viewProviders: this.viewProviders,
  3166. queries: this.queries,
  3167. guards: this.guards,
  3168. viewQueries: this.viewQueries,
  3169. entryComponents: this.entryComponents,
  3170. changeDetection: this.changeDetection,
  3171. template: this.template && this.template.toSummary(),
  3172. componentViewType: this.componentViewType,
  3173. rendererType: this.rendererType,
  3174. componentFactory: this.componentFactory
  3175. };
  3176. };
  3177. return CompileDirectiveMetadata;
  3178. }());
  3179. var CompilePipeMetadata = /** @class */ (function () {
  3180. function CompilePipeMetadata(_a) {
  3181. var type = _a.type, name = _a.name, pure = _a.pure;
  3182. this.type = type;
  3183. this.name = name;
  3184. this.pure = !!pure;
  3185. }
  3186. CompilePipeMetadata.prototype.toSummary = function () {
  3187. return {
  3188. summaryKind: CompileSummaryKind.Pipe,
  3189. type: this.type,
  3190. name: this.name,
  3191. pure: this.pure
  3192. };
  3193. };
  3194. return CompilePipeMetadata;
  3195. }());
  3196. /**
  3197. * Metadata regarding compilation of a module.
  3198. */
  3199. var CompileNgModuleMetadata = /** @class */ (function () {
  3200. function CompileNgModuleMetadata(_a) {
  3201. var type = _a.type, providers = _a.providers, declaredDirectives = _a.declaredDirectives, exportedDirectives = _a.exportedDirectives, declaredPipes = _a.declaredPipes, exportedPipes = _a.exportedPipes, entryComponents = _a.entryComponents, bootstrapComponents = _a.bootstrapComponents, importedModules = _a.importedModules, exportedModules = _a.exportedModules, schemas = _a.schemas, transitiveModule = _a.transitiveModule, id = _a.id;
  3202. this.type = type || null;
  3203. this.declaredDirectives = _normalizeArray(declaredDirectives);
  3204. this.exportedDirectives = _normalizeArray(exportedDirectives);
  3205. this.declaredPipes = _normalizeArray(declaredPipes);
  3206. this.exportedPipes = _normalizeArray(exportedPipes);
  3207. this.providers = _normalizeArray(providers);
  3208. this.entryComponents = _normalizeArray(entryComponents);
  3209. this.bootstrapComponents = _normalizeArray(bootstrapComponents);
  3210. this.importedModules = _normalizeArray(importedModules);
  3211. this.exportedModules = _normalizeArray(exportedModules);
  3212. this.schemas = _normalizeArray(schemas);
  3213. this.id = id || null;
  3214. this.transitiveModule = transitiveModule || null;
  3215. }
  3216. CompileNgModuleMetadata.prototype.toSummary = function () {
  3217. var module = this.transitiveModule;
  3218. return {
  3219. summaryKind: CompileSummaryKind.NgModule,
  3220. type: this.type,
  3221. entryComponents: module.entryComponents,
  3222. providers: module.providers,
  3223. modules: module.modules,
  3224. exportedDirectives: module.exportedDirectives,
  3225. exportedPipes: module.exportedPipes
  3226. };
  3227. };
  3228. return CompileNgModuleMetadata;
  3229. }());
  3230. var TransitiveCompileNgModuleMetadata = /** @class */ (function () {
  3231. function TransitiveCompileNgModuleMetadata() {
  3232. this.directivesSet = new Set();
  3233. this.directives = [];
  3234. this.exportedDirectivesSet = new Set();
  3235. this.exportedDirectives = [];
  3236. this.pipesSet = new Set();
  3237. this.pipes = [];
  3238. this.exportedPipesSet = new Set();
  3239. this.exportedPipes = [];
  3240. this.modulesSet = new Set();
  3241. this.modules = [];
  3242. this.entryComponentsSet = new Set();
  3243. this.entryComponents = [];
  3244. this.providers = [];
  3245. }
  3246. TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) {
  3247. this.providers.push({ provider: provider, module: module });
  3248. };
  3249. TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) {
  3250. if (!this.directivesSet.has(id.reference)) {
  3251. this.directivesSet.add(id.reference);
  3252. this.directives.push(id);
  3253. }
  3254. };
  3255. TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) {
  3256. if (!this.exportedDirectivesSet.has(id.reference)) {
  3257. this.exportedDirectivesSet.add(id.reference);
  3258. this.exportedDirectives.push(id);
  3259. }
  3260. };
  3261. TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) {
  3262. if (!this.pipesSet.has(id.reference)) {
  3263. this.pipesSet.add(id.reference);
  3264. this.pipes.push(id);
  3265. }
  3266. };
  3267. TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) {
  3268. if (!this.exportedPipesSet.has(id.reference)) {
  3269. this.exportedPipesSet.add(id.reference);
  3270. this.exportedPipes.push(id);
  3271. }
  3272. };
  3273. TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) {
  3274. if (!this.modulesSet.has(id.reference)) {
  3275. this.modulesSet.add(id.reference);
  3276. this.modules.push(id);
  3277. }
  3278. };
  3279. TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) {
  3280. if (!this.entryComponentsSet.has(ec.componentType)) {
  3281. this.entryComponentsSet.add(ec.componentType);
  3282. this.entryComponents.push(ec);
  3283. }
  3284. };
  3285. return TransitiveCompileNgModuleMetadata;
  3286. }());
  3287. function _normalizeArray(obj) {
  3288. return obj || [];
  3289. }
  3290. var ProviderMeta = /** @class */ (function () {
  3291. function ProviderMeta(token, _a) {
  3292. var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
  3293. this.token = token;
  3294. this.useClass = useClass || null;
  3295. this.useValue = useValue;
  3296. this.useExisting = useExisting;
  3297. this.useFactory = useFactory || null;
  3298. this.dependencies = deps || null;
  3299. this.multi = !!multi;
  3300. }
  3301. return ProviderMeta;
  3302. }());
  3303. function flatten(list) {
  3304. return list.reduce(function (flat, item) {
  3305. var flatItem = Array.isArray(item) ? flatten(item) : item;
  3306. return flat.concat(flatItem);
  3307. }, []);
  3308. }
  3309. function jitSourceUrl(url) {
  3310. // Note: We need 3 "/" so that ng shows up as a separate domain
  3311. // in the chrome dev tools.
  3312. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
  3313. }
  3314. function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
  3315. var url;
  3316. if (templateMeta.isInline) {
  3317. if (compMeta.type.reference instanceof StaticSymbol) {
  3318. // Note: a .ts file might contain multiple components with inline templates,
  3319. // so we need to give them unique urls, as these will be used for sourcemaps.
  3320. url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html";
  3321. }
  3322. else {
  3323. url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html";
  3324. }
  3325. }
  3326. else {
  3327. url = templateMeta.templateUrl;
  3328. }
  3329. return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
  3330. }
  3331. /**
  3332. * @license
  3333. * Copyright Google Inc. All Rights Reserved.
  3334. *
  3335. * Use of this source code is governed by an MIT-style license that can be
  3336. * found in the LICENSE file at https://angular.io/license
  3337. */
  3338. var CORE$1 = '@angular/core';
  3339. var Identifiers$1 = /** @class */ (function () {
  3340. function Identifiers() {
  3341. }
  3342. /* Methods */
  3343. Identifiers.NEW_METHOD = 'factory';
  3344. Identifiers.TRANSFORM_METHOD = 'transform';
  3345. Identifiers.PATCH_DEPS = 'patchedDeps';
  3346. /* Instructions */
  3347. Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 };
  3348. Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 };
  3349. Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 };
  3350. Identifiers.element = { name: 'ɵɵelement', moduleName: CORE$1 };
  3351. Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 };
  3352. Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 };
  3353. Identifiers.select = { name: 'ɵɵselect', moduleName: CORE$1 };
  3354. Identifiers.updateSyntheticHostBinding = { name: 'ɵɵupdateSyntheticHostBinding', moduleName: CORE$1 };
  3355. Identifiers.componentHostSyntheticListener = { name: 'ɵɵcomponentHostSyntheticListener', moduleName: CORE$1 };
  3356. Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 };
  3357. Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 };
  3358. Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 };
  3359. Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 };
  3360. Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 };
  3361. Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 };
  3362. Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 };
  3363. Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 };
  3364. Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 };
  3365. Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 };
  3366. Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 };
  3367. Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 };
  3368. Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 };
  3369. Identifiers.styling = { name: 'ɵɵstyling', moduleName: CORE$1 };
  3370. Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 };
  3371. Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 };
  3372. Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 };
  3373. Identifiers.stylingApply = { name: 'ɵɵstylingApply', moduleName: CORE$1 };
  3374. Identifiers.styleSanitizer = { name: 'ɵɵstyleSanitizer', moduleName: CORE$1 };
  3375. Identifiers.elementHostAttrs = { name: 'ɵɵelementHostAttrs', moduleName: CORE$1 };
  3376. Identifiers.containerCreate = { name: 'ɵɵcontainer', moduleName: CORE$1 };
  3377. Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 };
  3378. Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 };
  3379. Identifiers.text = { name: 'ɵɵtext', moduleName: CORE$1 };
  3380. Identifiers.textBinding = { name: 'ɵɵtextBinding', moduleName: CORE$1 };
  3381. Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 };
  3382. Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 };
  3383. Identifiers.allocHostVars = { name: 'ɵɵallocHostVars', moduleName: CORE$1 };
  3384. Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 };
  3385. Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 };
  3386. Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 };
  3387. Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 };
  3388. Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 };
  3389. Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 };
  3390. Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 };
  3391. Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 };
  3392. Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 };
  3393. Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 };
  3394. Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 };
  3395. Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 };
  3396. Identifiers.interpolation1 = { name: 'ɵɵinterpolation1', moduleName: CORE$1 };
  3397. Identifiers.interpolation2 = { name: 'ɵɵinterpolation2', moduleName: CORE$1 };
  3398. Identifiers.interpolation3 = { name: 'ɵɵinterpolation3', moduleName: CORE$1 };
  3399. Identifiers.interpolation4 = { name: 'ɵɵinterpolation4', moduleName: CORE$1 };
  3400. Identifiers.interpolation5 = { name: 'ɵɵinterpolation5', moduleName: CORE$1 };
  3401. Identifiers.interpolation6 = { name: 'ɵɵinterpolation6', moduleName: CORE$1 };
  3402. Identifiers.interpolation7 = { name: 'ɵɵinterpolation7', moduleName: CORE$1 };
  3403. Identifiers.interpolation8 = { name: 'ɵɵinterpolation8', moduleName: CORE$1 };
  3404. Identifiers.interpolationV = { name: 'ɵɵinterpolationV', moduleName: CORE$1 };
  3405. Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 };
  3406. Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 };
  3407. Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 };
  3408. Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 };
  3409. Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 };
  3410. Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 };
  3411. Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 };
  3412. Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 };
  3413. Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 };
  3414. Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 };
  3415. Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 };
  3416. Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 };
  3417. Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 };
  3418. Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 };
  3419. Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 };
  3420. Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE$1 };
  3421. Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 };
  3422. Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 };
  3423. Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 };
  3424. Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 };
  3425. Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 };
  3426. Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 };
  3427. Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 };
  3428. Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 };
  3429. Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 };
  3430. Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 };
  3431. Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 };
  3432. Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 };
  3433. Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 };
  3434. Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 };
  3435. Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 };
  3436. Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 };
  3437. Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 };
  3438. Identifiers.i18nLocalize = { name: 'ɵɵi18nLocalize', moduleName: CORE$1 };
  3439. Identifiers.load = { name: 'ɵɵload', moduleName: CORE$1 };
  3440. Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 };
  3441. Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE$1 };
  3442. Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 };
  3443. Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE$1 };
  3444. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
  3445. Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 };
  3446. Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
  3447. Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 };
  3448. Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 };
  3449. Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 };
  3450. Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 };
  3451. Identifiers.defineBase = { name: 'ɵɵdefineBase', moduleName: CORE$1 };
  3452. Identifiers.BaseDef = {
  3453. name: 'ɵɵBaseDef',
  3454. moduleName: CORE$1,
  3455. };
  3456. Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 };
  3457. Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 };
  3458. Identifiers.ComponentDefWithMeta = {
  3459. name: 'ɵɵComponentDefWithMeta',
  3460. moduleName: CORE$1,
  3461. };
  3462. Identifiers.defineDirective = {
  3463. name: 'ɵɵdefineDirective',
  3464. moduleName: CORE$1,
  3465. };
  3466. Identifiers.DirectiveDefWithMeta = {
  3467. name: 'ɵɵDirectiveDefWithMeta',
  3468. moduleName: CORE$1,
  3469. };
  3470. Identifiers.InjectorDef = {
  3471. name: 'ɵɵInjectorDef',
  3472. moduleName: CORE$1,
  3473. };
  3474. Identifiers.defineInjector = {
  3475. name: 'ɵɵdefineInjector',
  3476. moduleName: CORE$1,
  3477. };
  3478. Identifiers.NgModuleDefWithMeta = {
  3479. name: 'ɵɵNgModuleDefWithMeta',
  3480. moduleName: CORE$1,
  3481. };
  3482. Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 };
  3483. Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 };
  3484. Identifiers.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 };
  3485. Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 };
  3486. Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 };
  3487. Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 };
  3488. Identifiers.staticViewQuery = { name: 'ɵɵstaticViewQuery', moduleName: CORE$1 };
  3489. Identifiers.staticContentQuery = { name: 'ɵɵstaticContentQuery', moduleName: CORE$1 };
  3490. Identifiers.loadViewQuery = { name: 'ɵɵloadViewQuery', moduleName: CORE$1 };
  3491. Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 };
  3492. Identifiers.loadContentQuery = { name: 'ɵɵloadContentQuery', moduleName: CORE$1 };
  3493. Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 };
  3494. Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 };
  3495. Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 };
  3496. Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE$1 };
  3497. Identifiers.getFactoryOf = {
  3498. name: 'ɵɵgetFactoryOf',
  3499. moduleName: CORE$1,
  3500. };
  3501. Identifiers.getInheritedFactory = {
  3502. name: 'ɵɵgetInheritedFactory',
  3503. moduleName: CORE$1,
  3504. };
  3505. // sanitization-related functions
  3506. Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 };
  3507. Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 };
  3508. Identifiers.defaultStyleSanitizer = { name: 'ɵɵdefaultStyleSanitizer', moduleName: CORE$1 };
  3509. Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 };
  3510. Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 };
  3511. Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 };
  3512. Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 };
  3513. return Identifiers;
  3514. }());
  3515. /**
  3516. * @license
  3517. * Copyright Google Inc. All Rights Reserved.
  3518. *
  3519. * Use of this source code is governed by an MIT-style license that can be
  3520. * found in the LICENSE file at https://angular.io/license
  3521. */
  3522. var $EOF = 0;
  3523. var $BSPACE = 8;
  3524. var $TAB = 9;
  3525. var $LF = 10;
  3526. var $VTAB = 11;
  3527. var $FF = 12;
  3528. var $CR = 13;
  3529. var $SPACE = 32;
  3530. var $BANG = 33;
  3531. var $DQ = 34;
  3532. var $HASH = 35;
  3533. var $$ = 36;
  3534. var $PERCENT = 37;
  3535. var $AMPERSAND = 38;
  3536. var $SQ = 39;
  3537. var $LPAREN = 40;
  3538. var $RPAREN = 41;
  3539. var $STAR = 42;
  3540. var $PLUS = 43;
  3541. var $COMMA = 44;
  3542. var $MINUS = 45;
  3543. var $PERIOD = 46;
  3544. var $SLASH = 47;
  3545. var $COLON = 58;
  3546. var $SEMICOLON = 59;
  3547. var $LT = 60;
  3548. var $EQ = 61;
  3549. var $GT = 62;
  3550. var $QUESTION = 63;
  3551. var $0 = 48;
  3552. var $7 = 55;
  3553. var $9 = 57;
  3554. var $A = 65;
  3555. var $E = 69;
  3556. var $F = 70;
  3557. var $X = 88;
  3558. var $Z = 90;
  3559. var $LBRACKET = 91;
  3560. var $BACKSLASH = 92;
  3561. var $RBRACKET = 93;
  3562. var $CARET = 94;
  3563. var $_ = 95;
  3564. var $a = 97;
  3565. var $b = 98;
  3566. var $e = 101;
  3567. var $f = 102;
  3568. var $n = 110;
  3569. var $r = 114;
  3570. var $t = 116;
  3571. var $u = 117;
  3572. var $v = 118;
  3573. var $x = 120;
  3574. var $z = 122;
  3575. var $LBRACE = 123;
  3576. var $BAR = 124;
  3577. var $RBRACE = 125;
  3578. var $NBSP = 160;
  3579. var $BT = 96;
  3580. function isWhitespace(code) {
  3581. return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
  3582. }
  3583. function isDigit(code) {
  3584. return $0 <= code && code <= $9;
  3585. }
  3586. function isAsciiLetter(code) {
  3587. return code >= $a && code <= $z || code >= $A && code <= $Z;
  3588. }
  3589. function isAsciiHexDigit(code) {
  3590. return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
  3591. }
  3592. function isNewLine(code) {
  3593. return code === $LF || code === $CR;
  3594. }
  3595. function isOctalDigit(code) {
  3596. return $0 <= code && code <= $7;
  3597. }
  3598. /**
  3599. * @license
  3600. * Copyright Google Inc. All Rights Reserved.
  3601. *
  3602. * Use of this source code is governed by an MIT-style license that can be
  3603. * found in the LICENSE file at https://angular.io/license
  3604. */
  3605. var ParseLocation = /** @class */ (function () {
  3606. function ParseLocation(file, offset, line, col) {
  3607. this.file = file;
  3608. this.offset = offset;
  3609. this.line = line;
  3610. this.col = col;
  3611. }
  3612. ParseLocation.prototype.toString = function () {
  3613. return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url;
  3614. };
  3615. ParseLocation.prototype.moveBy = function (delta) {
  3616. var source = this.file.content;
  3617. var len = source.length;
  3618. var offset = this.offset;
  3619. var line = this.line;
  3620. var col = this.col;
  3621. while (offset > 0 && delta < 0) {
  3622. offset--;
  3623. delta++;
  3624. var ch = source.charCodeAt(offset);
  3625. if (ch == $LF) {
  3626. line--;
  3627. var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
  3628. col = priorLine > 0 ? offset - priorLine : offset;
  3629. }
  3630. else {
  3631. col--;
  3632. }
  3633. }
  3634. while (offset < len && delta > 0) {
  3635. var ch = source.charCodeAt(offset);
  3636. offset++;
  3637. delta--;
  3638. if (ch == $LF) {
  3639. line++;
  3640. col = 0;
  3641. }
  3642. else {
  3643. col++;
  3644. }
  3645. }
  3646. return new ParseLocation(this.file, offset, line, col);
  3647. };
  3648. // Return the source around the location
  3649. // Up to `maxChars` or `maxLines` on each side of the location
  3650. ParseLocation.prototype.getContext = function (maxChars, maxLines) {
  3651. var content = this.file.content;
  3652. var startOffset = this.offset;
  3653. if (startOffset != null) {
  3654. if (startOffset > content.length - 1) {
  3655. startOffset = content.length - 1;
  3656. }
  3657. var endOffset = startOffset;
  3658. var ctxChars = 0;
  3659. var ctxLines = 0;
  3660. while (ctxChars < maxChars && startOffset > 0) {
  3661. startOffset--;
  3662. ctxChars++;
  3663. if (content[startOffset] == '\n') {
  3664. if (++ctxLines == maxLines) {
  3665. break;
  3666. }
  3667. }
  3668. }
  3669. ctxChars = 0;
  3670. ctxLines = 0;
  3671. while (ctxChars < maxChars && endOffset < content.length - 1) {
  3672. endOffset++;
  3673. ctxChars++;
  3674. if (content[endOffset] == '\n') {
  3675. if (++ctxLines == maxLines) {
  3676. break;
  3677. }
  3678. }
  3679. }
  3680. return {
  3681. before: content.substring(startOffset, this.offset),
  3682. after: content.substring(this.offset, endOffset + 1),
  3683. };
  3684. }
  3685. return null;
  3686. };
  3687. return ParseLocation;
  3688. }());
  3689. var ParseSourceFile = /** @class */ (function () {
  3690. function ParseSourceFile(content, url) {
  3691. this.content = content;
  3692. this.url = url;
  3693. }
  3694. return ParseSourceFile;
  3695. }());
  3696. var ParseSourceSpan = /** @class */ (function () {
  3697. function ParseSourceSpan(start, end, details) {
  3698. if (details === void 0) { details = null; }
  3699. this.start = start;
  3700. this.end = end;
  3701. this.details = details;
  3702. }
  3703. ParseSourceSpan.prototype.toString = function () {
  3704. return this.start.file.content.substring(this.start.offset, this.end.offset);
  3705. };
  3706. return ParseSourceSpan;
  3707. }());
  3708. var ParseErrorLevel;
  3709. (function (ParseErrorLevel) {
  3710. ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
  3711. ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
  3712. })(ParseErrorLevel || (ParseErrorLevel = {}));
  3713. var ParseError = /** @class */ (function () {
  3714. function ParseError(span, msg, level) {
  3715. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  3716. this.span = span;
  3717. this.msg = msg;
  3718. this.level = level;
  3719. }
  3720. ParseError.prototype.contextualMessage = function () {
  3721. var ctx = this.span.start.getContext(100, 3);
  3722. return ctx ? this.msg + " (\"" + ctx.before + "[" + ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" :
  3723. this.msg;
  3724. };
  3725. ParseError.prototype.toString = function () {
  3726. var details = this.span.details ? ", " + this.span.details : '';
  3727. return this.contextualMessage() + ": " + this.span.start + details;
  3728. };
  3729. return ParseError;
  3730. }());
  3731. /**
  3732. * Generates Source Span object for a given R3 Type for JIT mode.
  3733. *
  3734. * @param kind Component or Directive.
  3735. * @param typeName name of the Component or Directive.
  3736. * @param sourceUrl reference to Component or Directive source.
  3737. * @returns instance of ParseSourceSpan that represent a given Component or Directive.
  3738. */
  3739. function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
  3740. var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl;
  3741. var sourceFile = new ParseSourceFile('', sourceFileName);
  3742. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3743. }
  3744. /**
  3745. * @license
  3746. * Copyright Google Inc. All Rights Reserved.
  3747. *
  3748. * Use of this source code is governed by an MIT-style license that can be
  3749. * found in the LICENSE file at https://angular.io/license
  3750. */
  3751. var Text = /** @class */ (function () {
  3752. function Text(value, sourceSpan) {
  3753. this.value = value;
  3754. this.sourceSpan = sourceSpan;
  3755. }
  3756. Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
  3757. return Text;
  3758. }());
  3759. var BoundText = /** @class */ (function () {
  3760. function BoundText(value, sourceSpan, i18n) {
  3761. this.value = value;
  3762. this.sourceSpan = sourceSpan;
  3763. this.i18n = i18n;
  3764. }
  3765. BoundText.prototype.visit = function (visitor) { return visitor.visitBoundText(this); };
  3766. return BoundText;
  3767. }());
  3768. var TextAttribute = /** @class */ (function () {
  3769. function TextAttribute(name, value, sourceSpan, valueSpan, i18n) {
  3770. this.name = name;
  3771. this.value = value;
  3772. this.sourceSpan = sourceSpan;
  3773. this.valueSpan = valueSpan;
  3774. this.i18n = i18n;
  3775. }
  3776. TextAttribute.prototype.visit = function (visitor) { return visitor.visitTextAttribute(this); };
  3777. return TextAttribute;
  3778. }());
  3779. var BoundAttribute = /** @class */ (function () {
  3780. function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, i18n) {
  3781. this.name = name;
  3782. this.type = type;
  3783. this.securityContext = securityContext;
  3784. this.value = value;
  3785. this.unit = unit;
  3786. this.sourceSpan = sourceSpan;
  3787. this.i18n = i18n;
  3788. }
  3789. BoundAttribute.fromBoundElementProperty = function (prop, i18n) {
  3790. return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, i18n);
  3791. };
  3792. BoundAttribute.prototype.visit = function (visitor) { return visitor.visitBoundAttribute(this); };
  3793. return BoundAttribute;
  3794. }());
  3795. var BoundEvent = /** @class */ (function () {
  3796. function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan) {
  3797. this.name = name;
  3798. this.type = type;
  3799. this.handler = handler;
  3800. this.target = target;
  3801. this.phase = phase;
  3802. this.sourceSpan = sourceSpan;
  3803. this.handlerSpan = handlerSpan;
  3804. }
  3805. BoundEvent.fromParsedEvent = function (event) {
  3806. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  3807. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  3808. return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan);
  3809. };
  3810. BoundEvent.prototype.visit = function (visitor) { return visitor.visitBoundEvent(this); };
  3811. return BoundEvent;
  3812. }());
  3813. var Element = /** @class */ (function () {
  3814. function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3815. this.name = name;
  3816. this.attributes = attributes;
  3817. this.inputs = inputs;
  3818. this.outputs = outputs;
  3819. this.children = children;
  3820. this.references = references;
  3821. this.sourceSpan = sourceSpan;
  3822. this.startSourceSpan = startSourceSpan;
  3823. this.endSourceSpan = endSourceSpan;
  3824. this.i18n = i18n;
  3825. // If the element is empty then the source span should include any closing tag
  3826. if (children.length === 0 && startSourceSpan && endSourceSpan) {
  3827. this.sourceSpan = new ParseSourceSpan(sourceSpan.start, endSourceSpan.end);
  3828. }
  3829. }
  3830. Element.prototype.visit = function (visitor) { return visitor.visitElement(this); };
  3831. return Element;
  3832. }());
  3833. var Template = /** @class */ (function () {
  3834. function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3835. this.tagName = tagName;
  3836. this.attributes = attributes;
  3837. this.inputs = inputs;
  3838. this.outputs = outputs;
  3839. this.templateAttrs = templateAttrs;
  3840. this.children = children;
  3841. this.references = references;
  3842. this.variables = variables;
  3843. this.sourceSpan = sourceSpan;
  3844. this.startSourceSpan = startSourceSpan;
  3845. this.endSourceSpan = endSourceSpan;
  3846. this.i18n = i18n;
  3847. }
  3848. Template.prototype.visit = function (visitor) { return visitor.visitTemplate(this); };
  3849. return Template;
  3850. }());
  3851. var Content = /** @class */ (function () {
  3852. function Content(selector, attributes, sourceSpan, i18n) {
  3853. this.selector = selector;
  3854. this.attributes = attributes;
  3855. this.sourceSpan = sourceSpan;
  3856. this.i18n = i18n;
  3857. }
  3858. Content.prototype.visit = function (visitor) { return visitor.visitContent(this); };
  3859. return Content;
  3860. }());
  3861. var Variable = /** @class */ (function () {
  3862. function Variable(name, value, sourceSpan) {
  3863. this.name = name;
  3864. this.value = value;
  3865. this.sourceSpan = sourceSpan;
  3866. }
  3867. Variable.prototype.visit = function (visitor) { return visitor.visitVariable(this); };
  3868. return Variable;
  3869. }());
  3870. var Reference = /** @class */ (function () {
  3871. function Reference(name, value, sourceSpan) {
  3872. this.name = name;
  3873. this.value = value;
  3874. this.sourceSpan = sourceSpan;
  3875. }
  3876. Reference.prototype.visit = function (visitor) { return visitor.visitReference(this); };
  3877. return Reference;
  3878. }());
  3879. var Icu = /** @class */ (function () {
  3880. function Icu(vars, placeholders, sourceSpan, i18n) {
  3881. this.vars = vars;
  3882. this.placeholders = placeholders;
  3883. this.sourceSpan = sourceSpan;
  3884. this.i18n = i18n;
  3885. }
  3886. Icu.prototype.visit = function (visitor) { return visitor.visitIcu(this); };
  3887. return Icu;
  3888. }());
  3889. function visitAll(visitor, nodes) {
  3890. var e_1, _a, e_2, _b;
  3891. var result = [];
  3892. if (visitor.visit) {
  3893. try {
  3894. for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
  3895. var node = nodes_1_1.value;
  3896. var newNode = visitor.visit(node) || node.visit(visitor);
  3897. }
  3898. }
  3899. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  3900. finally {
  3901. try {
  3902. if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1);
  3903. }
  3904. finally { if (e_1) throw e_1.error; }
  3905. }
  3906. }
  3907. else {
  3908. try {
  3909. for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) {
  3910. var node = nodes_2_1.value;
  3911. var newNode = node.visit(visitor);
  3912. if (newNode) {
  3913. result.push(newNode);
  3914. }
  3915. }
  3916. }
  3917. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  3918. finally {
  3919. try {
  3920. if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2);
  3921. }
  3922. finally { if (e_2) throw e_2.error; }
  3923. }
  3924. }
  3925. return result;
  3926. }
  3927. /**
  3928. * @license
  3929. * Copyright Google Inc. All Rights Reserved.
  3930. *
  3931. * Use of this source code is governed by an MIT-style license that can be
  3932. * found in the LICENSE file at https://angular.io/license
  3933. */
  3934. var Message = /** @class */ (function () {
  3935. /**
  3936. * @param nodes message AST
  3937. * @param placeholders maps placeholder names to static content
  3938. * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
  3939. * @param meaning
  3940. * @param description
  3941. * @param id
  3942. */
  3943. function Message(nodes, placeholders, placeholderToMessage, meaning, description, id) {
  3944. this.nodes = nodes;
  3945. this.placeholders = placeholders;
  3946. this.placeholderToMessage = placeholderToMessage;
  3947. this.meaning = meaning;
  3948. this.description = description;
  3949. this.id = id;
  3950. if (nodes.length) {
  3951. this.sources = [{
  3952. filePath: nodes[0].sourceSpan.start.file.url,
  3953. startLine: nodes[0].sourceSpan.start.line + 1,
  3954. startCol: nodes[0].sourceSpan.start.col + 1,
  3955. endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
  3956. endCol: nodes[0].sourceSpan.start.col + 1
  3957. }];
  3958. }
  3959. else {
  3960. this.sources = [];
  3961. }
  3962. }
  3963. return Message;
  3964. }());
  3965. var Text$1 = /** @class */ (function () {
  3966. function Text(value, sourceSpan) {
  3967. this.value = value;
  3968. this.sourceSpan = sourceSpan;
  3969. }
  3970. Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  3971. return Text;
  3972. }());
  3973. // TODO(vicb): do we really need this node (vs an array) ?
  3974. var Container = /** @class */ (function () {
  3975. function Container(children, sourceSpan) {
  3976. this.children = children;
  3977. this.sourceSpan = sourceSpan;
  3978. }
  3979. Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); };
  3980. return Container;
  3981. }());
  3982. var Icu$1 = /** @class */ (function () {
  3983. function Icu(expression, type, cases, sourceSpan) {
  3984. this.expression = expression;
  3985. this.type = type;
  3986. this.cases = cases;
  3987. this.sourceSpan = sourceSpan;
  3988. }
  3989. Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); };
  3990. return Icu;
  3991. }());
  3992. var TagPlaceholder = /** @class */ (function () {
  3993. function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, sourceSpan) {
  3994. this.tag = tag;
  3995. this.attrs = attrs;
  3996. this.startName = startName;
  3997. this.closeName = closeName;
  3998. this.children = children;
  3999. this.isVoid = isVoid;
  4000. this.sourceSpan = sourceSpan;
  4001. }
  4002. TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); };
  4003. return TagPlaceholder;
  4004. }());
  4005. var Placeholder = /** @class */ (function () {
  4006. function Placeholder(value, name, sourceSpan) {
  4007. this.value = value;
  4008. this.name = name;
  4009. this.sourceSpan = sourceSpan;
  4010. }
  4011. Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); };
  4012. return Placeholder;
  4013. }());
  4014. var IcuPlaceholder = /** @class */ (function () {
  4015. function IcuPlaceholder(value, name, sourceSpan) {
  4016. this.value = value;
  4017. this.name = name;
  4018. this.sourceSpan = sourceSpan;
  4019. }
  4020. IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); };
  4021. return IcuPlaceholder;
  4022. }());
  4023. // Clone the AST
  4024. var CloneVisitor = /** @class */ (function () {
  4025. function CloneVisitor() {
  4026. }
  4027. CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  4028. CloneVisitor.prototype.visitContainer = function (container, context) {
  4029. var _this = this;
  4030. var children = container.children.map(function (n) { return n.visit(_this, context); });
  4031. return new Container(children, container.sourceSpan);
  4032. };
  4033. CloneVisitor.prototype.visitIcu = function (icu, context) {
  4034. var _this = this;
  4035. var cases = {};
  4036. Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); });
  4037. var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
  4038. msg.expressionPlaceholder = icu.expressionPlaceholder;
  4039. return msg;
  4040. };
  4041. CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4042. var _this = this;
  4043. var children = ph.children.map(function (n) { return n.visit(_this, context); });
  4044. return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan);
  4045. };
  4046. CloneVisitor.prototype.visitPlaceholder = function (ph, context) {
  4047. return new Placeholder(ph.value, ph.name, ph.sourceSpan);
  4048. };
  4049. CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4050. return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
  4051. };
  4052. return CloneVisitor;
  4053. }());
  4054. // Visit all the nodes recursively
  4055. var RecurseVisitor = /** @class */ (function () {
  4056. function RecurseVisitor() {
  4057. }
  4058. RecurseVisitor.prototype.visitText = function (text, context) { };
  4059. RecurseVisitor.prototype.visitContainer = function (container, context) {
  4060. var _this = this;
  4061. container.children.forEach(function (child) { return child.visit(_this); });
  4062. };
  4063. RecurseVisitor.prototype.visitIcu = function (icu, context) {
  4064. var _this = this;
  4065. Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); });
  4066. };
  4067. RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4068. var _this = this;
  4069. ph.children.forEach(function (child) { return child.visit(_this); });
  4070. };
  4071. RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { };
  4072. RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { };
  4073. return RecurseVisitor;
  4074. }());
  4075. /**
  4076. * @license
  4077. * Copyright Google Inc. All Rights Reserved.
  4078. *
  4079. * Use of this source code is governed by an MIT-style license that can be
  4080. * found in the LICENSE file at https://angular.io/license
  4081. */
  4082. function digest(message) {
  4083. return message.id || sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
  4084. }
  4085. function decimalDigest(message) {
  4086. if (message.id) {
  4087. return message.id;
  4088. }
  4089. var visitor = new _SerializerIgnoreIcuExpVisitor();
  4090. var parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
  4091. return computeMsgId(parts.join(''), message.meaning);
  4092. }
  4093. /**
  4094. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4095. *
  4096. * The visitor is also used in the i18n parser tests
  4097. *
  4098. * @internal
  4099. */
  4100. var _SerializerVisitor = /** @class */ (function () {
  4101. function _SerializerVisitor() {
  4102. }
  4103. _SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
  4104. _SerializerVisitor.prototype.visitContainer = function (container, context) {
  4105. var _this = this;
  4106. return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]";
  4107. };
  4108. _SerializerVisitor.prototype.visitIcu = function (icu, context) {
  4109. var _this = this;
  4110. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4111. return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}";
  4112. };
  4113. _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4114. var _this = this;
  4115. return ph.isVoid ?
  4116. "<ph tag name=\"" + ph.startName + "\"/>" :
  4117. "<ph tag name=\"" + ph.startName + "\">" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + "</ph name=\"" + ph.closeName + "\">";
  4118. };
  4119. _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
  4120. return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
  4121. };
  4122. _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4123. return "<ph icu name=\"" + ph.name + "\">" + ph.value.visit(this) + "</ph>";
  4124. };
  4125. return _SerializerVisitor;
  4126. }());
  4127. var serializerVisitor = new _SerializerVisitor();
  4128. function serializeNodes(nodes) {
  4129. return nodes.map(function (a) { return a.visit(serializerVisitor, null); });
  4130. }
  4131. /**
  4132. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4133. *
  4134. * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
  4135. *
  4136. * @internal
  4137. */
  4138. var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) {
  4139. __extends(_SerializerIgnoreIcuExpVisitor, _super);
  4140. function _SerializerIgnoreIcuExpVisitor() {
  4141. return _super !== null && _super.apply(this, arguments) || this;
  4142. }
  4143. _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
  4144. var _this = this;
  4145. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4146. // Do not take the expression into account
  4147. return "{" + icu.type + ", " + strCases.join(', ') + "}";
  4148. };
  4149. return _SerializerIgnoreIcuExpVisitor;
  4150. }(_SerializerVisitor));
  4151. /**
  4152. * Compute the SHA1 of the given string
  4153. *
  4154. * see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
  4155. *
  4156. * WARNING: this function has not been designed not tested with security in mind.
  4157. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
  4158. */
  4159. function sha1(str) {
  4160. var _a, _b;
  4161. var utf8 = utf8Encode(str);
  4162. var words32 = stringToWords32(utf8, Endian.Big);
  4163. var len = utf8.length * 8;
  4164. var w = new Array(80);
  4165. var _c = __read([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0], 5), a = _c[0], b = _c[1], c = _c[2], d = _c[3], e = _c[4];
  4166. words32[len >> 5] |= 0x80 << (24 - len % 32);
  4167. words32[((len + 64 >> 9) << 4) + 15] = len;
  4168. for (var i = 0; i < words32.length; i += 16) {
  4169. var _d = __read([a, b, c, d, e], 5), h0 = _d[0], h1 = _d[1], h2 = _d[2], h3 = _d[3], h4 = _d[4];
  4170. for (var j = 0; j < 80; j++) {
  4171. if (j < 16) {
  4172. w[j] = words32[i + j];
  4173. }
  4174. else {
  4175. w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  4176. }
  4177. var _e = __read(fk(j, b, c, d), 2), f = _e[0], k = _e[1];
  4178. var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
  4179. _a = __read([d, c, rol32(b, 30), a, temp], 5), e = _a[0], d = _a[1], c = _a[2], b = _a[3], a = _a[4];
  4180. }
  4181. _b = __read([add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)], 5), a = _b[0], b = _b[1], c = _b[2], d = _b[3], e = _b[4];
  4182. }
  4183. return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
  4184. }
  4185. function fk(index, b, c, d) {
  4186. if (index < 20) {
  4187. return [(b & c) | (~b & d), 0x5a827999];
  4188. }
  4189. if (index < 40) {
  4190. return [b ^ c ^ d, 0x6ed9eba1];
  4191. }
  4192. if (index < 60) {
  4193. return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
  4194. }
  4195. return [b ^ c ^ d, 0xca62c1d6];
  4196. }
  4197. /**
  4198. * Compute the fingerprint of the given string
  4199. *
  4200. * The output is 64 bit number encoded as a decimal string
  4201. *
  4202. * based on:
  4203. * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
  4204. */
  4205. function fingerprint(str) {
  4206. var utf8 = utf8Encode(str);
  4207. var _a = __read([hash32(utf8, 0), hash32(utf8, 102072)], 2), hi = _a[0], lo = _a[1];
  4208. if (hi == 0 && (lo == 0 || lo == 1)) {
  4209. hi = hi ^ 0x130f9bef;
  4210. lo = lo ^ -0x6b5f56d8;
  4211. }
  4212. return [hi, lo];
  4213. }
  4214. function computeMsgId(msg, meaning) {
  4215. var _a;
  4216. var _b = __read(fingerprint(msg), 2), hi = _b[0], lo = _b[1];
  4217. if (meaning) {
  4218. var _c = __read(fingerprint(meaning), 2), him = _c[0], lom = _c[1];
  4219. _a = __read(add64(rol64([hi, lo], 1), [him, lom]), 2), hi = _a[0], lo = _a[1];
  4220. }
  4221. return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
  4222. }
  4223. function hash32(str, c) {
  4224. var _a;
  4225. var _b = __read([0x9e3779b9, 0x9e3779b9], 2), a = _b[0], b = _b[1];
  4226. var i;
  4227. var len = str.length;
  4228. for (i = 0; i + 12 <= len; i += 12) {
  4229. a = add32(a, wordAt(str, i, Endian.Little));
  4230. b = add32(b, wordAt(str, i + 4, Endian.Little));
  4231. c = add32(c, wordAt(str, i + 8, Endian.Little));
  4232. _a = __read(mix([a, b, c]), 3), a = _a[0], b = _a[1], c = _a[2];
  4233. }
  4234. a = add32(a, wordAt(str, i, Endian.Little));
  4235. b = add32(b, wordAt(str, i + 4, Endian.Little));
  4236. // the first byte of c is reserved for the length
  4237. c = add32(c, len);
  4238. c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
  4239. return mix([a, b, c])[2];
  4240. }
  4241. // clang-format off
  4242. function mix(_a) {
  4243. var _b = __read(_a, 3), a = _b[0], b = _b[1], c = _b[2];
  4244. a = sub32(a, b);
  4245. a = sub32(a, c);
  4246. a ^= c >>> 13;
  4247. b = sub32(b, c);
  4248. b = sub32(b, a);
  4249. b ^= a << 8;
  4250. c = sub32(c, a);
  4251. c = sub32(c, b);
  4252. c ^= b >>> 13;
  4253. a = sub32(a, b);
  4254. a = sub32(a, c);
  4255. a ^= c >>> 12;
  4256. b = sub32(b, c);
  4257. b = sub32(b, a);
  4258. b ^= a << 16;
  4259. c = sub32(c, a);
  4260. c = sub32(c, b);
  4261. c ^= b >>> 5;
  4262. a = sub32(a, b);
  4263. a = sub32(a, c);
  4264. a ^= c >>> 3;
  4265. b = sub32(b, c);
  4266. b = sub32(b, a);
  4267. b ^= a << 10;
  4268. c = sub32(c, a);
  4269. c = sub32(c, b);
  4270. c ^= b >>> 15;
  4271. return [a, b, c];
  4272. }
  4273. // clang-format on
  4274. // Utils
  4275. var Endian;
  4276. (function (Endian) {
  4277. Endian[Endian["Little"] = 0] = "Little";
  4278. Endian[Endian["Big"] = 1] = "Big";
  4279. })(Endian || (Endian = {}));
  4280. function add32(a, b) {
  4281. return add32to64(a, b)[1];
  4282. }
  4283. function add32to64(a, b) {
  4284. var low = (a & 0xffff) + (b & 0xffff);
  4285. var high = (a >>> 16) + (b >>> 16) + (low >>> 16);
  4286. return [high >>> 16, (high << 16) | (low & 0xffff)];
  4287. }
  4288. function add64(_a, _b) {
  4289. var _c = __read(_a, 2), ah = _c[0], al = _c[1];
  4290. var _d = __read(_b, 2), bh = _d[0], bl = _d[1];
  4291. var _e = __read(add32to64(al, bl), 2), carry = _e[0], l = _e[1];
  4292. var h = add32(add32(ah, bh), carry);
  4293. return [h, l];
  4294. }
  4295. function sub32(a, b) {
  4296. var low = (a & 0xffff) - (b & 0xffff);
  4297. var high = (a >> 16) - (b >> 16) + (low >> 16);
  4298. return (high << 16) | (low & 0xffff);
  4299. }
  4300. // Rotate a 32b number left `count` position
  4301. function rol32(a, count) {
  4302. return (a << count) | (a >>> (32 - count));
  4303. }
  4304. // Rotate a 64b number left `count` position
  4305. function rol64(_a, count) {
  4306. var _b = __read(_a, 2), hi = _b[0], lo = _b[1];
  4307. var h = (hi << count) | (lo >>> (32 - count));
  4308. var l = (lo << count) | (hi >>> (32 - count));
  4309. return [h, l];
  4310. }
  4311. function stringToWords32(str, endian) {
  4312. var words32 = Array((str.length + 3) >>> 2);
  4313. for (var i = 0; i < words32.length; i++) {
  4314. words32[i] = wordAt(str, i * 4, endian);
  4315. }
  4316. return words32;
  4317. }
  4318. function byteAt(str, index) {
  4319. return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
  4320. }
  4321. function wordAt(str, index, endian) {
  4322. var word = 0;
  4323. if (endian === Endian.Big) {
  4324. for (var i = 0; i < 4; i++) {
  4325. word += byteAt(str, index + i) << (24 - 8 * i);
  4326. }
  4327. }
  4328. else {
  4329. for (var i = 0; i < 4; i++) {
  4330. word += byteAt(str, index + i) << 8 * i;
  4331. }
  4332. }
  4333. return word;
  4334. }
  4335. function words32ToByteString(words32) {
  4336. return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, '');
  4337. }
  4338. function word32ToByteString(word) {
  4339. var str = '';
  4340. for (var i = 0; i < 4; i++) {
  4341. str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
  4342. }
  4343. return str;
  4344. }
  4345. function byteStringToHexString(str) {
  4346. var hex = '';
  4347. for (var i = 0; i < str.length; i++) {
  4348. var b = byteAt(str, i);
  4349. hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
  4350. }
  4351. return hex.toLowerCase();
  4352. }
  4353. // based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b)
  4354. function byteStringToDecString(str) {
  4355. var decimal = '';
  4356. var toThePower = '1';
  4357. for (var i = str.length - 1; i >= 0; i--) {
  4358. decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
  4359. toThePower = numberTimesBigInt(256, toThePower);
  4360. }
  4361. return decimal.split('').reverse().join('');
  4362. }
  4363. // x and y decimal, lowest significant digit first
  4364. function addBigInt(x, y) {
  4365. var sum = '';
  4366. var len = Math.max(x.length, y.length);
  4367. for (var i = 0, carry = 0; i < len || carry; i++) {
  4368. var tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
  4369. if (tmpSum >= 10) {
  4370. carry = 1;
  4371. sum += tmpSum - 10;
  4372. }
  4373. else {
  4374. carry = 0;
  4375. sum += tmpSum;
  4376. }
  4377. }
  4378. return sum;
  4379. }
  4380. function numberTimesBigInt(num, b) {
  4381. var product = '';
  4382. var bToThePower = b;
  4383. for (; num !== 0; num = num >>> 1) {
  4384. if (num & 1)
  4385. product = addBigInt(product, bToThePower);
  4386. bToThePower = addBigInt(bToThePower, bToThePower);
  4387. }
  4388. return product;
  4389. }
  4390. /**
  4391. * @license
  4392. * Copyright Google Inc. All Rights Reserved.
  4393. *
  4394. * Use of this source code is governed by an MIT-style license that can be
  4395. * found in the LICENSE file at https://angular.io/license
  4396. */
  4397. var Serializer = /** @class */ (function () {
  4398. function Serializer() {
  4399. }
  4400. // Creates a name mapper, see `PlaceholderMapper`
  4401. // Returning `null` means that no name mapping is used.
  4402. Serializer.prototype.createNameMapper = function (message) { return null; };
  4403. return Serializer;
  4404. }());
  4405. /**
  4406. * A simple mapper that take a function to transform an internal name to a public name
  4407. */
  4408. var SimplePlaceholderMapper = /** @class */ (function (_super) {
  4409. __extends(SimplePlaceholderMapper, _super);
  4410. // create a mapping from the message
  4411. function SimplePlaceholderMapper(message, mapName) {
  4412. var _this = _super.call(this) || this;
  4413. _this.mapName = mapName;
  4414. _this.internalToPublic = {};
  4415. _this.publicToNextId = {};
  4416. _this.publicToInternal = {};
  4417. message.nodes.forEach(function (node) { return node.visit(_this); });
  4418. return _this;
  4419. }
  4420. SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
  4421. return this.internalToPublic.hasOwnProperty(internalName) ?
  4422. this.internalToPublic[internalName] :
  4423. null;
  4424. };
  4425. SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
  4426. return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
  4427. null;
  4428. };
  4429. SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; };
  4430. SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
  4431. this.visitPlaceholderName(ph.startName);
  4432. _super.prototype.visitTagPlaceholder.call(this, ph, context);
  4433. this.visitPlaceholderName(ph.closeName);
  4434. };
  4435. SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); };
  4436. SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
  4437. this.visitPlaceholderName(ph.name);
  4438. };
  4439. // XMB placeholders could only contains A-Z, 0-9 and _
  4440. SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
  4441. if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
  4442. return;
  4443. }
  4444. var publicName = this.mapName(internalName);
  4445. if (this.publicToInternal.hasOwnProperty(publicName)) {
  4446. // Create a new XMB when it has already been used
  4447. var nextId = this.publicToNextId[publicName];
  4448. this.publicToNextId[publicName] = nextId + 1;
  4449. publicName = publicName + "_" + nextId;
  4450. }
  4451. else {
  4452. this.publicToNextId[publicName] = 1;
  4453. }
  4454. this.internalToPublic[internalName] = publicName;
  4455. this.publicToInternal[publicName] = internalName;
  4456. };
  4457. return SimplePlaceholderMapper;
  4458. }(RecurseVisitor));
  4459. /**
  4460. * @license
  4461. * Copyright Google Inc. All Rights Reserved.
  4462. *
  4463. * Use of this source code is governed by an MIT-style license that can be
  4464. * found in the LICENSE file at https://angular.io/license
  4465. */
  4466. var _Visitor = /** @class */ (function () {
  4467. function _Visitor() {
  4468. }
  4469. _Visitor.prototype.visitTag = function (tag) {
  4470. var _this = this;
  4471. var strAttrs = this._serializeAttributes(tag.attrs);
  4472. if (tag.children.length == 0) {
  4473. return "<" + tag.name + strAttrs + "/>";
  4474. }
  4475. var strChildren = tag.children.map(function (node) { return node.visit(_this); });
  4476. return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "</" + tag.name + ">";
  4477. };
  4478. _Visitor.prototype.visitText = function (text) { return text.value; };
  4479. _Visitor.prototype.visitDeclaration = function (decl) {
  4480. return "<?xml" + this._serializeAttributes(decl.attrs) + " ?>";
  4481. };
  4482. _Visitor.prototype._serializeAttributes = function (attrs) {
  4483. var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
  4484. return strAttrs.length > 0 ? ' ' + strAttrs : '';
  4485. };
  4486. _Visitor.prototype.visitDoctype = function (doctype) {
  4487. return "<!DOCTYPE " + doctype.rootTag + " [\n" + doctype.dtd + "\n]>";
  4488. };
  4489. return _Visitor;
  4490. }());
  4491. var _visitor = new _Visitor();
  4492. function serialize(nodes) {
  4493. return nodes.map(function (node) { return node.visit(_visitor); }).join('');
  4494. }
  4495. var Declaration = /** @class */ (function () {
  4496. function Declaration(unescapedAttrs) {
  4497. var _this = this;
  4498. this.attrs = {};
  4499. Object.keys(unescapedAttrs).forEach(function (k) {
  4500. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4501. });
  4502. }
  4503. Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); };
  4504. return Declaration;
  4505. }());
  4506. var Doctype = /** @class */ (function () {
  4507. function Doctype(rootTag, dtd) {
  4508. this.rootTag = rootTag;
  4509. this.dtd = dtd;
  4510. }
  4511. Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); };
  4512. return Doctype;
  4513. }());
  4514. var Tag = /** @class */ (function () {
  4515. function Tag(name, unescapedAttrs, children) {
  4516. var _this = this;
  4517. if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
  4518. if (children === void 0) { children = []; }
  4519. this.name = name;
  4520. this.children = children;
  4521. this.attrs = {};
  4522. Object.keys(unescapedAttrs).forEach(function (k) {
  4523. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4524. });
  4525. }
  4526. Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); };
  4527. return Tag;
  4528. }());
  4529. var Text$2 = /** @class */ (function () {
  4530. function Text(unescapedValue) {
  4531. this.value = escapeXml(unescapedValue);
  4532. }
  4533. Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
  4534. return Text;
  4535. }());
  4536. var CR = /** @class */ (function (_super) {
  4537. __extends(CR, _super);
  4538. function CR(ws) {
  4539. if (ws === void 0) { ws = 0; }
  4540. return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
  4541. }
  4542. return CR;
  4543. }(Text$2));
  4544. var _ESCAPED_CHARS = [
  4545. [/&/g, '&amp;'],
  4546. [/"/g, '&quot;'],
  4547. [/'/g, '&apos;'],
  4548. [/</g, '&lt;'],
  4549. [/>/g, '&gt;'],
  4550. ];
  4551. // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
  4552. function escapeXml(text) {
  4553. return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
  4554. }
  4555. /**
  4556. * @license
  4557. * Copyright Google Inc. All Rights Reserved.
  4558. *
  4559. * Use of this source code is governed by an MIT-style license that can be
  4560. * found in the LICENSE file at https://angular.io/license
  4561. */
  4562. var _MESSAGES_TAG = 'messagebundle';
  4563. var _MESSAGE_TAG = 'msg';
  4564. var _PLACEHOLDER_TAG = 'ph';
  4565. var _EXAMPLE_TAG = 'ex';
  4566. var _SOURCE_TAG = 'source';
  4567. var _DOCTYPE = "<!ELEMENT messagebundle (msg)*>\n<!ATTLIST messagebundle class CDATA #IMPLIED>\n\n<!ELEMENT msg (#PCDATA|ph|source)*>\n<!ATTLIST msg id CDATA #IMPLIED>\n<!ATTLIST msg seq CDATA #IMPLIED>\n<!ATTLIST msg name CDATA #IMPLIED>\n<!ATTLIST msg desc CDATA #IMPLIED>\n<!ATTLIST msg meaning CDATA #IMPLIED>\n<!ATTLIST msg obsolete (obsolete) #IMPLIED>\n<!ATTLIST msg xml:space (default|preserve) \"default\">\n<!ATTLIST msg is_hidden CDATA #IMPLIED>\n\n<!ELEMENT source (#PCDATA)>\n\n<!ELEMENT ph (#PCDATA|ex)*>\n<!ATTLIST ph name CDATA #REQUIRED>\n\n<!ELEMENT ex (#PCDATA)>";
  4568. var Xmb = /** @class */ (function (_super) {
  4569. __extends(Xmb, _super);
  4570. function Xmb() {
  4571. return _super !== null && _super.apply(this, arguments) || this;
  4572. }
  4573. Xmb.prototype.write = function (messages, locale) {
  4574. var exampleVisitor = new ExampleVisitor();
  4575. var visitor = new _Visitor$1();
  4576. var rootNode = new Tag(_MESSAGES_TAG);
  4577. messages.forEach(function (message) {
  4578. var attrs = { id: message.id };
  4579. if (message.description) {
  4580. attrs['desc'] = message.description;
  4581. }
  4582. if (message.meaning) {
  4583. attrs['meaning'] = message.meaning;
  4584. }
  4585. var sourceTags = [];
  4586. message.sources.forEach(function (source) {
  4587. sourceTags.push(new Tag(_SOURCE_TAG, {}, [
  4588. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  4589. ]));
  4590. });
  4591. rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spread(sourceTags, visitor.serialize(message.nodes))));
  4592. });
  4593. rootNode.children.push(new CR());
  4594. return serialize([
  4595. new Declaration({ version: '1.0', encoding: 'UTF-8' }),
  4596. new CR(),
  4597. new Doctype(_MESSAGES_TAG, _DOCTYPE),
  4598. new CR(),
  4599. exampleVisitor.addDefaultExamples(rootNode),
  4600. new CR(),
  4601. ]);
  4602. };
  4603. Xmb.prototype.load = function (content, url) {
  4604. throw new Error('Unsupported');
  4605. };
  4606. Xmb.prototype.digest = function (message) { return digest$1(message); };
  4607. Xmb.prototype.createNameMapper = function (message) {
  4608. return new SimplePlaceholderMapper(message, toPublicName);
  4609. };
  4610. return Xmb;
  4611. }(Serializer));
  4612. var _Visitor$1 = /** @class */ (function () {
  4613. function _Visitor() {
  4614. }
  4615. _Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  4616. _Visitor.prototype.visitContainer = function (container, context) {
  4617. var _this = this;
  4618. var nodes = [];
  4619. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  4620. return nodes;
  4621. };
  4622. _Visitor.prototype.visitIcu = function (icu, context) {
  4623. var _this = this;
  4624. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  4625. Object.keys(icu.cases).forEach(function (c) {
  4626. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  4627. });
  4628. nodes.push(new Text$2("}"));
  4629. return nodes;
  4630. };
  4631. _Visitor.prototype.visitTagPlaceholder = function (ph, context) {
  4632. var startTagAsText = new Text$2("<" + ph.tag + ">");
  4633. var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
  4634. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4635. var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
  4636. if (ph.isVoid) {
  4637. // void tags have no children nor closing tags
  4638. return [startTagPh];
  4639. }
  4640. var closeTagAsText = new Text$2("</" + ph.tag + ">");
  4641. var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
  4642. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4643. var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
  4644. return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
  4645. };
  4646. _Visitor.prototype.visitPlaceholder = function (ph, context) {
  4647. var interpolationAsText = new Text$2("{{" + ph.value + "}}");
  4648. // Example tag needs to be not-empty for TC.
  4649. var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
  4650. return [
  4651. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4652. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
  4653. ];
  4654. };
  4655. _Visitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4656. var icuExpression = ph.value.expression;
  4657. var icuType = ph.value.type;
  4658. var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  4659. var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}");
  4660. var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
  4661. return [
  4662. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4663. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
  4664. ];
  4665. };
  4666. _Visitor.prototype.serialize = function (nodes) {
  4667. var _this = this;
  4668. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  4669. };
  4670. return _Visitor;
  4671. }());
  4672. function digest$1(message) {
  4673. return decimalDigest(message);
  4674. }
  4675. // TC requires at least one non-empty example on placeholders
  4676. var ExampleVisitor = /** @class */ (function () {
  4677. function ExampleVisitor() {
  4678. }
  4679. ExampleVisitor.prototype.addDefaultExamples = function (node) {
  4680. node.visit(this);
  4681. return node;
  4682. };
  4683. ExampleVisitor.prototype.visitTag = function (tag) {
  4684. var _this = this;
  4685. if (tag.name === _PLACEHOLDER_TAG) {
  4686. if (!tag.children || tag.children.length == 0) {
  4687. var exText = new Text$2(tag.attrs['name'] || '...');
  4688. tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
  4689. }
  4690. }
  4691. else if (tag.children) {
  4692. tag.children.forEach(function (node) { return node.visit(_this); });
  4693. }
  4694. };
  4695. ExampleVisitor.prototype.visitText = function (text) { };
  4696. ExampleVisitor.prototype.visitDeclaration = function (decl) { };
  4697. ExampleVisitor.prototype.visitDoctype = function (doctype) { };
  4698. return ExampleVisitor;
  4699. }());
  4700. // XMB/XTB placeholders can only contain A-Z, 0-9 and _
  4701. function toPublicName(internalName) {
  4702. return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
  4703. }
  4704. /**
  4705. * @license
  4706. * Copyright Google Inc. All Rights Reserved.
  4707. *
  4708. * Use of this source code is governed by an MIT-style license that can be
  4709. * found in the LICENSE file at https://angular.io/license
  4710. */
  4711. function mapLiteral(obj, quoted) {
  4712. if (quoted === void 0) { quoted = false; }
  4713. return literalMap(Object.keys(obj).map(function (key) { return ({
  4714. key: key,
  4715. quoted: quoted,
  4716. value: obj[key],
  4717. }); }));
  4718. }
  4719. /**
  4720. * @license
  4721. * Copyright Google Inc. All Rights Reserved.
  4722. *
  4723. * Use of this source code is governed by an MIT-style license that can be
  4724. * found in the LICENSE file at https://angular.io/license
  4725. */
  4726. /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
  4727. var CLOSURE_TRANSLATION_PREFIX = 'MSG_';
  4728. /* Prefix for non-`goog.getMsg` i18n-related vars */
  4729. var TRANSLATION_PREFIX = 'I18N_';
  4730. /** Closure uses `goog.getMsg(message)` to lookup translations */
  4731. var GOOG_GET_MSG = 'goog.getMsg';
  4732. /** Name of the global variable that is used to determine if we use Closure translations or not */
  4733. var NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
  4734. /** I18n separators for metadata **/
  4735. var I18N_MEANING_SEPARATOR = '|';
  4736. var I18N_ID_SEPARATOR = '@@';
  4737. /** Name of the i18n attributes **/
  4738. var I18N_ATTR = 'i18n';
  4739. var I18N_ATTR_PREFIX = 'i18n-';
  4740. /** Prefix of var expressions used in ICUs */
  4741. var I18N_ICU_VAR_PREFIX = 'VAR_';
  4742. /** Prefix of ICU expressions for post processing */
  4743. var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
  4744. /** Placeholder wrapper for i18n expressions **/
  4745. var I18N_PLACEHOLDER_SYMBOL = '�';
  4746. function i18nTranslationToDeclStmt(variable$1, closureVar, message, meta, params) {
  4747. var statements = [];
  4748. // var I18N_X;
  4749. statements.push(new DeclareVarStmt(variable$1.name, undefined, INFERRED_TYPE, null, variable$1.sourceSpan));
  4750. var args = [literal(message)];
  4751. if (params && Object.keys(params).length) {
  4752. args.push(mapLiteral(params, true));
  4753. }
  4754. // Closure JSDoc comments
  4755. var docStatements = i18nMetaToDocStmt(meta);
  4756. var thenStatements = docStatements ? [docStatements] : [];
  4757. var googFnCall = variable(GOOG_GET_MSG).callFn(args);
  4758. // const MSG_... = goog.getMsg(..);
  4759. thenStatements.push(closureVar.set(googFnCall).toConstDecl());
  4760. // I18N_X = MSG_...;
  4761. thenStatements.push(new ExpressionStatement(variable$1.set(closureVar)));
  4762. var localizeFnCall = importExpr(Identifiers$1.i18nLocalize).callFn(args);
  4763. // I18N_X = i18nLocalize(...);
  4764. var elseStatements = [new ExpressionStatement(variable$1.set(localizeFnCall))];
  4765. // if(ngI18nClosureMode) { ... } else { ... }
  4766. statements.push(ifStmt(variable(NG_I18N_CLOSURE_MODE), thenStatements, elseStatements));
  4767. return statements;
  4768. }
  4769. // Converts i18n meta information for a message (id, description, meaning)
  4770. // to a JsDoc statement formatted as expected by the Closure compiler.
  4771. function i18nMetaToDocStmt(meta) {
  4772. var tags = [];
  4773. if (meta.description) {
  4774. tags.push({ tagName: "desc" /* Desc */, text: meta.description });
  4775. }
  4776. if (meta.meaning) {
  4777. tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
  4778. }
  4779. return tags.length == 0 ? null : new JSDocCommentStmt(tags);
  4780. }
  4781. function isI18nAttribute(name) {
  4782. return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
  4783. }
  4784. function isI18nRootNode(meta) {
  4785. return meta instanceof Message;
  4786. }
  4787. function isSingleI18nIcu(meta) {
  4788. return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
  4789. }
  4790. function hasI18nAttrs(element) {
  4791. return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); });
  4792. }
  4793. function metaFromI18nMessage(message, id) {
  4794. if (id === void 0) { id = null; }
  4795. return {
  4796. id: typeof id === 'string' ? id : message.id || '',
  4797. meaning: message.meaning || '',
  4798. description: message.description || ''
  4799. };
  4800. }
  4801. function icuFromI18nMessage(message) {
  4802. return message.nodes[0];
  4803. }
  4804. function wrapI18nPlaceholder(content, contextId) {
  4805. if (contextId === void 0) { contextId = 0; }
  4806. var blockId = contextId > 0 ? ":" + contextId : '';
  4807. return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL;
  4808. }
  4809. function assembleI18nBoundString(strings, bindingStartIndex, contextId) {
  4810. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  4811. if (contextId === void 0) { contextId = 0; }
  4812. if (!strings.length)
  4813. return '';
  4814. var acc = '';
  4815. var lastIdx = strings.length - 1;
  4816. for (var i = 0; i < lastIdx; i++) {
  4817. acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId);
  4818. }
  4819. acc += strings[lastIdx];
  4820. return acc;
  4821. }
  4822. function getSeqNumberGenerator(startsAt) {
  4823. if (startsAt === void 0) { startsAt = 0; }
  4824. var current = startsAt;
  4825. return function () { return current++; };
  4826. }
  4827. function placeholdersToParams(placeholders) {
  4828. var params = {};
  4829. placeholders.forEach(function (values, key) {
  4830. params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]);
  4831. });
  4832. return params;
  4833. }
  4834. function updatePlaceholderMap(map, name) {
  4835. var values = [];
  4836. for (var _i = 2; _i < arguments.length; _i++) {
  4837. values[_i - 2] = arguments[_i];
  4838. }
  4839. var current = map.get(name) || [];
  4840. current.push.apply(current, __spread(values));
  4841. map.set(name, current);
  4842. }
  4843. function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) {
  4844. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  4845. if (contextId === void 0) { contextId = 0; }
  4846. var startIdx = bindingStartIndex;
  4847. var placeholders = new Map();
  4848. var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta;
  4849. if (node) {
  4850. node
  4851. .children.filter(function (child) { return child instanceof Placeholder; })
  4852. .forEach(function (child, idx) {
  4853. var content = wrapI18nPlaceholder(startIdx + idx, contextId);
  4854. updatePlaceholderMap(placeholders, child.name, content);
  4855. });
  4856. }
  4857. return placeholders;
  4858. }
  4859. function findIndex(items, callback) {
  4860. for (var i = 0; i < items.length; i++) {
  4861. if (callback(items[i])) {
  4862. return i;
  4863. }
  4864. }
  4865. return -1;
  4866. }
  4867. /**
  4868. * Parses i18n metas like:
  4869. * - "@@id",
  4870. * - "description[@@id]",
  4871. * - "meaning|description[@@id]"
  4872. * and returns an object with parsed output.
  4873. *
  4874. * @param meta String that represents i18n meta
  4875. * @returns Object with id, meaning and description fields
  4876. */
  4877. function parseI18nMeta(meta) {
  4878. var _a, _b;
  4879. var id;
  4880. var meaning;
  4881. var description;
  4882. if (meta) {
  4883. var idIndex = meta.indexOf(I18N_ID_SEPARATOR);
  4884. var descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
  4885. var meaningAndDesc = void 0;
  4886. _a = __read((idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  4887. _b = __read((descIndex > -1) ?
  4888. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  4889. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  4890. }
  4891. return { id: id, meaning: meaning, description: description };
  4892. }
  4893. /**
  4894. * Converts internal placeholder names to public-facing format
  4895. * (for example to use in goog.getMsg call).
  4896. * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
  4897. *
  4898. * @param name The placeholder name that should be formatted
  4899. * @returns Formatted placeholder name
  4900. */
  4901. function formatI18nPlaceholderName(name) {
  4902. var chunks = toPublicName(name).split('_');
  4903. if (chunks.length === 1) {
  4904. // if no "_" found - just lowercase the value
  4905. return name.toLowerCase();
  4906. }
  4907. var postfix;
  4908. // eject last element if it's a number
  4909. if (/^\d+$/.test(chunks[chunks.length - 1])) {
  4910. postfix = chunks.pop();
  4911. }
  4912. var raw = chunks.shift().toLowerCase();
  4913. if (chunks.length) {
  4914. raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join('');
  4915. }
  4916. return postfix ? raw + "_" + postfix : raw;
  4917. }
  4918. /**
  4919. * Generates a prefix for translation const name.
  4920. *
  4921. * @param extra Additional local prefix that should be injected into translation var name
  4922. * @returns Complete translation const prefix
  4923. */
  4924. function getTranslationConstPrefix(extra) {
  4925. return ("" + CLOSURE_TRANSLATION_PREFIX + extra).toUpperCase();
  4926. }
  4927. /**
  4928. * Generates translation declaration statements.
  4929. *
  4930. * @param variable Translation value reference
  4931. * @param closureVar Variable for Closure `goog.getMsg` calls
  4932. * @param message Text message to be translated
  4933. * @param meta Object that contains meta information (id, meaning and description)
  4934. * @param params Object with placeholders key-value pairs
  4935. * @param transformFn Optional transformation (post processing) function reference
  4936. * @returns Array of Statements that represent a given translation
  4937. */
  4938. function getTranslationDeclStmts(variable, closureVar, message, meta, params, transformFn) {
  4939. if (params === void 0) { params = {}; }
  4940. var statements = [];
  4941. statements.push.apply(statements, __spread(i18nTranslationToDeclStmt(variable, closureVar, message, meta, params)));
  4942. if (transformFn) {
  4943. statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
  4944. }
  4945. return statements;
  4946. }
  4947. /**
  4948. * @license
  4949. * Copyright Google Inc. All Rights Reserved.
  4950. *
  4951. * Use of this source code is governed by an MIT-style license that can be
  4952. * found in the LICENSE file at https://angular.io/license
  4953. */
  4954. /**
  4955. * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
  4956. * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
  4957. * bot work in some cases when object keys are mangled by minifier.
  4958. *
  4959. * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
  4960. * inputs that contain potentially unsafe chars.
  4961. */
  4962. var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
  4963. /** Name of the temporary to use during data binding */
  4964. var TEMPORARY_NAME = '_t';
  4965. /** Name of the context parameter passed into a template function */
  4966. var CONTEXT_NAME = 'ctx';
  4967. /** Name of the RenderFlag passed into a template function */
  4968. var RENDER_FLAGS = 'rf';
  4969. /** The prefix reference variables */
  4970. var REFERENCE_PREFIX = '_r';
  4971. /** The name of the implicit context reference */
  4972. var IMPLICIT_REFERENCE = '$implicit';
  4973. /** Non bindable attribute name **/
  4974. var NON_BINDABLE_ATTR = 'ngNonBindable';
  4975. /**
  4976. * Creates an allocator for a temporary variable.
  4977. *
  4978. * A variable declaration is added to the statements the first time the allocator is invoked.
  4979. */
  4980. function temporaryAllocator(statements, name) {
  4981. var temp = null;
  4982. return function () {
  4983. if (!temp) {
  4984. statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
  4985. temp = variable(name);
  4986. }
  4987. return temp;
  4988. };
  4989. }
  4990. function unsupported(feature) {
  4991. if (this) {
  4992. throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet");
  4993. }
  4994. throw new Error("Feature " + feature + " is not supported yet");
  4995. }
  4996. function invalid$1(arg) {
  4997. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  4998. }
  4999. function asLiteral(value) {
  5000. if (Array.isArray(value)) {
  5001. return literalArr(value.map(asLiteral));
  5002. }
  5003. return literal(value, INFERRED_TYPE);
  5004. }
  5005. function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
  5006. if (Object.getOwnPropertyNames(keys).length > 0) {
  5007. return mapToExpression(keys, keepDeclared);
  5008. }
  5009. return null;
  5010. }
  5011. function mapToExpression(map, keepDeclared) {
  5012. return literalMap(Object.getOwnPropertyNames(map).map(function (key) {
  5013. var _a, _b;
  5014. // canonical syntax: `dirProp: publicProp`
  5015. // if there is no `:`, use dirProp = elProp
  5016. var value = map[key];
  5017. var declaredName;
  5018. var publicName;
  5019. var minifiedName;
  5020. if (Array.isArray(value)) {
  5021. _a = __read(value, 2), publicName = _a[0], declaredName = _a[1];
  5022. }
  5023. else {
  5024. _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1];
  5025. }
  5026. minifiedName = declaredName;
  5027. return {
  5028. key: minifiedName,
  5029. // put quotes around keys that contain potentially unsafe characters
  5030. quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
  5031. value: (keepDeclared && publicName !== declaredName) ?
  5032. literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
  5033. asLiteral(publicName)
  5034. };
  5035. }));
  5036. }
  5037. /**
  5038. * Remove trailing null nodes as they are implied.
  5039. */
  5040. function trimTrailingNulls(parameters) {
  5041. while (isNull(parameters[parameters.length - 1])) {
  5042. parameters.pop();
  5043. }
  5044. return parameters;
  5045. }
  5046. function getQueryPredicate(query, constantPool) {
  5047. if (Array.isArray(query.predicate)) {
  5048. var predicate_1 = [];
  5049. query.predicate.forEach(function (selector) {
  5050. // Each item in predicates array may contain strings with comma-separated refs
  5051. // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
  5052. // as separate array entities
  5053. var selectors = selector.split(',').map(function (token) { return literal(token.trim()); });
  5054. predicate_1.push.apply(predicate_1, __spread(selectors));
  5055. });
  5056. return constantPool.getConstLiteral(literalArr(predicate_1), true);
  5057. }
  5058. else {
  5059. return query.predicate;
  5060. }
  5061. }
  5062. var DefinitionMap = /** @class */ (function () {
  5063. function DefinitionMap() {
  5064. this.values = [];
  5065. }
  5066. DefinitionMap.prototype.set = function (key, value) {
  5067. if (value) {
  5068. this.values.push({ key: key, value: value, quoted: false });
  5069. }
  5070. };
  5071. DefinitionMap.prototype.toLiteralMap = function () { return literalMap(this.values); };
  5072. return DefinitionMap;
  5073. }());
  5074. /**
  5075. * Extract a map of properties to values for a given element or template node, which can be used
  5076. * by the directive matching machinery.
  5077. *
  5078. * @param elOrTpl the element or template in question
  5079. * @return an object set up for directive matching. For attributes on the element/template, this
  5080. * object maps a property name to its (static) value. For any bindings, this map simply maps the
  5081. * property name to an empty string.
  5082. */
  5083. function getAttrsForDirectiveMatching(elOrTpl) {
  5084. var attributesMap = {};
  5085. if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
  5086. elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; });
  5087. }
  5088. else {
  5089. elOrTpl.attributes.forEach(function (a) {
  5090. if (!isI18nAttribute(a.name)) {
  5091. attributesMap[a.name] = a.value;
  5092. }
  5093. });
  5094. elOrTpl.inputs.forEach(function (i) { attributesMap[i.name] = ''; });
  5095. elOrTpl.outputs.forEach(function (o) { attributesMap[o.name] = ''; });
  5096. }
  5097. return attributesMap;
  5098. }
  5099. /**
  5100. * @license
  5101. * Copyright Google Inc. All Rights Reserved.
  5102. *
  5103. * Use of this source code is governed by an MIT-style license that can be
  5104. * found in the LICENSE file at https://angular.io/license
  5105. */
  5106. var R3FactoryDelegateType;
  5107. (function (R3FactoryDelegateType) {
  5108. R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
  5109. R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
  5110. R3FactoryDelegateType[R3FactoryDelegateType["Factory"] = 2] = "Factory";
  5111. })(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
  5112. /**
  5113. * Resolved type of a dependency.
  5114. *
  5115. * Occasionally, dependencies will have special significance which is known statically. In that
  5116. * case the `R3ResolvedDependencyType` informs the factory generator that a particular dependency
  5117. * should be generated specially (usually by calling a special injection function instead of the
  5118. * standard one).
  5119. */
  5120. var R3ResolvedDependencyType;
  5121. (function (R3ResolvedDependencyType) {
  5122. /**
  5123. * A normal token dependency.
  5124. */
  5125. R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
  5126. /**
  5127. * The dependency is for an attribute.
  5128. *
  5129. * The token expression is a string representing the attribute name.
  5130. */
  5131. R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
  5132. })(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
  5133. /**
  5134. * Construct a factory function expression for the given `R3FactoryMetadata`.
  5135. */
  5136. function compileFactoryFunction(meta) {
  5137. var t = variable('t');
  5138. var statements = [];
  5139. // The type to instantiate via constructor invocation. If there is no delegated factory, meaning
  5140. // this type is always created by constructor invocation, then this is the type-to-create
  5141. // parameter provided by the user (t) if specified, or the current type if not. If there is a
  5142. // delegated factory (which is used to create the current type) then this is only the type-to-
  5143. // create parameter (t).
  5144. var typeForCtor = !isDelegatedMetadata(meta) ? new BinaryOperatorExpr(BinaryOperator.Or, t, meta.type) : t;
  5145. var ctorExpr = null;
  5146. if (meta.deps !== null) {
  5147. // There is a constructor (either explicitly or implicitly defined).
  5148. if (meta.deps !== 'invalid') {
  5149. ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn));
  5150. }
  5151. }
  5152. else {
  5153. var baseFactory = variable("\u0275" + meta.name + "_BaseFactory");
  5154. var getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory);
  5155. var baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.type])).toDeclStmt(INFERRED_TYPE, [
  5156. StmtModifier.Exported, StmtModifier.Final
  5157. ]);
  5158. statements.push(baseFactoryStmt);
  5159. // There is no constructor, use the base class' factory to construct typeForCtor.
  5160. ctorExpr = baseFactory.callFn([typeForCtor]);
  5161. }
  5162. var ctorExprFinal = ctorExpr;
  5163. var body = [];
  5164. var retExpr = null;
  5165. function makeConditionalFactory(nonCtorExpr) {
  5166. var r = variable('r');
  5167. body.push(r.set(NULL_EXPR).toDeclStmt());
  5168. var ctorStmt = null;
  5169. if (ctorExprFinal !== null) {
  5170. ctorStmt = r.set(ctorExprFinal).toStmt();
  5171. }
  5172. else {
  5173. ctorStmt = makeErrorStmt(meta.name);
  5174. }
  5175. body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
  5176. return r;
  5177. }
  5178. if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) {
  5179. var delegateFactory = variable("\u0275" + meta.name + "_BaseFactory");
  5180. var getFactoryOf = importExpr(Identifiers$1.getFactoryOf);
  5181. if (meta.delegate.isEquivalent(meta.type)) {
  5182. throw new Error("Illegal state: compiling factory that delegates to itself");
  5183. }
  5184. var delegateFactoryStmt = delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt(INFERRED_TYPE, [
  5185. StmtModifier.Exported, StmtModifier.Final
  5186. ]);
  5187. statements.push(delegateFactoryStmt);
  5188. retExpr = makeConditionalFactory(delegateFactory.callFn([]));
  5189. }
  5190. else if (isDelegatedMetadata(meta)) {
  5191. // This type is created with a delegated factory. If a type parameter is not specified, call
  5192. // the factory instead.
  5193. var delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn);
  5194. // Either call `new delegate(...)` or `delegate(...)` depending on meta.useNewForDelegate.
  5195. var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
  5196. InstantiateExpr :
  5197. InvokeFunctionExpr)(meta.delegate, delegateArgs);
  5198. retExpr = makeConditionalFactory(factoryExpr);
  5199. }
  5200. else if (isExpressionFactoryMetadata(meta)) {
  5201. // TODO(alxhub): decide whether to lower the value here or in the caller
  5202. retExpr = makeConditionalFactory(meta.expression);
  5203. }
  5204. else {
  5205. retExpr = ctorExpr;
  5206. }
  5207. if (retExpr !== null) {
  5208. body.push(new ReturnStatement(retExpr));
  5209. }
  5210. else {
  5211. body.push(makeErrorStmt(meta.name));
  5212. }
  5213. return {
  5214. factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory"),
  5215. statements: statements,
  5216. };
  5217. }
  5218. function injectDependencies(deps, injectFn) {
  5219. return deps.map(function (dep) { return compileInjectDependency(dep, injectFn); });
  5220. }
  5221. function compileInjectDependency(dep, injectFn) {
  5222. // Interpret the dependency according to its resolved type.
  5223. switch (dep.resolved) {
  5224. case R3ResolvedDependencyType.Token: {
  5225. // Build up the injection flags according to the metadata.
  5226. var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
  5227. (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
  5228. (dep.optional ? 8 /* Optional */ : 0);
  5229. // Build up the arguments to the injectFn call.
  5230. var injectArgs = [dep.token];
  5231. // If this dependency is optional or otherwise has non-default flags, then additional
  5232. // parameters describing how to inject the dependency must be passed to the inject function
  5233. // that's being used.
  5234. if (flags !== 0 /* Default */ || dep.optional) {
  5235. injectArgs.push(literal(flags));
  5236. }
  5237. return importExpr(injectFn).callFn(injectArgs);
  5238. }
  5239. case R3ResolvedDependencyType.Attribute:
  5240. // In the case of attributes, the attribute name in question is given as the token.
  5241. return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]);
  5242. default:
  5243. return unsupported("Unknown R3ResolvedDependencyType: " + R3ResolvedDependencyType[dep.resolved]);
  5244. }
  5245. }
  5246. function makeErrorStmt(name) {
  5247. return new ThrowStmt(new InstantiateExpr(new ReadVarExpr('Error'), [
  5248. literal(name + " has a constructor which is not compatible with Dependency Injection. It should probably not be @Injectable().")
  5249. ]));
  5250. }
  5251. function isDelegatedMetadata(meta) {
  5252. return meta.delegateType !== undefined;
  5253. }
  5254. function isExpressionFactoryMetadata(meta) {
  5255. return meta.expression !== undefined;
  5256. }
  5257. /**
  5258. * @license
  5259. * Copyright Google Inc. All Rights Reserved.
  5260. *
  5261. * Use of this source code is governed by an MIT-style license that can be
  5262. * found in the LICENSE file at https://angular.io/license
  5263. */
  5264. /**
  5265. * Convert an object map with `Expression` values into a `LiteralMapExpr`.
  5266. */
  5267. function mapToMapExpression(map) {
  5268. var result = Object.keys(map).map(function (key) { return ({ key: key, value: map[key], quoted: false }); });
  5269. return literalMap(result);
  5270. }
  5271. function typeWithParameters(type, numParams) {
  5272. var params = null;
  5273. if (numParams > 0) {
  5274. params = [];
  5275. for (var i = 0; i < numParams; i++) {
  5276. params.push(DYNAMIC_TYPE);
  5277. }
  5278. }
  5279. return expressionType(type, null, params);
  5280. }
  5281. var ANIMATE_SYMBOL_PREFIX = '@';
  5282. function prepareSyntheticPropertyName(name) {
  5283. return "" + ANIMATE_SYMBOL_PREFIX + name;
  5284. }
  5285. function prepareSyntheticListenerName(name, phase) {
  5286. return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase;
  5287. }
  5288. function prepareSyntheticListenerFunctionName(name, phase) {
  5289. return "animation_" + name + "_" + phase;
  5290. }
  5291. /**
  5292. * @license
  5293. * Copyright Google Inc. All Rights Reserved.
  5294. *
  5295. * Use of this source code is governed by an MIT-style license that can be
  5296. * found in the LICENSE file at https://angular.io/license
  5297. */
  5298. function compileInjectable(meta) {
  5299. var result = null;
  5300. var factoryMeta = {
  5301. name: meta.name,
  5302. type: meta.type,
  5303. deps: meta.ctorDeps,
  5304. injectFn: Identifiers.inject,
  5305. };
  5306. if (meta.useClass !== undefined) {
  5307. // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
  5308. // used to instantiate the class with dependencies injected, or deps are not specified and
  5309. // the factory of the class is used to instantiate it.
  5310. //
  5311. // A special case exists for useClass: Type where Type is the injectable type itself and no
  5312. // deps are specified, in which case 'useClass' is effectively ignored.
  5313. var useClassOnSelf = meta.useClass.isEquivalent(meta.type);
  5314. var deps = undefined;
  5315. if (meta.userDeps !== undefined) {
  5316. deps = meta.userDeps;
  5317. }
  5318. if (deps !== undefined) {
  5319. // factory: () => new meta.useClass(...deps)
  5320. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
  5321. }
  5322. else if (useClassOnSelf) {
  5323. result = compileFactoryFunction(factoryMeta);
  5324. }
  5325. else {
  5326. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateType: R3FactoryDelegateType.Factory }));
  5327. }
  5328. }
  5329. else if (meta.useFactory !== undefined) {
  5330. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function }));
  5331. }
  5332. else if (meta.useValue !== undefined) {
  5333. // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
  5334. // client code because meta.useValue is an Expression which will be defined even if the actual
  5335. // value is undefined.
  5336. result = compileFactoryFunction(__assign({}, factoryMeta, { expression: meta.useValue }));
  5337. }
  5338. else if (meta.useExisting !== undefined) {
  5339. // useExisting is an `inject` call on the existing token.
  5340. result = compileFactoryFunction(__assign({}, factoryMeta, { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) }));
  5341. }
  5342. else {
  5343. result = compileFactoryFunction(factoryMeta);
  5344. }
  5345. var token = meta.type;
  5346. var providedIn = meta.providedIn;
  5347. var expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression({ token: token, factory: result.factory, providedIn: providedIn })]);
  5348. var type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type, meta.typeArgumentCount)]));
  5349. return {
  5350. expression: expression,
  5351. type: type,
  5352. statements: result.statements,
  5353. };
  5354. }
  5355. /**
  5356. * @license
  5357. * Copyright Google Inc. All Rights Reserved.
  5358. *
  5359. * Use of this source code is governed by an MIT-style license that can be
  5360. * found in the LICENSE file at https://angular.io/license
  5361. */
  5362. function assertArrayOfStrings(identifier, value) {
  5363. if (value == null) {
  5364. return;
  5365. }
  5366. if (!Array.isArray(value)) {
  5367. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  5368. }
  5369. for (var i = 0; i < value.length; i += 1) {
  5370. if (typeof value[i] !== 'string') {
  5371. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  5372. }
  5373. }
  5374. }
  5375. var UNUSABLE_INTERPOLATION_REGEXPS = [
  5376. /^\s*$/,
  5377. /[<>]/,
  5378. /^[{}]$/,
  5379. /&(#|[a-z])/i,
  5380. /^\/\//,
  5381. ];
  5382. function assertInterpolationSymbols(identifier, value) {
  5383. if (value != null && !(Array.isArray(value) && value.length == 2)) {
  5384. throw new Error("Expected '" + identifier + "' to be an array, [start, end].");
  5385. }
  5386. else if (value != null) {
  5387. var start_1 = value[0];
  5388. var end_1 = value[1];
  5389. // Check for unusable interpolation symbols
  5390. UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) {
  5391. if (regexp.test(start_1) || regexp.test(end_1)) {
  5392. throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol.");
  5393. }
  5394. });
  5395. }
  5396. }
  5397. /**
  5398. * @license
  5399. * Copyright Google Inc. All Rights Reserved.
  5400. *
  5401. * Use of this source code is governed by an MIT-style license that can be
  5402. * found in the LICENSE file at https://angular.io/license
  5403. */
  5404. var InterpolationConfig = /** @class */ (function () {
  5405. function InterpolationConfig(start, end) {
  5406. this.start = start;
  5407. this.end = end;
  5408. }
  5409. InterpolationConfig.fromArray = function (markers) {
  5410. if (!markers) {
  5411. return DEFAULT_INTERPOLATION_CONFIG;
  5412. }
  5413. assertInterpolationSymbols('interpolation', markers);
  5414. return new InterpolationConfig(markers[0], markers[1]);
  5415. };
  5416. return InterpolationConfig;
  5417. }());
  5418. var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
  5419. /**
  5420. * @license
  5421. * Copyright Google Inc. All Rights Reserved.
  5422. *
  5423. * Use of this source code is governed by an MIT-style license that can be
  5424. * found in the LICENSE file at https://angular.io/license
  5425. */
  5426. // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  5427. var VERSION = 3;
  5428. var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
  5429. var SourceMapGenerator = /** @class */ (function () {
  5430. function SourceMapGenerator(file) {
  5431. if (file === void 0) { file = null; }
  5432. this.file = file;
  5433. this.sourcesContent = new Map();
  5434. this.lines = [];
  5435. this.lastCol0 = 0;
  5436. this.hasMappings = false;
  5437. }
  5438. // The content is `null` when the content is expected to be loaded using the URL
  5439. SourceMapGenerator.prototype.addSource = function (url, content) {
  5440. if (content === void 0) { content = null; }
  5441. if (!this.sourcesContent.has(url)) {
  5442. this.sourcesContent.set(url, content);
  5443. }
  5444. return this;
  5445. };
  5446. SourceMapGenerator.prototype.addLine = function () {
  5447. this.lines.push([]);
  5448. this.lastCol0 = 0;
  5449. return this;
  5450. };
  5451. SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
  5452. if (!this.currentLine) {
  5453. throw new Error("A line must be added before mappings can be added");
  5454. }
  5455. if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
  5456. throw new Error("Unknown source file \"" + sourceUrl + "\"");
  5457. }
  5458. if (col0 == null) {
  5459. throw new Error("The column in the generated code must be provided");
  5460. }
  5461. if (col0 < this.lastCol0) {
  5462. throw new Error("Mapping should be added in output order");
  5463. }
  5464. if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
  5465. throw new Error("The source location must be provided when a source url is provided");
  5466. }
  5467. this.hasMappings = true;
  5468. this.lastCol0 = col0;
  5469. this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
  5470. return this;
  5471. };
  5472. Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
  5473. get: function () { return this.lines.slice(-1)[0]; },
  5474. enumerable: true,
  5475. configurable: true
  5476. });
  5477. SourceMapGenerator.prototype.toJSON = function () {
  5478. var _this = this;
  5479. if (!this.hasMappings) {
  5480. return null;
  5481. }
  5482. var sourcesIndex = new Map();
  5483. var sources = [];
  5484. var sourcesContent = [];
  5485. Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
  5486. sourcesIndex.set(url, i);
  5487. sources.push(url);
  5488. sourcesContent.push(_this.sourcesContent.get(url) || null);
  5489. });
  5490. var mappings = '';
  5491. var lastCol0 = 0;
  5492. var lastSourceIndex = 0;
  5493. var lastSourceLine0 = 0;
  5494. var lastSourceCol0 = 0;
  5495. this.lines.forEach(function (segments) {
  5496. lastCol0 = 0;
  5497. mappings += segments
  5498. .map(function (segment) {
  5499. // zero-based starting column of the line in the generated code
  5500. var segAsStr = toBase64VLQ(segment.col0 - lastCol0);
  5501. lastCol0 = segment.col0;
  5502. if (segment.sourceUrl != null) {
  5503. // zero-based index into the “sources” list
  5504. segAsStr +=
  5505. toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
  5506. lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
  5507. // the zero-based starting line in the original source
  5508. segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
  5509. lastSourceLine0 = segment.sourceLine0;
  5510. // the zero-based starting column in the original source
  5511. segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
  5512. lastSourceCol0 = segment.sourceCol0;
  5513. }
  5514. return segAsStr;
  5515. })
  5516. .join(',');
  5517. mappings += ';';
  5518. });
  5519. mappings = mappings.slice(0, -1);
  5520. return {
  5521. 'file': this.file || '',
  5522. 'version': VERSION,
  5523. 'sourceRoot': '',
  5524. 'sources': sources,
  5525. 'sourcesContent': sourcesContent,
  5526. 'mappings': mappings,
  5527. };
  5528. };
  5529. SourceMapGenerator.prototype.toJsComment = function () {
  5530. return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
  5531. '';
  5532. };
  5533. return SourceMapGenerator;
  5534. }());
  5535. function toBase64String(value) {
  5536. var b64 = '';
  5537. value = utf8Encode(value);
  5538. for (var i = 0; i < value.length;) {
  5539. var i1 = value.charCodeAt(i++);
  5540. var i2 = value.charCodeAt(i++);
  5541. var i3 = value.charCodeAt(i++);
  5542. b64 += toBase64Digit(i1 >> 2);
  5543. b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
  5544. b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
  5545. b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
  5546. }
  5547. return b64;
  5548. }
  5549. function toBase64VLQ(value) {
  5550. value = value < 0 ? ((-value) << 1) + 1 : value << 1;
  5551. var out = '';
  5552. do {
  5553. var digit = value & 31;
  5554. value = value >> 5;
  5555. if (value > 0) {
  5556. digit = digit | 32;
  5557. }
  5558. out += toBase64Digit(digit);
  5559. } while (value > 0);
  5560. return out;
  5561. }
  5562. var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5563. function toBase64Digit(value) {
  5564. if (value < 0 || value >= 64) {
  5565. throw new Error("Can only encode value in the range [0, 63]");
  5566. }
  5567. return B64_DIGITS[value];
  5568. }
  5569. /**
  5570. * @license
  5571. * Copyright Google Inc. All Rights Reserved.
  5572. *
  5573. * Use of this source code is governed by an MIT-style license that can be
  5574. * found in the LICENSE file at https://angular.io/license
  5575. */
  5576. var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
  5577. var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
  5578. var _INDENT_WITH = ' ';
  5579. var CATCH_ERROR_VAR$1 = variable('error', null, null);
  5580. var CATCH_STACK_VAR$1 = variable('stack', null, null);
  5581. var _EmittedLine = /** @class */ (function () {
  5582. function _EmittedLine(indent) {
  5583. this.indent = indent;
  5584. this.partsLength = 0;
  5585. this.parts = [];
  5586. this.srcSpans = [];
  5587. }
  5588. return _EmittedLine;
  5589. }());
  5590. var EmitterVisitorContext = /** @class */ (function () {
  5591. function EmitterVisitorContext(_indent) {
  5592. this._indent = _indent;
  5593. this._classes = [];
  5594. this._preambleLineCount = 0;
  5595. this._lines = [new _EmittedLine(_indent)];
  5596. }
  5597. EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); };
  5598. Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
  5599. get: function () { return this._lines[this._lines.length - 1]; },
  5600. enumerable: true,
  5601. configurable: true
  5602. });
  5603. EmitterVisitorContext.prototype.println = function (from, lastPart) {
  5604. if (lastPart === void 0) { lastPart = ''; }
  5605. this.print(from || null, lastPart, true);
  5606. };
  5607. EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; };
  5608. EmitterVisitorContext.prototype.lineLength = function () {
  5609. return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
  5610. };
  5611. EmitterVisitorContext.prototype.print = function (from, part, newLine) {
  5612. if (newLine === void 0) { newLine = false; }
  5613. if (part.length > 0) {
  5614. this._currentLine.parts.push(part);
  5615. this._currentLine.partsLength += part.length;
  5616. this._currentLine.srcSpans.push(from && from.sourceSpan || null);
  5617. }
  5618. if (newLine) {
  5619. this._lines.push(new _EmittedLine(this._indent));
  5620. }
  5621. };
  5622. EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
  5623. if (this.lineIsEmpty()) {
  5624. this._lines.pop();
  5625. }
  5626. };
  5627. EmitterVisitorContext.prototype.incIndent = function () {
  5628. this._indent++;
  5629. if (this.lineIsEmpty()) {
  5630. this._currentLine.indent = this._indent;
  5631. }
  5632. };
  5633. EmitterVisitorContext.prototype.decIndent = function () {
  5634. this._indent--;
  5635. if (this.lineIsEmpty()) {
  5636. this._currentLine.indent = this._indent;
  5637. }
  5638. };
  5639. EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); };
  5640. EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); };
  5641. Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
  5642. get: function () {
  5643. return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
  5644. },
  5645. enumerable: true,
  5646. configurable: true
  5647. });
  5648. EmitterVisitorContext.prototype.toSource = function () {
  5649. return this.sourceLines
  5650. .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
  5651. .join('\n');
  5652. };
  5653. EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) {
  5654. if (startsAtLine === void 0) { startsAtLine = 0; }
  5655. var map = new SourceMapGenerator(genFilePath);
  5656. var firstOffsetMapped = false;
  5657. var mapFirstOffsetIfNeeded = function () {
  5658. if (!firstOffsetMapped) {
  5659. // Add a single space so that tools won't try to load the file from disk.
  5660. // Note: We are using virtual urls like `ng:///`, so we have to
  5661. // provide a content here.
  5662. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
  5663. firstOffsetMapped = true;
  5664. }
  5665. };
  5666. for (var i = 0; i < startsAtLine; i++) {
  5667. map.addLine();
  5668. mapFirstOffsetIfNeeded();
  5669. }
  5670. this.sourceLines.forEach(function (line, lineIdx) {
  5671. map.addLine();
  5672. var spans = line.srcSpans;
  5673. var parts = line.parts;
  5674. var col0 = line.indent * _INDENT_WITH.length;
  5675. var spanIdx = 0;
  5676. // skip leading parts without source spans
  5677. while (spanIdx < spans.length && !spans[spanIdx]) {
  5678. col0 += parts[spanIdx].length;
  5679. spanIdx++;
  5680. }
  5681. if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
  5682. firstOffsetMapped = true;
  5683. }
  5684. else {
  5685. mapFirstOffsetIfNeeded();
  5686. }
  5687. while (spanIdx < spans.length) {
  5688. var span = spans[spanIdx];
  5689. var source = span.start.file;
  5690. var sourceLine = span.start.line;
  5691. var sourceCol = span.start.col;
  5692. map.addSource(source.url, source.content)
  5693. .addMapping(col0, source.url, sourceLine, sourceCol);
  5694. col0 += parts[spanIdx].length;
  5695. spanIdx++;
  5696. // assign parts without span or the same span to the previous segment
  5697. while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
  5698. col0 += parts[spanIdx].length;
  5699. spanIdx++;
  5700. }
  5701. }
  5702. });
  5703. return map;
  5704. };
  5705. EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; };
  5706. EmitterVisitorContext.prototype.spanOf = function (line, column) {
  5707. var emittedLine = this._lines[line - this._preambleLineCount];
  5708. if (emittedLine) {
  5709. var columnsLeft = column - _createIndent(emittedLine.indent).length;
  5710. for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
  5711. var part = emittedLine.parts[partIndex];
  5712. if (part.length > columnsLeft) {
  5713. return emittedLine.srcSpans[partIndex];
  5714. }
  5715. columnsLeft -= part.length;
  5716. }
  5717. }
  5718. return null;
  5719. };
  5720. Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
  5721. get: function () {
  5722. if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
  5723. return this._lines.slice(0, -1);
  5724. }
  5725. return this._lines;
  5726. },
  5727. enumerable: true,
  5728. configurable: true
  5729. });
  5730. return EmitterVisitorContext;
  5731. }());
  5732. var AbstractEmitterVisitor = /** @class */ (function () {
  5733. function AbstractEmitterVisitor(_escapeDollarInStrings) {
  5734. this._escapeDollarInStrings = _escapeDollarInStrings;
  5735. }
  5736. AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
  5737. stmt.expr.visitExpression(this, ctx);
  5738. ctx.println(stmt, ';');
  5739. return null;
  5740. };
  5741. AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
  5742. ctx.print(stmt, "return ");
  5743. stmt.value.visitExpression(this, ctx);
  5744. ctx.println(stmt, ';');
  5745. return null;
  5746. };
  5747. AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
  5748. ctx.print(stmt, "if (");
  5749. stmt.condition.visitExpression(this, ctx);
  5750. ctx.print(stmt, ") {");
  5751. var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
  5752. if (stmt.trueCase.length <= 1 && !hasElseCase) {
  5753. ctx.print(stmt, " ");
  5754. this.visitAllStatements(stmt.trueCase, ctx);
  5755. ctx.removeEmptyLastLine();
  5756. ctx.print(stmt, " ");
  5757. }
  5758. else {
  5759. ctx.println();
  5760. ctx.incIndent();
  5761. this.visitAllStatements(stmt.trueCase, ctx);
  5762. ctx.decIndent();
  5763. if (hasElseCase) {
  5764. ctx.println(stmt, "} else {");
  5765. ctx.incIndent();
  5766. this.visitAllStatements(stmt.falseCase, ctx);
  5767. ctx.decIndent();
  5768. }
  5769. }
  5770. ctx.println(stmt, "}");
  5771. return null;
  5772. };
  5773. AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
  5774. ctx.print(stmt, "throw ");
  5775. stmt.error.visitExpression(this, ctx);
  5776. ctx.println(stmt, ";");
  5777. return null;
  5778. };
  5779. AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) {
  5780. if (stmt.multiline) {
  5781. ctx.println(stmt, "/* " + stmt.comment + " */");
  5782. }
  5783. else {
  5784. stmt.comment.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); });
  5785. }
  5786. return null;
  5787. };
  5788. AbstractEmitterVisitor.prototype.visitJSDocCommentStmt = function (stmt, ctx) {
  5789. ctx.println(stmt, "/*" + stmt.toString() + "*/");
  5790. return null;
  5791. };
  5792. AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
  5793. var lineWasEmpty = ctx.lineIsEmpty();
  5794. if (!lineWasEmpty) {
  5795. ctx.print(expr, '(');
  5796. }
  5797. ctx.print(expr, expr.name + " = ");
  5798. expr.value.visitExpression(this, ctx);
  5799. if (!lineWasEmpty) {
  5800. ctx.print(expr, ')');
  5801. }
  5802. return null;
  5803. };
  5804. AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
  5805. var lineWasEmpty = ctx.lineIsEmpty();
  5806. if (!lineWasEmpty) {
  5807. ctx.print(expr, '(');
  5808. }
  5809. expr.receiver.visitExpression(this, ctx);
  5810. ctx.print(expr, "[");
  5811. expr.index.visitExpression(this, ctx);
  5812. ctx.print(expr, "] = ");
  5813. expr.value.visitExpression(this, ctx);
  5814. if (!lineWasEmpty) {
  5815. ctx.print(expr, ')');
  5816. }
  5817. return null;
  5818. };
  5819. AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
  5820. var lineWasEmpty = ctx.lineIsEmpty();
  5821. if (!lineWasEmpty) {
  5822. ctx.print(expr, '(');
  5823. }
  5824. expr.receiver.visitExpression(this, ctx);
  5825. ctx.print(expr, "." + expr.name + " = ");
  5826. expr.value.visitExpression(this, ctx);
  5827. if (!lineWasEmpty) {
  5828. ctx.print(expr, ')');
  5829. }
  5830. return null;
  5831. };
  5832. AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  5833. expr.receiver.visitExpression(this, ctx);
  5834. var name = expr.name;
  5835. if (expr.builtin != null) {
  5836. name = this.getBuiltinMethodName(expr.builtin);
  5837. if (name == null) {
  5838. // some builtins just mean to skip the call.
  5839. return null;
  5840. }
  5841. }
  5842. ctx.print(expr, "." + name + "(");
  5843. this.visitAllExpressions(expr.args, ctx, ",");
  5844. ctx.print(expr, ")");
  5845. return null;
  5846. };
  5847. AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  5848. expr.fn.visitExpression(this, ctx);
  5849. ctx.print(expr, "(");
  5850. this.visitAllExpressions(expr.args, ctx, ',');
  5851. ctx.print(expr, ")");
  5852. return null;
  5853. };
  5854. AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  5855. throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
  5856. };
  5857. AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) {
  5858. ctx.print(expr, 'typeof ');
  5859. expr.expr.visitExpression(this, ctx);
  5860. };
  5861. AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  5862. var varName = ast.name;
  5863. if (ast.builtin != null) {
  5864. switch (ast.builtin) {
  5865. case BuiltinVar.Super:
  5866. varName = 'super';
  5867. break;
  5868. case BuiltinVar.This:
  5869. varName = 'this';
  5870. break;
  5871. case BuiltinVar.CatchError:
  5872. varName = CATCH_ERROR_VAR$1.name;
  5873. break;
  5874. case BuiltinVar.CatchStack:
  5875. varName = CATCH_STACK_VAR$1.name;
  5876. break;
  5877. default:
  5878. throw new Error("Unknown builtin variable " + ast.builtin);
  5879. }
  5880. }
  5881. ctx.print(ast, varName);
  5882. return null;
  5883. };
  5884. AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  5885. ctx.print(ast, "new ");
  5886. ast.classExpr.visitExpression(this, ctx);
  5887. ctx.print(ast, "(");
  5888. this.visitAllExpressions(ast.args, ctx, ',');
  5889. ctx.print(ast, ")");
  5890. return null;
  5891. };
  5892. AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  5893. var value = ast.value;
  5894. if (typeof value === 'string') {
  5895. ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
  5896. }
  5897. else {
  5898. ctx.print(ast, "" + value);
  5899. }
  5900. return null;
  5901. };
  5902. AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
  5903. ctx.print(ast, "(");
  5904. ast.condition.visitExpression(this, ctx);
  5905. ctx.print(ast, '? ');
  5906. ast.trueCase.visitExpression(this, ctx);
  5907. ctx.print(ast, ': ');
  5908. ast.falseCase.visitExpression(this, ctx);
  5909. ctx.print(ast, ")");
  5910. return null;
  5911. };
  5912. AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
  5913. ctx.print(ast, '!');
  5914. ast.condition.visitExpression(this, ctx);
  5915. return null;
  5916. };
  5917. AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  5918. ast.condition.visitExpression(this, ctx);
  5919. return null;
  5920. };
  5921. AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  5922. var opStr;
  5923. switch (ast.operator) {
  5924. case BinaryOperator.Equals:
  5925. opStr = '==';
  5926. break;
  5927. case BinaryOperator.Identical:
  5928. opStr = '===';
  5929. break;
  5930. case BinaryOperator.NotEquals:
  5931. opStr = '!=';
  5932. break;
  5933. case BinaryOperator.NotIdentical:
  5934. opStr = '!==';
  5935. break;
  5936. case BinaryOperator.And:
  5937. opStr = '&&';
  5938. break;
  5939. case BinaryOperator.BitwiseAnd:
  5940. opStr = '&';
  5941. break;
  5942. case BinaryOperator.Or:
  5943. opStr = '||';
  5944. break;
  5945. case BinaryOperator.Plus:
  5946. opStr = '+';
  5947. break;
  5948. case BinaryOperator.Minus:
  5949. opStr = '-';
  5950. break;
  5951. case BinaryOperator.Divide:
  5952. opStr = '/';
  5953. break;
  5954. case BinaryOperator.Multiply:
  5955. opStr = '*';
  5956. break;
  5957. case BinaryOperator.Modulo:
  5958. opStr = '%';
  5959. break;
  5960. case BinaryOperator.Lower:
  5961. opStr = '<';
  5962. break;
  5963. case BinaryOperator.LowerEquals:
  5964. opStr = '<=';
  5965. break;
  5966. case BinaryOperator.Bigger:
  5967. opStr = '>';
  5968. break;
  5969. case BinaryOperator.BiggerEquals:
  5970. opStr = '>=';
  5971. break;
  5972. default:
  5973. throw new Error("Unknown operator " + ast.operator);
  5974. }
  5975. if (ast.parens)
  5976. ctx.print(ast, "(");
  5977. ast.lhs.visitExpression(this, ctx);
  5978. ctx.print(ast, " " + opStr + " ");
  5979. ast.rhs.visitExpression(this, ctx);
  5980. if (ast.parens)
  5981. ctx.print(ast, ")");
  5982. return null;
  5983. };
  5984. AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
  5985. ast.receiver.visitExpression(this, ctx);
  5986. ctx.print(ast, ".");
  5987. ctx.print(ast, ast.name);
  5988. return null;
  5989. };
  5990. AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
  5991. ast.receiver.visitExpression(this, ctx);
  5992. ctx.print(ast, "[");
  5993. ast.index.visitExpression(this, ctx);
  5994. ctx.print(ast, "]");
  5995. return null;
  5996. };
  5997. AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  5998. ctx.print(ast, "[");
  5999. this.visitAllExpressions(ast.entries, ctx, ',');
  6000. ctx.print(ast, "]");
  6001. return null;
  6002. };
  6003. AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
  6004. var _this = this;
  6005. ctx.print(ast, "{");
  6006. this.visitAllObjects(function (entry) {
  6007. ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":");
  6008. entry.value.visitExpression(_this, ctx);
  6009. }, ast.entries, ctx, ',');
  6010. ctx.print(ast, "}");
  6011. return null;
  6012. };
  6013. AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
  6014. ctx.print(ast, '(');
  6015. this.visitAllExpressions(ast.parts, ctx, ',');
  6016. ctx.print(ast, ')');
  6017. return null;
  6018. };
  6019. AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) {
  6020. var _this = this;
  6021. this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator);
  6022. };
  6023. AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) {
  6024. var incrementedIndent = false;
  6025. for (var i = 0; i < expressions.length; i++) {
  6026. if (i > 0) {
  6027. if (ctx.lineLength() > 80) {
  6028. ctx.print(null, separator, true);
  6029. if (!incrementedIndent) {
  6030. // continuation are marked with double indent.
  6031. ctx.incIndent();
  6032. ctx.incIndent();
  6033. incrementedIndent = true;
  6034. }
  6035. }
  6036. else {
  6037. ctx.print(null, separator, false);
  6038. }
  6039. }
  6040. handler(expressions[i]);
  6041. }
  6042. if (incrementedIndent) {
  6043. // continuation are marked with double indent.
  6044. ctx.decIndent();
  6045. ctx.decIndent();
  6046. }
  6047. };
  6048. AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
  6049. var _this = this;
  6050. statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
  6051. };
  6052. return AbstractEmitterVisitor;
  6053. }());
  6054. function escapeIdentifier(input, escapeDollar, alwaysQuote) {
  6055. if (alwaysQuote === void 0) { alwaysQuote = true; }
  6056. if (input == null) {
  6057. return null;
  6058. }
  6059. var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
  6060. var match = [];
  6061. for (var _i = 0; _i < arguments.length; _i++) {
  6062. match[_i] = arguments[_i];
  6063. }
  6064. if (match[0] == '$') {
  6065. return escapeDollar ? '\\$' : '$';
  6066. }
  6067. else if (match[0] == '\n') {
  6068. return '\\n';
  6069. }
  6070. else if (match[0] == '\r') {
  6071. return '\\r';
  6072. }
  6073. else {
  6074. return "\\" + match[0];
  6075. }
  6076. });
  6077. var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
  6078. return requiresQuotes ? "'" + body + "'" : body;
  6079. }
  6080. function _createIndent(count) {
  6081. var res = '';
  6082. for (var i = 0; i < count; i++) {
  6083. res += _INDENT_WITH;
  6084. }
  6085. return res;
  6086. }
  6087. /**
  6088. * @license
  6089. * Copyright Google Inc. All Rights Reserved.
  6090. *
  6091. * Use of this source code is governed by an MIT-style license that can be
  6092. * found in the LICENSE file at https://angular.io/license
  6093. */
  6094. var AbstractJsEmitterVisitor = /** @class */ (function (_super) {
  6095. __extends(AbstractJsEmitterVisitor, _super);
  6096. function AbstractJsEmitterVisitor() {
  6097. return _super.call(this, false) || this;
  6098. }
  6099. AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  6100. var _this = this;
  6101. ctx.pushClass(stmt);
  6102. this._visitClassConstructor(stmt, ctx);
  6103. if (stmt.parent != null) {
  6104. ctx.print(stmt, stmt.name + ".prototype = Object.create(");
  6105. stmt.parent.visitExpression(this, ctx);
  6106. ctx.println(stmt, ".prototype);");
  6107. }
  6108. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); });
  6109. stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); });
  6110. ctx.popClass();
  6111. return null;
  6112. };
  6113. AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  6114. ctx.print(stmt, "function " + stmt.name + "(");
  6115. if (stmt.constructorMethod != null) {
  6116. this._visitParams(stmt.constructorMethod.params, ctx);
  6117. }
  6118. ctx.println(stmt, ") {");
  6119. ctx.incIndent();
  6120. if (stmt.constructorMethod != null) {
  6121. if (stmt.constructorMethod.body.length > 0) {
  6122. ctx.println(stmt, "var self = this;");
  6123. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  6124. }
  6125. }
  6126. ctx.decIndent();
  6127. ctx.println(stmt, "}");
  6128. };
  6129. AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) {
  6130. ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {");
  6131. ctx.incIndent();
  6132. if (getter.body.length > 0) {
  6133. ctx.println(stmt, "var self = this;");
  6134. this.visitAllStatements(getter.body, ctx);
  6135. }
  6136. ctx.decIndent();
  6137. ctx.println(stmt, "}});");
  6138. };
  6139. AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) {
  6140. ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function(");
  6141. this._visitParams(method.params, ctx);
  6142. ctx.println(stmt, ") {");
  6143. ctx.incIndent();
  6144. if (method.body.length > 0) {
  6145. ctx.println(stmt, "var self = this;");
  6146. this.visitAllStatements(method.body, ctx);
  6147. }
  6148. ctx.decIndent();
  6149. ctx.println(stmt, "};");
  6150. };
  6151. AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6152. throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
  6153. };
  6154. AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  6155. if (ast.builtin === BuiltinVar.This) {
  6156. ctx.print(ast, 'self');
  6157. }
  6158. else if (ast.builtin === BuiltinVar.Super) {
  6159. throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!");
  6160. }
  6161. else {
  6162. _super.prototype.visitReadVarExpr.call(this, ast, ctx);
  6163. }
  6164. return null;
  6165. };
  6166. AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  6167. ctx.print(stmt, "var " + stmt.name);
  6168. if (stmt.value) {
  6169. ctx.print(stmt, ' = ');
  6170. stmt.value.visitExpression(this, ctx);
  6171. }
  6172. ctx.println(stmt, ";");
  6173. return null;
  6174. };
  6175. AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  6176. ast.value.visitExpression(this, ctx);
  6177. return null;
  6178. };
  6179. AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  6180. var fnExpr = expr.fn;
  6181. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
  6182. ctx.currentClass.parent.visitExpression(this, ctx);
  6183. ctx.print(expr, ".call(this");
  6184. if (expr.args.length > 0) {
  6185. ctx.print(expr, ", ");
  6186. this.visitAllExpressions(expr.args, ctx, ',');
  6187. }
  6188. ctx.print(expr, ")");
  6189. }
  6190. else {
  6191. _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx);
  6192. }
  6193. return null;
  6194. };
  6195. AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  6196. ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "(");
  6197. this._visitParams(ast.params, ctx);
  6198. ctx.println(ast, ") {");
  6199. ctx.incIndent();
  6200. this.visitAllStatements(ast.statements, ctx);
  6201. ctx.decIndent();
  6202. ctx.print(ast, "}");
  6203. return null;
  6204. };
  6205. AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  6206. ctx.print(stmt, "function " + stmt.name + "(");
  6207. this._visitParams(stmt.params, ctx);
  6208. ctx.println(stmt, ") {");
  6209. ctx.incIndent();
  6210. this.visitAllStatements(stmt.statements, ctx);
  6211. ctx.decIndent();
  6212. ctx.println(stmt, "}");
  6213. return null;
  6214. };
  6215. AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  6216. ctx.println(stmt, "try {");
  6217. ctx.incIndent();
  6218. this.visitAllStatements(stmt.bodyStmts, ctx);
  6219. ctx.decIndent();
  6220. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  6221. ctx.incIndent();
  6222. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
  6223. StmtModifier.Final
  6224. ])].concat(stmt.catchStmts);
  6225. this.visitAllStatements(catchStmts, ctx);
  6226. ctx.decIndent();
  6227. ctx.println(stmt, "}");
  6228. return null;
  6229. };
  6230. AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  6231. this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ',');
  6232. };
  6233. AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  6234. var name;
  6235. switch (method) {
  6236. case BuiltinMethod.ConcatArray:
  6237. name = 'concat';
  6238. break;
  6239. case BuiltinMethod.SubscribeObservable:
  6240. name = 'subscribe';
  6241. break;
  6242. case BuiltinMethod.Bind:
  6243. name = 'bind';
  6244. break;
  6245. default:
  6246. throw new Error("Unknown builtin method: " + method);
  6247. }
  6248. return name;
  6249. };
  6250. return AbstractJsEmitterVisitor;
  6251. }(AbstractEmitterVisitor));
  6252. /**
  6253. * @license
  6254. * Copyright Google Inc. All Rights Reserved.
  6255. *
  6256. * Use of this source code is governed by an MIT-style license that can be
  6257. * found in the LICENSE file at https://angular.io/license
  6258. */
  6259. /**
  6260. * A helper class to manage the evaluation of JIT generated code.
  6261. */
  6262. var JitEvaluator = /** @class */ (function () {
  6263. function JitEvaluator() {
  6264. }
  6265. /**
  6266. *
  6267. * @param sourceUrl The URL of the generated code.
  6268. * @param statements An array of Angular statement AST nodes to be evaluated.
  6269. * @param reflector A helper used when converting the statements to executable code.
  6270. * @param createSourceMaps If true then create a source-map for the generated code and include it
  6271. * inline as a source-map comment.
  6272. * @returns A map of all the variables in the generated code.
  6273. */
  6274. JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) {
  6275. var converter = new JitEmitterVisitor(reflector);
  6276. var ctx = EmitterVisitorContext.createRoot();
  6277. // Ensure generated code is in strict mode
  6278. if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
  6279. statements = __spread([
  6280. literal('use strict').toStmt()
  6281. ], statements);
  6282. }
  6283. converter.visitAllStatements(statements, ctx);
  6284. converter.createReturnStmt(ctx);
  6285. return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
  6286. };
  6287. /**
  6288. * Evaluate a piece of JIT generated code.
  6289. * @param sourceUrl The URL of this generated code.
  6290. * @param ctx A context object that contains an AST of the code to be evaluated.
  6291. * @param vars A map containing the names and values of variables that the evaluated code might
  6292. * reference.
  6293. * @param createSourceMap If true then create a source-map for the generated code and include it
  6294. * inline as a source-map comment.
  6295. * @returns The result of evaluating the code.
  6296. */
  6297. JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) {
  6298. var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl;
  6299. var fnArgNames = [];
  6300. var fnArgValues = [];
  6301. for (var argName in vars) {
  6302. fnArgValues.push(vars[argName]);
  6303. fnArgNames.push(argName);
  6304. }
  6305. if (createSourceMap) {
  6306. // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
  6307. // E.g. ```
  6308. // function anonymous(a,b,c
  6309. // /**/) { ... }```
  6310. // We don't want to hard code this fact, so we auto detect it via an empty function first.
  6311. var emptyFn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat('return null;'))))().toString();
  6312. var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
  6313. fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment();
  6314. }
  6315. var fn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat(fnBody))))();
  6316. return this.executeFunction(fn, fnArgValues);
  6317. };
  6318. /**
  6319. * Execute a JIT generated function by calling it.
  6320. *
  6321. * This method can be overridden in tests to capture the functions that are generated
  6322. * by this `JitEvaluator` class.
  6323. *
  6324. * @param fn A function to execute.
  6325. * @param args The arguments to pass to the function being executed.
  6326. * @returns The return value of the executed function.
  6327. */
  6328. JitEvaluator.prototype.executeFunction = function (fn, args) { return fn.apply(void 0, __spread(args)); };
  6329. return JitEvaluator;
  6330. }());
  6331. /**
  6332. * An Angular AST visitor that converts AST nodes into executable JavaScript code.
  6333. */
  6334. var JitEmitterVisitor = /** @class */ (function (_super) {
  6335. __extends(JitEmitterVisitor, _super);
  6336. function JitEmitterVisitor(reflector) {
  6337. var _this = _super.call(this) || this;
  6338. _this.reflector = reflector;
  6339. _this._evalArgNames = [];
  6340. _this._evalArgValues = [];
  6341. _this._evalExportedVars = [];
  6342. return _this;
  6343. }
  6344. JitEmitterVisitor.prototype.createReturnStmt = function (ctx) {
  6345. var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); })));
  6346. stmt.visitStatement(this, ctx);
  6347. };
  6348. JitEmitterVisitor.prototype.getArgs = function () {
  6349. var result = {};
  6350. for (var i = 0; i < this._evalArgNames.length; i++) {
  6351. result[this._evalArgNames[i]] = this._evalArgValues[i];
  6352. }
  6353. return result;
  6354. };
  6355. JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  6356. this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
  6357. return null;
  6358. };
  6359. JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6360. this._emitReferenceToExternal(ast, ast.node, ctx);
  6361. return null;
  6362. };
  6363. JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  6364. if (stmt.hasModifier(StmtModifier.Exported)) {
  6365. this._evalExportedVars.push(stmt.name);
  6366. }
  6367. return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx);
  6368. };
  6369. JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  6370. if (stmt.hasModifier(StmtModifier.Exported)) {
  6371. this._evalExportedVars.push(stmt.name);
  6372. }
  6373. return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx);
  6374. };
  6375. JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  6376. if (stmt.hasModifier(StmtModifier.Exported)) {
  6377. this._evalExportedVars.push(stmt.name);
  6378. }
  6379. return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx);
  6380. };
  6381. JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) {
  6382. var id = this._evalArgValues.indexOf(value);
  6383. if (id === -1) {
  6384. id = this._evalArgValues.length;
  6385. this._evalArgValues.push(value);
  6386. var name_1 = identifierName({ reference: value }) || 'val';
  6387. this._evalArgNames.push("jit_" + name_1 + "_" + id);
  6388. }
  6389. ctx.print(ast, this._evalArgNames[id]);
  6390. };
  6391. return JitEmitterVisitor;
  6392. }(AbstractJsEmitterVisitor));
  6393. function isUseStrictStatement(statement) {
  6394. return statement.isEquivalent(literal('use strict').toStmt());
  6395. }
  6396. /**
  6397. * @license
  6398. * Copyright Google Inc. All Rights Reserved.
  6399. *
  6400. * Use of this source code is governed by an MIT-style license that can be
  6401. * found in the LICENSE file at https://angular.io/license
  6402. */
  6403. /**
  6404. * Implementation of `CompileReflector` which resolves references to @angular/core
  6405. * symbols at runtime, according to a consumer-provided mapping.
  6406. *
  6407. * Only supports `resolveExternalReference`, all other methods throw.
  6408. */
  6409. var R3JitReflector = /** @class */ (function () {
  6410. function R3JitReflector(context) {
  6411. this.context = context;
  6412. }
  6413. R3JitReflector.prototype.resolveExternalReference = function (ref) {
  6414. // This reflector only handles @angular/core imports.
  6415. if (ref.moduleName !== '@angular/core') {
  6416. throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported.");
  6417. }
  6418. if (!this.context.hasOwnProperty(ref.name)) {
  6419. throw new Error("No value provided for @angular/core symbol '" + ref.name + "'.");
  6420. }
  6421. return this.context[ref.name];
  6422. };
  6423. R3JitReflector.prototype.parameters = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6424. R3JitReflector.prototype.annotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6425. R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6426. R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6427. R3JitReflector.prototype.propMetadata = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6428. R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) { throw new Error('Not implemented.'); };
  6429. R3JitReflector.prototype.guards = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6430. R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) { throw new Error('Not implemented.'); };
  6431. return R3JitReflector;
  6432. }());
  6433. /**
  6434. * @license
  6435. * Copyright Google Inc. All Rights Reserved.
  6436. *
  6437. * Use of this source code is governed by an MIT-style license that can be
  6438. * found in the LICENSE file at https://angular.io/license
  6439. */
  6440. /**
  6441. * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
  6442. */
  6443. function compileNgModule(meta) {
  6444. var moduleType = meta.type, bootstrap = meta.bootstrap, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, schemas = meta.schemas, containsForwardDecls = meta.containsForwardDecls, emitInline = meta.emitInline, id = meta.id;
  6445. var additionalStatements = [];
  6446. var definitionMap = {
  6447. type: moduleType
  6448. };
  6449. // Only generate the keys in the metadata if the arrays have values.
  6450. if (bootstrap.length) {
  6451. definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
  6452. }
  6453. // If requested to emit scope information inline, pass the declarations, imports and exports to
  6454. // the `ɵɵdefineNgModule` call. The JIT compilation uses this.
  6455. if (emitInline) {
  6456. if (declarations.length) {
  6457. definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
  6458. }
  6459. if (imports.length) {
  6460. definitionMap.imports = refsToArray(imports, containsForwardDecls);
  6461. }
  6462. if (exports.length) {
  6463. definitionMap.exports = refsToArray(exports, containsForwardDecls);
  6464. }
  6465. }
  6466. // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
  6467. // prevent tree-shaking of the declarations, imports and exports references.
  6468. else {
  6469. var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
  6470. if (setNgModuleScopeCall !== null) {
  6471. additionalStatements.push(setNgModuleScopeCall);
  6472. }
  6473. }
  6474. if (schemas && schemas.length) {
  6475. definitionMap.schemas = literalArr(schemas.map(function (ref) { return ref.value; }));
  6476. }
  6477. if (id) {
  6478. definitionMap.id = id;
  6479. }
  6480. var expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
  6481. var type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [
  6482. new ExpressionType(moduleType), tupleTypeOf(declarations), tupleTypeOf(imports),
  6483. tupleTypeOf(exports)
  6484. ]));
  6485. return { expression: expression, type: type, additionalStatements: additionalStatements };
  6486. }
  6487. /**
  6488. * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
  6489. * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
  6490. * such that the references to declarations, imports and exports may be elided causing these
  6491. * symbols to become tree-shakeable.
  6492. */
  6493. function generateSetNgModuleScopeCall(meta) {
  6494. var moduleType = meta.type, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls;
  6495. var scopeMap = {};
  6496. if (declarations.length) {
  6497. scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
  6498. }
  6499. if (imports.length) {
  6500. scopeMap.imports = refsToArray(imports, containsForwardDecls);
  6501. }
  6502. if (exports.length) {
  6503. scopeMap.exports = refsToArray(exports, containsForwardDecls);
  6504. }
  6505. if (Object.keys(scopeMap).length === 0) {
  6506. return null;
  6507. }
  6508. var fnCall = new InvokeFunctionExpr(
  6509. /* fn */ importExpr(Identifiers$1.setNgModuleScope),
  6510. /* args */ [moduleType, mapToMapExpression(scopeMap)],
  6511. /* type */ undefined,
  6512. /* sourceSpan */ undefined,
  6513. /* pure */ true);
  6514. return fnCall.toStmt();
  6515. }
  6516. function compileInjector(meta) {
  6517. var result = compileFactoryFunction({
  6518. name: meta.name,
  6519. type: meta.type,
  6520. deps: meta.deps,
  6521. injectFn: Identifiers$1.inject,
  6522. });
  6523. var definitionMap = {
  6524. factory: result.factory,
  6525. };
  6526. if (meta.providers !== null) {
  6527. definitionMap.providers = meta.providers;
  6528. }
  6529. if (meta.imports.length > 0) {
  6530. definitionMap.imports = literalArr(meta.imports);
  6531. }
  6532. var expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]);
  6533. var type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type)]));
  6534. return { expression: expression, type: type, statements: result.statements };
  6535. }
  6536. function tupleTypeOf(exp) {
  6537. var types = exp.map(function (ref) { return typeofExpr(ref.type); });
  6538. return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
  6539. }
  6540. function refsToArray(refs, shouldForwardDeclare) {
  6541. var values = literalArr(refs.map(function (ref) { return ref.value; }));
  6542. return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
  6543. }
  6544. /**
  6545. * @license
  6546. * Copyright Google Inc. All Rights Reserved.
  6547. *
  6548. * Use of this source code is governed by an MIT-style license that can be
  6549. * found in the LICENSE file at https://angular.io/license
  6550. */
  6551. function compilePipeFromMetadata(metadata) {
  6552. var definitionMapValues = [];
  6553. // e.g. `name: 'myPipe'`
  6554. definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
  6555. // e.g. `type: MyPipe`
  6556. definitionMapValues.push({ key: 'type', value: metadata.type, quoted: false });
  6557. var templateFactory = compileFactoryFunction({
  6558. name: metadata.name,
  6559. type: metadata.type,
  6560. deps: metadata.deps,
  6561. injectFn: Identifiers$1.directiveInject,
  6562. });
  6563. definitionMapValues.push({ key: 'factory', value: templateFactory.factory, quoted: false });
  6564. // e.g. `pure: true`
  6565. definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
  6566. var expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]);
  6567. var type = new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [
  6568. typeWithParameters(metadata.type, metadata.typeArgumentCount),
  6569. new ExpressionType(new LiteralExpr(metadata.pipeName)),
  6570. ]));
  6571. return { expression: expression, type: type, statements: templateFactory.statements };
  6572. }
  6573. /**
  6574. * @license
  6575. * Copyright Google Inc. All Rights Reserved.
  6576. *
  6577. * Use of this source code is governed by an MIT-style license that can be
  6578. * found in the LICENSE file at https://angular.io/license
  6579. */
  6580. var ParserError = /** @class */ (function () {
  6581. function ParserError(message, input, errLocation, ctxLocation) {
  6582. this.input = input;
  6583. this.errLocation = errLocation;
  6584. this.ctxLocation = ctxLocation;
  6585. this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation;
  6586. }
  6587. return ParserError;
  6588. }());
  6589. var ParseSpan = /** @class */ (function () {
  6590. function ParseSpan(start, end) {
  6591. this.start = start;
  6592. this.end = end;
  6593. }
  6594. return ParseSpan;
  6595. }());
  6596. var AST = /** @class */ (function () {
  6597. function AST(span) {
  6598. this.span = span;
  6599. }
  6600. AST.prototype.visit = function (visitor, context) {
  6601. if (context === void 0) { context = null; }
  6602. return null;
  6603. };
  6604. AST.prototype.toString = function () { return 'AST'; };
  6605. return AST;
  6606. }());
  6607. /**
  6608. * Represents a quoted expression of the form:
  6609. *
  6610. * quote = prefix `:` uninterpretedExpression
  6611. * prefix = identifier
  6612. * uninterpretedExpression = arbitrary string
  6613. *
  6614. * A quoted expression is meant to be pre-processed by an AST transformer that
  6615. * converts it into another AST that no longer contains quoted expressions.
  6616. * It is meant to allow third-party developers to extend Angular template
  6617. * expression language. The `uninterpretedExpression` part of the quote is
  6618. * therefore not interpreted by the Angular's own expression parser.
  6619. */
  6620. var Quote = /** @class */ (function (_super) {
  6621. __extends(Quote, _super);
  6622. function Quote(span, prefix, uninterpretedExpression, location) {
  6623. var _this = _super.call(this, span) || this;
  6624. _this.prefix = prefix;
  6625. _this.uninterpretedExpression = uninterpretedExpression;
  6626. _this.location = location;
  6627. return _this;
  6628. }
  6629. Quote.prototype.visit = function (visitor, context) {
  6630. if (context === void 0) { context = null; }
  6631. return visitor.visitQuote(this, context);
  6632. };
  6633. Quote.prototype.toString = function () { return 'Quote'; };
  6634. return Quote;
  6635. }(AST));
  6636. var EmptyExpr = /** @class */ (function (_super) {
  6637. __extends(EmptyExpr, _super);
  6638. function EmptyExpr() {
  6639. return _super !== null && _super.apply(this, arguments) || this;
  6640. }
  6641. EmptyExpr.prototype.visit = function (visitor, context) {
  6642. if (context === void 0) { context = null; }
  6643. // do nothing
  6644. };
  6645. return EmptyExpr;
  6646. }(AST));
  6647. var ImplicitReceiver = /** @class */ (function (_super) {
  6648. __extends(ImplicitReceiver, _super);
  6649. function ImplicitReceiver() {
  6650. return _super !== null && _super.apply(this, arguments) || this;
  6651. }
  6652. ImplicitReceiver.prototype.visit = function (visitor, context) {
  6653. if (context === void 0) { context = null; }
  6654. return visitor.visitImplicitReceiver(this, context);
  6655. };
  6656. return ImplicitReceiver;
  6657. }(AST));
  6658. /**
  6659. * Multiple expressions separated by a semicolon.
  6660. */
  6661. var Chain = /** @class */ (function (_super) {
  6662. __extends(Chain, _super);
  6663. function Chain(span, expressions) {
  6664. var _this = _super.call(this, span) || this;
  6665. _this.expressions = expressions;
  6666. return _this;
  6667. }
  6668. Chain.prototype.visit = function (visitor, context) {
  6669. if (context === void 0) { context = null; }
  6670. return visitor.visitChain(this, context);
  6671. };
  6672. return Chain;
  6673. }(AST));
  6674. var Conditional = /** @class */ (function (_super) {
  6675. __extends(Conditional, _super);
  6676. function Conditional(span, condition, trueExp, falseExp) {
  6677. var _this = _super.call(this, span) || this;
  6678. _this.condition = condition;
  6679. _this.trueExp = trueExp;
  6680. _this.falseExp = falseExp;
  6681. return _this;
  6682. }
  6683. Conditional.prototype.visit = function (visitor, context) {
  6684. if (context === void 0) { context = null; }
  6685. return visitor.visitConditional(this, context);
  6686. };
  6687. return Conditional;
  6688. }(AST));
  6689. var PropertyRead = /** @class */ (function (_super) {
  6690. __extends(PropertyRead, _super);
  6691. function PropertyRead(span, receiver, name) {
  6692. var _this = _super.call(this, span) || this;
  6693. _this.receiver = receiver;
  6694. _this.name = name;
  6695. return _this;
  6696. }
  6697. PropertyRead.prototype.visit = function (visitor, context) {
  6698. if (context === void 0) { context = null; }
  6699. return visitor.visitPropertyRead(this, context);
  6700. };
  6701. return PropertyRead;
  6702. }(AST));
  6703. var PropertyWrite = /** @class */ (function (_super) {
  6704. __extends(PropertyWrite, _super);
  6705. function PropertyWrite(span, receiver, name, value) {
  6706. var _this = _super.call(this, span) || this;
  6707. _this.receiver = receiver;
  6708. _this.name = name;
  6709. _this.value = value;
  6710. return _this;
  6711. }
  6712. PropertyWrite.prototype.visit = function (visitor, context) {
  6713. if (context === void 0) { context = null; }
  6714. return visitor.visitPropertyWrite(this, context);
  6715. };
  6716. return PropertyWrite;
  6717. }(AST));
  6718. var SafePropertyRead = /** @class */ (function (_super) {
  6719. __extends(SafePropertyRead, _super);
  6720. function SafePropertyRead(span, receiver, name) {
  6721. var _this = _super.call(this, span) || this;
  6722. _this.receiver = receiver;
  6723. _this.name = name;
  6724. return _this;
  6725. }
  6726. SafePropertyRead.prototype.visit = function (visitor, context) {
  6727. if (context === void 0) { context = null; }
  6728. return visitor.visitSafePropertyRead(this, context);
  6729. };
  6730. return SafePropertyRead;
  6731. }(AST));
  6732. var KeyedRead = /** @class */ (function (_super) {
  6733. __extends(KeyedRead, _super);
  6734. function KeyedRead(span, obj, key) {
  6735. var _this = _super.call(this, span) || this;
  6736. _this.obj = obj;
  6737. _this.key = key;
  6738. return _this;
  6739. }
  6740. KeyedRead.prototype.visit = function (visitor, context) {
  6741. if (context === void 0) { context = null; }
  6742. return visitor.visitKeyedRead(this, context);
  6743. };
  6744. return KeyedRead;
  6745. }(AST));
  6746. var KeyedWrite = /** @class */ (function (_super) {
  6747. __extends(KeyedWrite, _super);
  6748. function KeyedWrite(span, obj, key, value) {
  6749. var _this = _super.call(this, span) || this;
  6750. _this.obj = obj;
  6751. _this.key = key;
  6752. _this.value = value;
  6753. return _this;
  6754. }
  6755. KeyedWrite.prototype.visit = function (visitor, context) {
  6756. if (context === void 0) { context = null; }
  6757. return visitor.visitKeyedWrite(this, context);
  6758. };
  6759. return KeyedWrite;
  6760. }(AST));
  6761. var BindingPipe = /** @class */ (function (_super) {
  6762. __extends(BindingPipe, _super);
  6763. function BindingPipe(span, exp, name, args) {
  6764. var _this = _super.call(this, span) || this;
  6765. _this.exp = exp;
  6766. _this.name = name;
  6767. _this.args = args;
  6768. return _this;
  6769. }
  6770. BindingPipe.prototype.visit = function (visitor, context) {
  6771. if (context === void 0) { context = null; }
  6772. return visitor.visitPipe(this, context);
  6773. };
  6774. return BindingPipe;
  6775. }(AST));
  6776. var LiteralPrimitive = /** @class */ (function (_super) {
  6777. __extends(LiteralPrimitive, _super);
  6778. function LiteralPrimitive(span, value) {
  6779. var _this = _super.call(this, span) || this;
  6780. _this.value = value;
  6781. return _this;
  6782. }
  6783. LiteralPrimitive.prototype.visit = function (visitor, context) {
  6784. if (context === void 0) { context = null; }
  6785. return visitor.visitLiteralPrimitive(this, context);
  6786. };
  6787. return LiteralPrimitive;
  6788. }(AST));
  6789. var LiteralArray = /** @class */ (function (_super) {
  6790. __extends(LiteralArray, _super);
  6791. function LiteralArray(span, expressions) {
  6792. var _this = _super.call(this, span) || this;
  6793. _this.expressions = expressions;
  6794. return _this;
  6795. }
  6796. LiteralArray.prototype.visit = function (visitor, context) {
  6797. if (context === void 0) { context = null; }
  6798. return visitor.visitLiteralArray(this, context);
  6799. };
  6800. return LiteralArray;
  6801. }(AST));
  6802. var LiteralMap = /** @class */ (function (_super) {
  6803. __extends(LiteralMap, _super);
  6804. function LiteralMap(span, keys, values) {
  6805. var _this = _super.call(this, span) || this;
  6806. _this.keys = keys;
  6807. _this.values = values;
  6808. return _this;
  6809. }
  6810. LiteralMap.prototype.visit = function (visitor, context) {
  6811. if (context === void 0) { context = null; }
  6812. return visitor.visitLiteralMap(this, context);
  6813. };
  6814. return LiteralMap;
  6815. }(AST));
  6816. var Interpolation = /** @class */ (function (_super) {
  6817. __extends(Interpolation, _super);
  6818. function Interpolation(span, strings, expressions) {
  6819. var _this = _super.call(this, span) || this;
  6820. _this.strings = strings;
  6821. _this.expressions = expressions;
  6822. return _this;
  6823. }
  6824. Interpolation.prototype.visit = function (visitor, context) {
  6825. if (context === void 0) { context = null; }
  6826. return visitor.visitInterpolation(this, context);
  6827. };
  6828. return Interpolation;
  6829. }(AST));
  6830. var Binary = /** @class */ (function (_super) {
  6831. __extends(Binary, _super);
  6832. function Binary(span, operation, left, right) {
  6833. var _this = _super.call(this, span) || this;
  6834. _this.operation = operation;
  6835. _this.left = left;
  6836. _this.right = right;
  6837. return _this;
  6838. }
  6839. Binary.prototype.visit = function (visitor, context) {
  6840. if (context === void 0) { context = null; }
  6841. return visitor.visitBinary(this, context);
  6842. };
  6843. return Binary;
  6844. }(AST));
  6845. var PrefixNot = /** @class */ (function (_super) {
  6846. __extends(PrefixNot, _super);
  6847. function PrefixNot(span, expression) {
  6848. var _this = _super.call(this, span) || this;
  6849. _this.expression = expression;
  6850. return _this;
  6851. }
  6852. PrefixNot.prototype.visit = function (visitor, context) {
  6853. if (context === void 0) { context = null; }
  6854. return visitor.visitPrefixNot(this, context);
  6855. };
  6856. return PrefixNot;
  6857. }(AST));
  6858. var NonNullAssert = /** @class */ (function (_super) {
  6859. __extends(NonNullAssert, _super);
  6860. function NonNullAssert(span, expression) {
  6861. var _this = _super.call(this, span) || this;
  6862. _this.expression = expression;
  6863. return _this;
  6864. }
  6865. NonNullAssert.prototype.visit = function (visitor, context) {
  6866. if (context === void 0) { context = null; }
  6867. return visitor.visitNonNullAssert(this, context);
  6868. };
  6869. return NonNullAssert;
  6870. }(AST));
  6871. var MethodCall = /** @class */ (function (_super) {
  6872. __extends(MethodCall, _super);
  6873. function MethodCall(span, receiver, name, args) {
  6874. var _this = _super.call(this, span) || this;
  6875. _this.receiver = receiver;
  6876. _this.name = name;
  6877. _this.args = args;
  6878. return _this;
  6879. }
  6880. MethodCall.prototype.visit = function (visitor, context) {
  6881. if (context === void 0) { context = null; }
  6882. return visitor.visitMethodCall(this, context);
  6883. };
  6884. return MethodCall;
  6885. }(AST));
  6886. var SafeMethodCall = /** @class */ (function (_super) {
  6887. __extends(SafeMethodCall, _super);
  6888. function SafeMethodCall(span, receiver, name, args) {
  6889. var _this = _super.call(this, span) || this;
  6890. _this.receiver = receiver;
  6891. _this.name = name;
  6892. _this.args = args;
  6893. return _this;
  6894. }
  6895. SafeMethodCall.prototype.visit = function (visitor, context) {
  6896. if (context === void 0) { context = null; }
  6897. return visitor.visitSafeMethodCall(this, context);
  6898. };
  6899. return SafeMethodCall;
  6900. }(AST));
  6901. var FunctionCall = /** @class */ (function (_super) {
  6902. __extends(FunctionCall, _super);
  6903. function FunctionCall(span, target, args) {
  6904. var _this = _super.call(this, span) || this;
  6905. _this.target = target;
  6906. _this.args = args;
  6907. return _this;
  6908. }
  6909. FunctionCall.prototype.visit = function (visitor, context) {
  6910. if (context === void 0) { context = null; }
  6911. return visitor.visitFunctionCall(this, context);
  6912. };
  6913. return FunctionCall;
  6914. }(AST));
  6915. var ASTWithSource = /** @class */ (function (_super) {
  6916. __extends(ASTWithSource, _super);
  6917. function ASTWithSource(ast, source, location, errors) {
  6918. var _this = _super.call(this, new ParseSpan(0, source == null ? 0 : source.length)) || this;
  6919. _this.ast = ast;
  6920. _this.source = source;
  6921. _this.location = location;
  6922. _this.errors = errors;
  6923. return _this;
  6924. }
  6925. ASTWithSource.prototype.visit = function (visitor, context) {
  6926. if (context === void 0) { context = null; }
  6927. return this.ast.visit(visitor, context);
  6928. };
  6929. ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; };
  6930. return ASTWithSource;
  6931. }(AST));
  6932. var TemplateBinding = /** @class */ (function () {
  6933. function TemplateBinding(span, key, keyIsVar, name, expression) {
  6934. this.span = span;
  6935. this.key = key;
  6936. this.keyIsVar = keyIsVar;
  6937. this.name = name;
  6938. this.expression = expression;
  6939. }
  6940. return TemplateBinding;
  6941. }());
  6942. var NullAstVisitor = /** @class */ (function () {
  6943. function NullAstVisitor() {
  6944. }
  6945. NullAstVisitor.prototype.visitBinary = function (ast, context) { };
  6946. NullAstVisitor.prototype.visitChain = function (ast, context) { };
  6947. NullAstVisitor.prototype.visitConditional = function (ast, context) { };
  6948. NullAstVisitor.prototype.visitFunctionCall = function (ast, context) { };
  6949. NullAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { };
  6950. NullAstVisitor.prototype.visitInterpolation = function (ast, context) { };
  6951. NullAstVisitor.prototype.visitKeyedRead = function (ast, context) { };
  6952. NullAstVisitor.prototype.visitKeyedWrite = function (ast, context) { };
  6953. NullAstVisitor.prototype.visitLiteralArray = function (ast, context) { };
  6954. NullAstVisitor.prototype.visitLiteralMap = function (ast, context) { };
  6955. NullAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { };
  6956. NullAstVisitor.prototype.visitMethodCall = function (ast, context) { };
  6957. NullAstVisitor.prototype.visitPipe = function (ast, context) { };
  6958. NullAstVisitor.prototype.visitPrefixNot = function (ast, context) { };
  6959. NullAstVisitor.prototype.visitNonNullAssert = function (ast, context) { };
  6960. NullAstVisitor.prototype.visitPropertyRead = function (ast, context) { };
  6961. NullAstVisitor.prototype.visitPropertyWrite = function (ast, context) { };
  6962. NullAstVisitor.prototype.visitQuote = function (ast, context) { };
  6963. NullAstVisitor.prototype.visitSafeMethodCall = function (ast, context) { };
  6964. NullAstVisitor.prototype.visitSafePropertyRead = function (ast, context) { };
  6965. return NullAstVisitor;
  6966. }());
  6967. var RecursiveAstVisitor$1 = /** @class */ (function () {
  6968. function RecursiveAstVisitor() {
  6969. }
  6970. RecursiveAstVisitor.prototype.visitBinary = function (ast, context) {
  6971. ast.left.visit(this, context);
  6972. ast.right.visit(this, context);
  6973. return null;
  6974. };
  6975. RecursiveAstVisitor.prototype.visitChain = function (ast, context) { return this.visitAll(ast.expressions, context); };
  6976. RecursiveAstVisitor.prototype.visitConditional = function (ast, context) {
  6977. ast.condition.visit(this, context);
  6978. ast.trueExp.visit(this, context);
  6979. ast.falseExp.visit(this, context);
  6980. return null;
  6981. };
  6982. RecursiveAstVisitor.prototype.visitPipe = function (ast, context) {
  6983. ast.exp.visit(this, context);
  6984. this.visitAll(ast.args, context);
  6985. return null;
  6986. };
  6987. RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) {
  6988. ast.target.visit(this, context);
  6989. this.visitAll(ast.args, context);
  6990. return null;
  6991. };
  6992. RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { return null; };
  6993. RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) {
  6994. return this.visitAll(ast.expressions, context);
  6995. };
  6996. RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) {
  6997. ast.obj.visit(this, context);
  6998. ast.key.visit(this, context);
  6999. return null;
  7000. };
  7001. RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) {
  7002. ast.obj.visit(this, context);
  7003. ast.key.visit(this, context);
  7004. ast.value.visit(this, context);
  7005. return null;
  7006. };
  7007. RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) {
  7008. return this.visitAll(ast.expressions, context);
  7009. };
  7010. RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { return this.visitAll(ast.values, context); };
  7011. RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { return null; };
  7012. RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) {
  7013. ast.receiver.visit(this, context);
  7014. return this.visitAll(ast.args, context);
  7015. };
  7016. RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) {
  7017. ast.expression.visit(this, context);
  7018. return null;
  7019. };
  7020. RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) {
  7021. ast.expression.visit(this, context);
  7022. return null;
  7023. };
  7024. RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) {
  7025. ast.receiver.visit(this, context);
  7026. return null;
  7027. };
  7028. RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) {
  7029. ast.receiver.visit(this, context);
  7030. ast.value.visit(this, context);
  7031. return null;
  7032. };
  7033. RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) {
  7034. ast.receiver.visit(this, context);
  7035. return null;
  7036. };
  7037. RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) {
  7038. ast.receiver.visit(this, context);
  7039. return this.visitAll(ast.args, context);
  7040. };
  7041. RecursiveAstVisitor.prototype.visitAll = function (asts, context) {
  7042. var _this = this;
  7043. asts.forEach(function (ast) { return ast.visit(_this, context); });
  7044. return null;
  7045. };
  7046. RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { return null; };
  7047. return RecursiveAstVisitor;
  7048. }());
  7049. var AstTransformer$1 = /** @class */ (function () {
  7050. function AstTransformer() {
  7051. }
  7052. AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
  7053. AstTransformer.prototype.visitInterpolation = function (ast, context) {
  7054. return new Interpolation(ast.span, ast.strings, this.visitAll(ast.expressions));
  7055. };
  7056. AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
  7057. return new LiteralPrimitive(ast.span, ast.value);
  7058. };
  7059. AstTransformer.prototype.visitPropertyRead = function (ast, context) {
  7060. return new PropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  7061. };
  7062. AstTransformer.prototype.visitPropertyWrite = function (ast, context) {
  7063. return new PropertyWrite(ast.span, ast.receiver.visit(this), ast.name, ast.value.visit(this));
  7064. };
  7065. AstTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  7066. return new SafePropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  7067. };
  7068. AstTransformer.prototype.visitMethodCall = function (ast, context) {
  7069. return new MethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  7070. };
  7071. AstTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  7072. return new SafeMethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  7073. };
  7074. AstTransformer.prototype.visitFunctionCall = function (ast, context) {
  7075. return new FunctionCall(ast.span, ast.target.visit(this), this.visitAll(ast.args));
  7076. };
  7077. AstTransformer.prototype.visitLiteralArray = function (ast, context) {
  7078. return new LiteralArray(ast.span, this.visitAll(ast.expressions));
  7079. };
  7080. AstTransformer.prototype.visitLiteralMap = function (ast, context) {
  7081. return new LiteralMap(ast.span, ast.keys, this.visitAll(ast.values));
  7082. };
  7083. AstTransformer.prototype.visitBinary = function (ast, context) {
  7084. return new Binary(ast.span, ast.operation, ast.left.visit(this), ast.right.visit(this));
  7085. };
  7086. AstTransformer.prototype.visitPrefixNot = function (ast, context) {
  7087. return new PrefixNot(ast.span, ast.expression.visit(this));
  7088. };
  7089. AstTransformer.prototype.visitNonNullAssert = function (ast, context) {
  7090. return new NonNullAssert(ast.span, ast.expression.visit(this));
  7091. };
  7092. AstTransformer.prototype.visitConditional = function (ast, context) {
  7093. return new Conditional(ast.span, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
  7094. };
  7095. AstTransformer.prototype.visitPipe = function (ast, context) {
  7096. return new BindingPipe(ast.span, ast.exp.visit(this), ast.name, this.visitAll(ast.args));
  7097. };
  7098. AstTransformer.prototype.visitKeyedRead = function (ast, context) {
  7099. return new KeyedRead(ast.span, ast.obj.visit(this), ast.key.visit(this));
  7100. };
  7101. AstTransformer.prototype.visitKeyedWrite = function (ast, context) {
  7102. return new KeyedWrite(ast.span, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
  7103. };
  7104. AstTransformer.prototype.visitAll = function (asts) {
  7105. var res = new Array(asts.length);
  7106. for (var i = 0; i < asts.length; ++i) {
  7107. res[i] = asts[i].visit(this);
  7108. }
  7109. return res;
  7110. };
  7111. AstTransformer.prototype.visitChain = function (ast, context) {
  7112. return new Chain(ast.span, this.visitAll(ast.expressions));
  7113. };
  7114. AstTransformer.prototype.visitQuote = function (ast, context) {
  7115. return new Quote(ast.span, ast.prefix, ast.uninterpretedExpression, ast.location);
  7116. };
  7117. return AstTransformer;
  7118. }());
  7119. // A transformer that only creates new nodes if the transformer makes a change or
  7120. // a change is made a child node.
  7121. var AstMemoryEfficientTransformer = /** @class */ (function () {
  7122. function AstMemoryEfficientTransformer() {
  7123. }
  7124. AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
  7125. AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) {
  7126. var expressions = this.visitAll(ast.expressions);
  7127. if (expressions !== ast.expressions)
  7128. return new Interpolation(ast.span, ast.strings, expressions);
  7129. return ast;
  7130. };
  7131. AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return ast; };
  7132. AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) {
  7133. var receiver = ast.receiver.visit(this);
  7134. if (receiver !== ast.receiver) {
  7135. return new PropertyRead(ast.span, receiver, ast.name);
  7136. }
  7137. return ast;
  7138. };
  7139. AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) {
  7140. var receiver = ast.receiver.visit(this);
  7141. var value = ast.value.visit(this);
  7142. if (receiver !== ast.receiver || value !== ast.value) {
  7143. return new PropertyWrite(ast.span, receiver, ast.name, value);
  7144. }
  7145. return ast;
  7146. };
  7147. AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  7148. var receiver = ast.receiver.visit(this);
  7149. if (receiver !== ast.receiver) {
  7150. return new SafePropertyRead(ast.span, receiver, ast.name);
  7151. }
  7152. return ast;
  7153. };
  7154. AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) {
  7155. var receiver = ast.receiver.visit(this);
  7156. var args = this.visitAll(ast.args);
  7157. if (receiver !== ast.receiver || args !== ast.args) {
  7158. return new MethodCall(ast.span, receiver, ast.name, args);
  7159. }
  7160. return ast;
  7161. };
  7162. AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  7163. var receiver = ast.receiver.visit(this);
  7164. var args = this.visitAll(ast.args);
  7165. if (receiver !== ast.receiver || args !== ast.args) {
  7166. return new SafeMethodCall(ast.span, receiver, ast.name, args);
  7167. }
  7168. return ast;
  7169. };
  7170. AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) {
  7171. var target = ast.target && ast.target.visit(this);
  7172. var args = this.visitAll(ast.args);
  7173. if (target !== ast.target || args !== ast.args) {
  7174. return new FunctionCall(ast.span, target, args);
  7175. }
  7176. return ast;
  7177. };
  7178. AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) {
  7179. var expressions = this.visitAll(ast.expressions);
  7180. if (expressions !== ast.expressions) {
  7181. return new LiteralArray(ast.span, expressions);
  7182. }
  7183. return ast;
  7184. };
  7185. AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) {
  7186. var values = this.visitAll(ast.values);
  7187. if (values !== ast.values) {
  7188. return new LiteralMap(ast.span, ast.keys, values);
  7189. }
  7190. return ast;
  7191. };
  7192. AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) {
  7193. var left = ast.left.visit(this);
  7194. var right = ast.right.visit(this);
  7195. if (left !== ast.left || right !== ast.right) {
  7196. return new Binary(ast.span, ast.operation, left, right);
  7197. }
  7198. return ast;
  7199. };
  7200. AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) {
  7201. var expression = ast.expression.visit(this);
  7202. if (expression !== ast.expression) {
  7203. return new PrefixNot(ast.span, expression);
  7204. }
  7205. return ast;
  7206. };
  7207. AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) {
  7208. var expression = ast.expression.visit(this);
  7209. if (expression !== ast.expression) {
  7210. return new NonNullAssert(ast.span, expression);
  7211. }
  7212. return ast;
  7213. };
  7214. AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) {
  7215. var condition = ast.condition.visit(this);
  7216. var trueExp = ast.trueExp.visit(this);
  7217. var falseExp = ast.falseExp.visit(this);
  7218. if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
  7219. return new Conditional(ast.span, condition, trueExp, falseExp);
  7220. }
  7221. return ast;
  7222. };
  7223. AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) {
  7224. var exp = ast.exp.visit(this);
  7225. var args = this.visitAll(ast.args);
  7226. if (exp !== ast.exp || args !== ast.args) {
  7227. return new BindingPipe(ast.span, exp, ast.name, args);
  7228. }
  7229. return ast;
  7230. };
  7231. AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) {
  7232. var obj = ast.obj.visit(this);
  7233. var key = ast.key.visit(this);
  7234. if (obj !== ast.obj || key !== ast.key) {
  7235. return new KeyedRead(ast.span, obj, key);
  7236. }
  7237. return ast;
  7238. };
  7239. AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) {
  7240. var obj = ast.obj.visit(this);
  7241. var key = ast.key.visit(this);
  7242. var value = ast.value.visit(this);
  7243. if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
  7244. return new KeyedWrite(ast.span, obj, key, value);
  7245. }
  7246. return ast;
  7247. };
  7248. AstMemoryEfficientTransformer.prototype.visitAll = function (asts) {
  7249. var res = new Array(asts.length);
  7250. var modified = false;
  7251. for (var i = 0; i < asts.length; ++i) {
  7252. var original = asts[i];
  7253. var value = original.visit(this);
  7254. res[i] = value;
  7255. modified = modified || value !== original;
  7256. }
  7257. return modified ? res : asts;
  7258. };
  7259. AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) {
  7260. var expressions = this.visitAll(ast.expressions);
  7261. if (expressions !== ast.expressions) {
  7262. return new Chain(ast.span, expressions);
  7263. }
  7264. return ast;
  7265. };
  7266. AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) { return ast; };
  7267. return AstMemoryEfficientTransformer;
  7268. }());
  7269. function visitAstChildren(ast, visitor, context) {
  7270. function visit(ast) {
  7271. visitor.visit && visitor.visit(ast, context) || ast.visit(visitor, context);
  7272. }
  7273. function visitAll(asts) { asts.forEach(visit); }
  7274. ast.visit({
  7275. visitBinary: function (ast) {
  7276. visit(ast.left);
  7277. visit(ast.right);
  7278. },
  7279. visitChain: function (ast) { visitAll(ast.expressions); },
  7280. visitConditional: function (ast) {
  7281. visit(ast.condition);
  7282. visit(ast.trueExp);
  7283. visit(ast.falseExp);
  7284. },
  7285. visitFunctionCall: function (ast) {
  7286. if (ast.target) {
  7287. visit(ast.target);
  7288. }
  7289. visitAll(ast.args);
  7290. },
  7291. visitImplicitReceiver: function (ast) { },
  7292. visitInterpolation: function (ast) { visitAll(ast.expressions); },
  7293. visitKeyedRead: function (ast) {
  7294. visit(ast.obj);
  7295. visit(ast.key);
  7296. },
  7297. visitKeyedWrite: function (ast) {
  7298. visit(ast.obj);
  7299. visit(ast.key);
  7300. visit(ast.obj);
  7301. },
  7302. visitLiteralArray: function (ast) { visitAll(ast.expressions); },
  7303. visitLiteralMap: function (ast) { },
  7304. visitLiteralPrimitive: function (ast) { },
  7305. visitMethodCall: function (ast) {
  7306. visit(ast.receiver);
  7307. visitAll(ast.args);
  7308. },
  7309. visitPipe: function (ast) {
  7310. visit(ast.exp);
  7311. visitAll(ast.args);
  7312. },
  7313. visitPrefixNot: function (ast) { visit(ast.expression); },
  7314. visitNonNullAssert: function (ast) { visit(ast.expression); },
  7315. visitPropertyRead: function (ast) { visit(ast.receiver); },
  7316. visitPropertyWrite: function (ast) {
  7317. visit(ast.receiver);
  7318. visit(ast.value);
  7319. },
  7320. visitQuote: function (ast) { },
  7321. visitSafeMethodCall: function (ast) {
  7322. visit(ast.receiver);
  7323. visitAll(ast.args);
  7324. },
  7325. visitSafePropertyRead: function (ast) { visit(ast.receiver); },
  7326. });
  7327. }
  7328. // Bindings
  7329. var ParsedProperty = /** @class */ (function () {
  7330. function ParsedProperty(name, expression, type, sourceSpan) {
  7331. this.name = name;
  7332. this.expression = expression;
  7333. this.type = type;
  7334. this.sourceSpan = sourceSpan;
  7335. this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
  7336. this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
  7337. }
  7338. return ParsedProperty;
  7339. }());
  7340. var ParsedPropertyType;
  7341. (function (ParsedPropertyType) {
  7342. ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
  7343. ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
  7344. ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
  7345. })(ParsedPropertyType || (ParsedPropertyType = {}));
  7346. var ParsedEvent = /** @class */ (function () {
  7347. // Regular events have a target
  7348. // Animation events have a phase
  7349. function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan, handlerSpan) {
  7350. this.name = name;
  7351. this.targetOrPhase = targetOrPhase;
  7352. this.type = type;
  7353. this.handler = handler;
  7354. this.sourceSpan = sourceSpan;
  7355. this.handlerSpan = handlerSpan;
  7356. }
  7357. return ParsedEvent;
  7358. }());
  7359. var ParsedVariable = /** @class */ (function () {
  7360. function ParsedVariable(name, value, sourceSpan) {
  7361. this.name = name;
  7362. this.value = value;
  7363. this.sourceSpan = sourceSpan;
  7364. }
  7365. return ParsedVariable;
  7366. }());
  7367. var BoundElementProperty = /** @class */ (function () {
  7368. function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan) {
  7369. this.name = name;
  7370. this.type = type;
  7371. this.securityContext = securityContext;
  7372. this.value = value;
  7373. this.unit = unit;
  7374. this.sourceSpan = sourceSpan;
  7375. }
  7376. return BoundElementProperty;
  7377. }());
  7378. /**
  7379. * @license
  7380. * Copyright Google Inc. All Rights Reserved.
  7381. *
  7382. * Use of this source code is governed by an MIT-style license that can be
  7383. * found in the LICENSE file at https://angular.io/license
  7384. */
  7385. var EventHandlerVars = /** @class */ (function () {
  7386. function EventHandlerVars() {
  7387. }
  7388. EventHandlerVars.event = variable('$event');
  7389. return EventHandlerVars;
  7390. }());
  7391. var ConvertActionBindingResult = /** @class */ (function () {
  7392. function ConvertActionBindingResult(
  7393. /**
  7394. * Render2 compatible statements,
  7395. */
  7396. stmts,
  7397. /**
  7398. * Variable name used with render2 compatible statements.
  7399. */
  7400. allowDefault) {
  7401. this.stmts = stmts;
  7402. this.allowDefault = allowDefault;
  7403. /**
  7404. * This is bit of a hack. It converts statements which render2 expects to statements which are
  7405. * expected by render3.
  7406. *
  7407. * Example: `<div click="doSomething($event)">` will generate:
  7408. *
  7409. * Render3:
  7410. * ```
  7411. * const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
  7412. * return pd_b;
  7413. * ```
  7414. *
  7415. * but render2 expects:
  7416. * ```
  7417. * return ctx.doSomething($event);
  7418. * ```
  7419. */
  7420. // TODO(misko): remove this hack once we no longer support ViewEngine.
  7421. this.render3Stmts = stmts.map(function (statement) {
  7422. if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
  7423. statement.value instanceof BinaryOperatorExpr) {
  7424. var lhs = statement.value.lhs;
  7425. return new ReturnStatement(lhs.value);
  7426. }
  7427. return statement;
  7428. });
  7429. }
  7430. return ConvertActionBindingResult;
  7431. }());
  7432. /**
  7433. * Converts the given expression AST into an executable output AST, assuming the expression is
  7434. * used in an action binding (e.g. an event handler).
  7435. */
  7436. function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan) {
  7437. if (!localResolver) {
  7438. localResolver = new DefaultLocalResolver();
  7439. }
  7440. var actionWithoutBuiltins = convertPropertyBindingBuiltins({
  7441. createLiteralArrayConverter: function (argCount) {
  7442. // Note: no caching for literal arrays in actions.
  7443. return function (args) { return literalArr(args); };
  7444. },
  7445. createLiteralMapConverter: function (keys) {
  7446. // Note: no caching for literal maps in actions.
  7447. return function (values) {
  7448. var entries = keys.map(function (k, i) { return ({
  7449. key: k.key,
  7450. value: values[i],
  7451. quoted: k.quoted,
  7452. }); });
  7453. return literalMap(entries);
  7454. };
  7455. },
  7456. createPipeConverter: function (name) {
  7457. throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name);
  7458. }
  7459. }, action);
  7460. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan);
  7461. var actionStmts = [];
  7462. flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
  7463. prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
  7464. if (visitor.usesImplicitReceiver) {
  7465. localResolver.notifyImplicitReceiverUse();
  7466. }
  7467. var lastIndex = actionStmts.length - 1;
  7468. var preventDefaultVar = null;
  7469. if (lastIndex >= 0) {
  7470. var lastStatement = actionStmts[lastIndex];
  7471. var returnExpr = convertStmtIntoExpression(lastStatement);
  7472. if (returnExpr) {
  7473. // Note: We need to cast the result of the method call to dynamic,
  7474. // as it might be a void method!
  7475. preventDefaultVar = createPreventDefaultVar(bindingId);
  7476. actionStmts[lastIndex] =
  7477. preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
  7478. .toDeclStmt(null, [StmtModifier.Final]);
  7479. }
  7480. }
  7481. return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
  7482. }
  7483. function convertPropertyBindingBuiltins(converterFactory, ast) {
  7484. return convertBuiltins(converterFactory, ast);
  7485. }
  7486. var ConvertPropertyBindingResult = /** @class */ (function () {
  7487. function ConvertPropertyBindingResult(stmts, currValExpr) {
  7488. this.stmts = stmts;
  7489. this.currValExpr = currValExpr;
  7490. }
  7491. return ConvertPropertyBindingResult;
  7492. }());
  7493. var BindingForm;
  7494. (function (BindingForm) {
  7495. // The general form of binding expression, supports all expressions.
  7496. BindingForm[BindingForm["General"] = 0] = "General";
  7497. // Try to generate a simple binding (no temporaries or statements)
  7498. // otherwise generate a general binding
  7499. BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
  7500. })(BindingForm || (BindingForm = {}));
  7501. /**
  7502. * Converts the given expression AST into an executable output AST, assuming the expression
  7503. * is used in property binding. The expression has to be preprocessed via
  7504. * `convertPropertyBindingBuiltins`.
  7505. */
  7506. function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
  7507. if (!localResolver) {
  7508. localResolver = new DefaultLocalResolver();
  7509. }
  7510. var currValExpr = createCurrValueExpr(bindingId);
  7511. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
  7512. var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
  7513. var stmts = getStatementsFromVisitor(visitor, bindingId);
  7514. if (visitor.usesImplicitReceiver) {
  7515. localResolver.notifyImplicitReceiverUse();
  7516. }
  7517. if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
  7518. return new ConvertPropertyBindingResult([], outputExpr);
  7519. }
  7520. stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [StmtModifier.Final]));
  7521. return new ConvertPropertyBindingResult(stmts, currValExpr);
  7522. }
  7523. /**
  7524. * Given some expression, such as a binding or interpolation expression, and a context expression to
  7525. * look values up on, visit each facet of the given expression resolving values from the context
  7526. * expression such that a list of arguments can be derived from the found values that can be used as
  7527. * arguments to an external update instruction.
  7528. *
  7529. * @param localResolver The resolver to use to look up expressions by name appropriately
  7530. * @param contextVariableExpression The expression representing the context variable used to create
  7531. * the final argument expressions
  7532. * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
  7533. * be resolved and what arguments list to build.
  7534. * @param bindingId A name prefix used to create temporary variable names if they're needed for the
  7535. * arguments generated
  7536. * @returns An array of expressions that can be passed as arguments to instruction expressions like
  7537. * `o.importExpr(R3.propertyInterpolate).callFn(result)`
  7538. */
  7539. function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
  7540. var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
  7541. var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
  7542. if (visitor.usesImplicitReceiver) {
  7543. localResolver.notifyImplicitReceiverUse();
  7544. }
  7545. var stmts = getStatementsFromVisitor(visitor, bindingId);
  7546. // Removing the first argument, because it was a length for ViewEngine, not Ivy.
  7547. var args = outputExpr.args.slice(1);
  7548. if (expressionWithArgumentsToExtract instanceof Interpolation) {
  7549. // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
  7550. // args returned to just the value, because we're going to pass it to a special instruction.
  7551. var strings = expressionWithArgumentsToExtract.strings;
  7552. if (args.length === 3 && strings[0] === '' && strings[1] === '') {
  7553. // Single argument interpolate instructions.
  7554. args = [args[1]];
  7555. }
  7556. else if (args.length >= 19) {
  7557. // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
  7558. // an array of arguments
  7559. args = [literalArr(args)];
  7560. }
  7561. }
  7562. return { stmts: stmts, args: args };
  7563. }
  7564. function getStatementsFromVisitor(visitor, bindingId) {
  7565. var stmts = [];
  7566. for (var i = 0; i < visitor.temporaryCount; i++) {
  7567. stmts.push(temporaryDeclaration(bindingId, i));
  7568. }
  7569. return stmts;
  7570. }
  7571. function convertBuiltins(converterFactory, ast) {
  7572. var visitor = new _BuiltinAstConverter(converterFactory);
  7573. return ast.visit(visitor);
  7574. }
  7575. function temporaryName(bindingId, temporaryNumber) {
  7576. return "tmp_" + bindingId + "_" + temporaryNumber;
  7577. }
  7578. function temporaryDeclaration(bindingId, temporaryNumber) {
  7579. return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
  7580. }
  7581. function prependTemporaryDecls(temporaryCount, bindingId, statements) {
  7582. for (var i = temporaryCount - 1; i >= 0; i--) {
  7583. statements.unshift(temporaryDeclaration(bindingId, i));
  7584. }
  7585. }
  7586. var _Mode;
  7587. (function (_Mode) {
  7588. _Mode[_Mode["Statement"] = 0] = "Statement";
  7589. _Mode[_Mode["Expression"] = 1] = "Expression";
  7590. })(_Mode || (_Mode = {}));
  7591. function ensureStatementMode(mode, ast) {
  7592. if (mode !== _Mode.Statement) {
  7593. throw new Error("Expected a statement, but saw " + ast);
  7594. }
  7595. }
  7596. function ensureExpressionMode(mode, ast) {
  7597. if (mode !== _Mode.Expression) {
  7598. throw new Error("Expected an expression, but saw " + ast);
  7599. }
  7600. }
  7601. function convertToStatementIfNeeded(mode, expr) {
  7602. if (mode === _Mode.Statement) {
  7603. return expr.toStmt();
  7604. }
  7605. else {
  7606. return expr;
  7607. }
  7608. }
  7609. var _BuiltinAstConverter = /** @class */ (function (_super) {
  7610. __extends(_BuiltinAstConverter, _super);
  7611. function _BuiltinAstConverter(_converterFactory) {
  7612. var _this = _super.call(this) || this;
  7613. _this._converterFactory = _converterFactory;
  7614. return _this;
  7615. }
  7616. _BuiltinAstConverter.prototype.visitPipe = function (ast, context) {
  7617. var _this = this;
  7618. var args = __spread([ast.exp], ast.args).map(function (ast) { return ast.visit(_this, context); });
  7619. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createPipeConverter(ast.name, args.length));
  7620. };
  7621. _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) {
  7622. var _this = this;
  7623. var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); });
  7624. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
  7625. };
  7626. _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) {
  7627. var _this = this;
  7628. var args = ast.values.map(function (ast) { return ast.visit(_this, context); });
  7629. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
  7630. };
  7631. return _BuiltinAstConverter;
  7632. }(AstTransformer$1));
  7633. var _AstToIrVisitor = /** @class */ (function () {
  7634. function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan) {
  7635. this._localResolver = _localResolver;
  7636. this._implicitReceiver = _implicitReceiver;
  7637. this.bindingId = bindingId;
  7638. this.interpolationFunction = interpolationFunction;
  7639. this.baseSourceSpan = baseSourceSpan;
  7640. this._nodeMap = new Map();
  7641. this._resultMap = new Map();
  7642. this._currentTemporary = 0;
  7643. this.temporaryCount = 0;
  7644. this.usesImplicitReceiver = false;
  7645. }
  7646. _AstToIrVisitor.prototype.visitBinary = function (ast, mode) {
  7647. var op;
  7648. switch (ast.operation) {
  7649. case '+':
  7650. op = BinaryOperator.Plus;
  7651. break;
  7652. case '-':
  7653. op = BinaryOperator.Minus;
  7654. break;
  7655. case '*':
  7656. op = BinaryOperator.Multiply;
  7657. break;
  7658. case '/':
  7659. op = BinaryOperator.Divide;
  7660. break;
  7661. case '%':
  7662. op = BinaryOperator.Modulo;
  7663. break;
  7664. case '&&':
  7665. op = BinaryOperator.And;
  7666. break;
  7667. case '||':
  7668. op = BinaryOperator.Or;
  7669. break;
  7670. case '==':
  7671. op = BinaryOperator.Equals;
  7672. break;
  7673. case '!=':
  7674. op = BinaryOperator.NotEquals;
  7675. break;
  7676. case '===':
  7677. op = BinaryOperator.Identical;
  7678. break;
  7679. case '!==':
  7680. op = BinaryOperator.NotIdentical;
  7681. break;
  7682. case '<':
  7683. op = BinaryOperator.Lower;
  7684. break;
  7685. case '>':
  7686. op = BinaryOperator.Bigger;
  7687. break;
  7688. case '<=':
  7689. op = BinaryOperator.LowerEquals;
  7690. break;
  7691. case '>=':
  7692. op = BinaryOperator.BiggerEquals;
  7693. break;
  7694. default:
  7695. throw new Error("Unsupported operation " + ast.operation);
  7696. }
  7697. return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
  7698. };
  7699. _AstToIrVisitor.prototype.visitChain = function (ast, mode) {
  7700. ensureStatementMode(mode, ast);
  7701. return this.visitAll(ast.expressions, mode);
  7702. };
  7703. _AstToIrVisitor.prototype.visitConditional = function (ast, mode) {
  7704. var value = this._visit(ast.condition, _Mode.Expression);
  7705. return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
  7706. };
  7707. _AstToIrVisitor.prototype.visitPipe = function (ast, mode) {
  7708. throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name);
  7709. };
  7710. _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) {
  7711. var convertedArgs = this.visitAll(ast.args, _Mode.Expression);
  7712. var fnResult;
  7713. if (ast instanceof BuiltinFunctionCall) {
  7714. fnResult = ast.converter(convertedArgs);
  7715. }
  7716. else {
  7717. fnResult = this._visit(ast.target, _Mode.Expression)
  7718. .callFn(convertedArgs, this.convertSourceSpan(ast.span));
  7719. }
  7720. return convertToStatementIfNeeded(mode, fnResult);
  7721. };
  7722. _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) {
  7723. ensureExpressionMode(mode, ast);
  7724. this.usesImplicitReceiver = true;
  7725. return this._implicitReceiver;
  7726. };
  7727. _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) {
  7728. ensureExpressionMode(mode, ast);
  7729. var args = [literal(ast.expressions.length)];
  7730. for (var i = 0; i < ast.strings.length - 1; i++) {
  7731. args.push(literal(ast.strings[i]));
  7732. args.push(this._visit(ast.expressions[i], _Mode.Expression));
  7733. }
  7734. args.push(literal(ast.strings[ast.strings.length - 1]));
  7735. if (this.interpolationFunction) {
  7736. return this.interpolationFunction(args);
  7737. }
  7738. return ast.expressions.length <= 9 ?
  7739. importExpr(Identifiers.inlineInterpolate).callFn(args) :
  7740. importExpr(Identifiers.interpolate).callFn([
  7741. args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
  7742. ]);
  7743. };
  7744. _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) {
  7745. var leftMostSafe = this.leftMostSafeNode(ast);
  7746. if (leftMostSafe) {
  7747. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7748. }
  7749. else {
  7750. return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
  7751. }
  7752. };
  7753. _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) {
  7754. var obj = this._visit(ast.obj, _Mode.Expression);
  7755. var key = this._visit(ast.key, _Mode.Expression);
  7756. var value = this._visit(ast.value, _Mode.Expression);
  7757. return convertToStatementIfNeeded(mode, obj.key(key).set(value));
  7758. };
  7759. _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) {
  7760. throw new Error("Illegal State: literal arrays should have been converted into functions");
  7761. };
  7762. _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) {
  7763. throw new Error("Illegal State: literal maps should have been converted into functions");
  7764. };
  7765. _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) {
  7766. // For literal values of null, undefined, true, or false allow type interference
  7767. // to infer the type.
  7768. var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
  7769. INFERRED_TYPE :
  7770. undefined;
  7771. return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
  7772. };
  7773. _AstToIrVisitor.prototype._getLocal = function (name) { return this._localResolver.getLocal(name); };
  7774. _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) {
  7775. if (ast.receiver instanceof ImplicitReceiver && ast.name == '$any') {
  7776. var args = this.visitAll(ast.args, _Mode.Expression);
  7777. if (args.length != 1) {
  7778. throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none'));
  7779. }
  7780. return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
  7781. }
  7782. var leftMostSafe = this.leftMostSafeNode(ast);
  7783. if (leftMostSafe) {
  7784. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7785. }
  7786. else {
  7787. var args = this.visitAll(ast.args, _Mode.Expression);
  7788. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7789. var result = null;
  7790. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7791. if (receiver === this._implicitReceiver) {
  7792. var varExpr = this._getLocal(ast.name);
  7793. if (varExpr) {
  7794. // Restore the previous "usesImplicitReceiver" state since the implicit
  7795. // receiver has been replaced with a resolved local expression.
  7796. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7797. result = varExpr.callFn(args);
  7798. }
  7799. }
  7800. if (result == null) {
  7801. result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
  7802. }
  7803. return convertToStatementIfNeeded(mode, result);
  7804. }
  7805. };
  7806. _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) {
  7807. return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
  7808. };
  7809. _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) {
  7810. return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
  7811. };
  7812. _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) {
  7813. var leftMostSafe = this.leftMostSafeNode(ast);
  7814. if (leftMostSafe) {
  7815. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7816. }
  7817. else {
  7818. var result = null;
  7819. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7820. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7821. if (receiver === this._implicitReceiver) {
  7822. result = this._getLocal(ast.name);
  7823. if (result) {
  7824. // Restore the previous "usesImplicitReceiver" state since the implicit
  7825. // receiver has been replaced with a resolved local expression.
  7826. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7827. }
  7828. }
  7829. if (result == null) {
  7830. result = receiver.prop(ast.name);
  7831. }
  7832. return convertToStatementIfNeeded(mode, result);
  7833. }
  7834. };
  7835. _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) {
  7836. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7837. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7838. var varExpr = null;
  7839. if (receiver === this._implicitReceiver) {
  7840. var localExpr = this._getLocal(ast.name);
  7841. if (localExpr) {
  7842. if (localExpr instanceof ReadPropExpr) {
  7843. // If the local variable is a property read expression, it's a reference
  7844. // to a 'context.property' value and will be used as the target of the
  7845. // write expression.
  7846. varExpr = localExpr;
  7847. // Restore the previous "usesImplicitReceiver" state since the implicit
  7848. // receiver has been replaced with a resolved local expression.
  7849. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7850. }
  7851. else {
  7852. // Otherwise it's an error.
  7853. throw new Error('Cannot assign to a reference or variable!');
  7854. }
  7855. }
  7856. }
  7857. // If no local expression could be produced, use the original receiver's
  7858. // property as the target.
  7859. if (varExpr === null) {
  7860. varExpr = receiver.prop(ast.name);
  7861. }
  7862. return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
  7863. };
  7864. _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) {
  7865. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  7866. };
  7867. _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) {
  7868. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  7869. };
  7870. _AstToIrVisitor.prototype.visitAll = function (asts, mode) {
  7871. var _this = this;
  7872. return asts.map(function (ast) { return _this._visit(ast, mode); });
  7873. };
  7874. _AstToIrVisitor.prototype.visitQuote = function (ast, mode) {
  7875. throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location);
  7876. };
  7877. _AstToIrVisitor.prototype._visit = function (ast, mode) {
  7878. var result = this._resultMap.get(ast);
  7879. if (result)
  7880. return result;
  7881. return (this._nodeMap.get(ast) || ast).visit(this, mode);
  7882. };
  7883. _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) {
  7884. // If the expression contains a safe access node on the left it needs to be converted to
  7885. // an expression that guards the access to the member by checking the receiver for blank. As
  7886. // execution proceeds from left to right, the left most part of the expression must be guarded
  7887. // first but, because member access is left associative, the right side of the expression is at
  7888. // the top of the AST. The desired result requires lifting a copy of the the left part of the
  7889. // expression up to test it for blank before generating the unguarded version.
  7890. // Consider, for example the following expression: a?.b.c?.d.e
  7891. // This results in the ast:
  7892. // .
  7893. // / \
  7894. // ?. e
  7895. // / \
  7896. // . d
  7897. // / \
  7898. // ?. c
  7899. // / \
  7900. // a b
  7901. // The following tree should be generated:
  7902. //
  7903. // /---- ? ----\
  7904. // / | \
  7905. // a /--- ? ---\ null
  7906. // / | \
  7907. // . . null
  7908. // / \ / \
  7909. // . c . e
  7910. // / \ / \
  7911. // a b . d
  7912. // / \
  7913. // . c
  7914. // / \
  7915. // a b
  7916. //
  7917. // Notice that the first guard condition is the left hand of the left most safe access node
  7918. // which comes in as leftMostSafe to this routine.
  7919. var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
  7920. var temporary = undefined;
  7921. if (this.needsTemporary(leftMostSafe.receiver)) {
  7922. // If the expression has method calls or pipes then we need to save the result into a
  7923. // temporary variable to avoid calling stateful or impure code more than once.
  7924. temporary = this.allocateTemporary();
  7925. // Preserve the result in the temporary variable
  7926. guardedExpression = temporary.set(guardedExpression);
  7927. // Ensure all further references to the guarded expression refer to the temporary instead.
  7928. this._resultMap.set(leftMostSafe.receiver, temporary);
  7929. }
  7930. var condition = guardedExpression.isBlank();
  7931. // Convert the ast to an unguarded access to the receiver's member. The map will substitute
  7932. // leftMostNode with its unguarded version in the call to `this.visit()`.
  7933. if (leftMostSafe instanceof SafeMethodCall) {
  7934. this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
  7935. }
  7936. else {
  7937. this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name));
  7938. }
  7939. // Recursively convert the node now without the guarded member access.
  7940. var access = this._visit(ast, _Mode.Expression);
  7941. // Remove the mapping. This is not strictly required as the converter only traverses each node
  7942. // once but is safer if the conversion is changed to traverse the nodes more than once.
  7943. this._nodeMap.delete(leftMostSafe);
  7944. // If we allocated a temporary, release it.
  7945. if (temporary) {
  7946. this.releaseTemporary(temporary);
  7947. }
  7948. // Produce the conditional
  7949. return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
  7950. };
  7951. // Given a expression of the form a?.b.c?.d.e the the left most safe node is
  7952. // the (a?.b). The . and ?. are left associative thus can be rewritten as:
  7953. // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
  7954. // safe method call as this needs be transform initially to:
  7955. // a == null ? null : a.c.b.c?.d.e
  7956. // then to:
  7957. // a == null ? null : a.b.c == null ? null : a.b.c.d.e
  7958. _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) {
  7959. var _this = this;
  7960. var visit = function (visitor, ast) {
  7961. return (_this._nodeMap.get(ast) || ast).visit(visitor);
  7962. };
  7963. return ast.visit({
  7964. visitBinary: function (ast) { return null; },
  7965. visitChain: function (ast) { return null; },
  7966. visitConditional: function (ast) { return null; },
  7967. visitFunctionCall: function (ast) { return null; },
  7968. visitImplicitReceiver: function (ast) { return null; },
  7969. visitInterpolation: function (ast) { return null; },
  7970. visitKeyedRead: function (ast) { return visit(this, ast.obj); },
  7971. visitKeyedWrite: function (ast) { return null; },
  7972. visitLiteralArray: function (ast) { return null; },
  7973. visitLiteralMap: function (ast) { return null; },
  7974. visitLiteralPrimitive: function (ast) { return null; },
  7975. visitMethodCall: function (ast) { return visit(this, ast.receiver); },
  7976. visitPipe: function (ast) { return null; },
  7977. visitPrefixNot: function (ast) { return null; },
  7978. visitNonNullAssert: function (ast) { return null; },
  7979. visitPropertyRead: function (ast) { return visit(this, ast.receiver); },
  7980. visitPropertyWrite: function (ast) { return null; },
  7981. visitQuote: function (ast) { return null; },
  7982. visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; },
  7983. visitSafePropertyRead: function (ast) {
  7984. return visit(this, ast.receiver) || ast;
  7985. }
  7986. });
  7987. };
  7988. // Returns true of the AST includes a method or a pipe indicating that, if the
  7989. // expression is used as the target of a safe property or method access then
  7990. // the expression should be stored into a temporary variable.
  7991. _AstToIrVisitor.prototype.needsTemporary = function (ast) {
  7992. var _this = this;
  7993. var visit = function (visitor, ast) {
  7994. return ast && (_this._nodeMap.get(ast) || ast).visit(visitor);
  7995. };
  7996. var visitSome = function (visitor, ast) {
  7997. return ast.some(function (ast) { return visit(visitor, ast); });
  7998. };
  7999. return ast.visit({
  8000. visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); },
  8001. visitChain: function (ast) { return false; },
  8002. visitConditional: function (ast) {
  8003. return visit(this, ast.condition) || visit(this, ast.trueExp) ||
  8004. visit(this, ast.falseExp);
  8005. },
  8006. visitFunctionCall: function (ast) { return true; },
  8007. visitImplicitReceiver: function (ast) { return false; },
  8008. visitInterpolation: function (ast) { return visitSome(this, ast.expressions); },
  8009. visitKeyedRead: function (ast) { return false; },
  8010. visitKeyedWrite: function (ast) { return false; },
  8011. visitLiteralArray: function (ast) { return true; },
  8012. visitLiteralMap: function (ast) { return true; },
  8013. visitLiteralPrimitive: function (ast) { return false; },
  8014. visitMethodCall: function (ast) { return true; },
  8015. visitPipe: function (ast) { return true; },
  8016. visitPrefixNot: function (ast) { return visit(this, ast.expression); },
  8017. visitNonNullAssert: function (ast) { return visit(this, ast.expression); },
  8018. visitPropertyRead: function (ast) { return false; },
  8019. visitPropertyWrite: function (ast) { return false; },
  8020. visitQuote: function (ast) { return false; },
  8021. visitSafeMethodCall: function (ast) { return true; },
  8022. visitSafePropertyRead: function (ast) { return false; }
  8023. });
  8024. };
  8025. _AstToIrVisitor.prototype.allocateTemporary = function () {
  8026. var tempNumber = this._currentTemporary++;
  8027. this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
  8028. return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
  8029. };
  8030. _AstToIrVisitor.prototype.releaseTemporary = function (temporary) {
  8031. this._currentTemporary--;
  8032. if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
  8033. throw new Error("Temporary " + temporary.name + " released out of order");
  8034. }
  8035. };
  8036. /**
  8037. * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
  8038. *
  8039. * `ParseSpan` objects are relative to the start of the expression.
  8040. * This method converts these to full `ParseSourceSpan` objects that
  8041. * show where the span is within the overall source file.
  8042. *
  8043. * @param span the relative span to convert.
  8044. * @returns a `ParseSourceSpan` for the the given span or null if no
  8045. * `baseSourceSpan` was provided to this class.
  8046. */
  8047. _AstToIrVisitor.prototype.convertSourceSpan = function (span) {
  8048. if (this.baseSourceSpan) {
  8049. var start = this.baseSourceSpan.start.moveBy(span.start);
  8050. var end = this.baseSourceSpan.start.moveBy(span.end);
  8051. return new ParseSourceSpan(start, end);
  8052. }
  8053. else {
  8054. return null;
  8055. }
  8056. };
  8057. return _AstToIrVisitor;
  8058. }());
  8059. function flattenStatements(arg, output) {
  8060. if (Array.isArray(arg)) {
  8061. arg.forEach(function (entry) { return flattenStatements(entry, output); });
  8062. }
  8063. else {
  8064. output.push(arg);
  8065. }
  8066. }
  8067. var DefaultLocalResolver = /** @class */ (function () {
  8068. function DefaultLocalResolver() {
  8069. }
  8070. DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  8071. DefaultLocalResolver.prototype.getLocal = function (name) {
  8072. if (name === EventHandlerVars.event.name) {
  8073. return EventHandlerVars.event;
  8074. }
  8075. return null;
  8076. };
  8077. return DefaultLocalResolver;
  8078. }());
  8079. function createCurrValueExpr(bindingId) {
  8080. return variable("currVal_" + bindingId); // fix syntax highlighting: `
  8081. }
  8082. function createPreventDefaultVar(bindingId) {
  8083. return variable("pd_" + bindingId);
  8084. }
  8085. function convertStmtIntoExpression(stmt) {
  8086. if (stmt instanceof ExpressionStatement) {
  8087. return stmt.expr;
  8088. }
  8089. else if (stmt instanceof ReturnStatement) {
  8090. return stmt.value;
  8091. }
  8092. return null;
  8093. }
  8094. var BuiltinFunctionCall = /** @class */ (function (_super) {
  8095. __extends(BuiltinFunctionCall, _super);
  8096. function BuiltinFunctionCall(span, args, converter) {
  8097. var _this = _super.call(this, span, null, args) || this;
  8098. _this.args = args;
  8099. _this.converter = converter;
  8100. return _this;
  8101. }
  8102. return BuiltinFunctionCall;
  8103. }(FunctionCall));
  8104. /**
  8105. * @license
  8106. * Copyright Google Inc. All Rights Reserved.
  8107. *
  8108. * Use of this source code is governed by an MIT-style license that can be
  8109. * found in the LICENSE file at https://angular.io/license
  8110. */
  8111. /**
  8112. * This file is a port of shadowCSS from webcomponents.js to TypeScript.
  8113. *
  8114. * Please make sure to keep to edits in sync with the source file.
  8115. *
  8116. * Source:
  8117. * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
  8118. *
  8119. * The original file level comment is reproduced below
  8120. */
  8121. /*
  8122. This is a limited shim for ShadowDOM css styling.
  8123. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
  8124. The intention here is to support only the styling features which can be
  8125. relatively simply implemented. The goal is to allow users to avoid the
  8126. most obvious pitfalls and do so without compromising performance significantly.
  8127. For ShadowDOM styling that's not covered here, a set of best practices
  8128. can be provided that should allow users to accomplish more complex styling.
  8129. The following is a list of specific ShadowDOM styling features and a brief
  8130. discussion of the approach used to shim.
  8131. Shimmed features:
  8132. * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
  8133. element using the :host rule. To shim this feature, the :host styles are
  8134. reformatted and prefixed with a given scope name and promoted to a
  8135. document level stylesheet.
  8136. For example, given a scope name of .foo, a rule like this:
  8137. :host {
  8138. background: red;
  8139. }
  8140. }
  8141. becomes:
  8142. .foo {
  8143. background: red;
  8144. }
  8145. * encapsulation: Styles defined within ShadowDOM, apply only to
  8146. dom inside the ShadowDOM. Polymer uses one of two techniques to implement
  8147. this feature.
  8148. By default, rules are prefixed with the host element tag name
  8149. as a descendant selector. This ensures styling does not leak out of the 'top'
  8150. of the element's ShadowDOM. For example,
  8151. div {
  8152. font-weight: bold;
  8153. }
  8154. becomes:
  8155. x-foo div {
  8156. font-weight: bold;
  8157. }
  8158. becomes:
  8159. Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
  8160. selectors are scoped by adding an attribute selector suffix to each
  8161. simple selector that contains the host element tag name. Each element
  8162. in the element's ShadowDOM template is also given the scope attribute.
  8163. Thus, these rules match only elements that have the scope attribute.
  8164. For example, given a scope name of x-foo, a rule like this:
  8165. div {
  8166. font-weight: bold;
  8167. }
  8168. becomes:
  8169. div[x-foo] {
  8170. font-weight: bold;
  8171. }
  8172. Note that elements that are dynamically added to a scope must have the scope
  8173. selector added to them manually.
  8174. * upper/lower bound encapsulation: Styles which are defined outside a
  8175. shadowRoot should not cross the ShadowDOM boundary and should not apply
  8176. inside a shadowRoot.
  8177. This styling behavior is not emulated. Some possible ways to do this that
  8178. were rejected due to complexity and/or performance concerns include: (1) reset
  8179. every possible property for every possible selector for a given scope name;
  8180. (2) re-implement css in javascript.
  8181. As an alternative, users should make sure to use selectors
  8182. specific to the scope in which they are working.
  8183. * ::distributed: This behavior is not emulated. It's often not necessary
  8184. to style the contents of a specific insertion point and instead, descendants
  8185. of the host element can be styled selectively. Users can also create an
  8186. extra node around an insertion point and style that node's contents
  8187. via descendent selectors. For example, with a shadowRoot like this:
  8188. <style>
  8189. ::content(div) {
  8190. background: red;
  8191. }
  8192. </style>
  8193. <content></content>
  8194. could become:
  8195. <style>
  8196. / *@polyfill .content-container div * /
  8197. ::content(div) {
  8198. background: red;
  8199. }
  8200. </style>
  8201. <div class="content-container">
  8202. <content></content>
  8203. </div>
  8204. Note the use of @polyfill in the comment above a ShadowDOM specific style
  8205. declaration. This is a directive to the styling shim to use the selector
  8206. in comments in lieu of the next selector when running under polyfill.
  8207. */
  8208. var ShadowCss = /** @class */ (function () {
  8209. function ShadowCss() {
  8210. this.strictStyling = true;
  8211. }
  8212. /*
  8213. * Shim some cssText with the given selector. Returns cssText that can
  8214. * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
  8215. *
  8216. * When strictStyling is true:
  8217. * - selector is the attribute added to all elements inside the host,
  8218. * - hostSelector is the attribute added to the host itself.
  8219. */
  8220. ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
  8221. if (hostSelector === void 0) { hostSelector = ''; }
  8222. var commentsWithHash = extractCommentsWithHash(cssText);
  8223. cssText = stripComments(cssText);
  8224. cssText = this._insertDirectives(cssText);
  8225. var scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
  8226. return __spread([scopedCssText], commentsWithHash).join('\n');
  8227. };
  8228. ShadowCss.prototype._insertDirectives = function (cssText) {
  8229. cssText = this._insertPolyfillDirectivesInCssText(cssText);
  8230. return this._insertPolyfillRulesInCssText(cssText);
  8231. };
  8232. /*
  8233. * Process styles to convert native ShadowDOM rules that will trip
  8234. * up the css parser; we rely on decorating the stylesheet with inert rules.
  8235. *
  8236. * For example, we convert this rule:
  8237. *
  8238. * polyfill-next-selector { content: ':host menu-item'; }
  8239. * ::content menu-item {
  8240. *
  8241. * to this:
  8242. *
  8243. * scopeName menu-item {
  8244. *
  8245. **/
  8246. ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
  8247. // Difference with webcomponents.js: does not handle comments
  8248. return cssText.replace(_cssContentNextSelectorRe, function () {
  8249. var m = [];
  8250. for (var _i = 0; _i < arguments.length; _i++) {
  8251. m[_i] = arguments[_i];
  8252. }
  8253. return m[2] + '{';
  8254. });
  8255. };
  8256. /*
  8257. * Process styles to add rules which will only apply under the polyfill
  8258. *
  8259. * For example, we convert this rule:
  8260. *
  8261. * polyfill-rule {
  8262. * content: ':host menu-item';
  8263. * ...
  8264. * }
  8265. *
  8266. * to this:
  8267. *
  8268. * scopeName menu-item {...}
  8269. *
  8270. **/
  8271. ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
  8272. // Difference with webcomponents.js: does not handle comments
  8273. return cssText.replace(_cssContentRuleRe, function () {
  8274. var m = [];
  8275. for (var _i = 0; _i < arguments.length; _i++) {
  8276. m[_i] = arguments[_i];
  8277. }
  8278. var rule = m[0].replace(m[1], '').replace(m[2], '');
  8279. return m[4] + rule;
  8280. });
  8281. };
  8282. /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
  8283. *
  8284. * .foo {... }
  8285. *
  8286. * and converts this to
  8287. *
  8288. * scopeName .foo { ... }
  8289. */
  8290. ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
  8291. var unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
  8292. // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
  8293. cssText = this._insertPolyfillHostInCssText(cssText);
  8294. cssText = this._convertColonHost(cssText);
  8295. cssText = this._convertColonHostContext(cssText);
  8296. cssText = this._convertShadowDOMSelectors(cssText);
  8297. if (scopeSelector) {
  8298. cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
  8299. }
  8300. cssText = cssText + '\n' + unscopedRules;
  8301. return cssText.trim();
  8302. };
  8303. /*
  8304. * Process styles to add rules which will only apply under the polyfill
  8305. * and do not process via CSSOM. (CSSOM is destructive to rules on rare
  8306. * occasions, e.g. -webkit-calc on Safari.)
  8307. * For example, we convert this rule:
  8308. *
  8309. * @polyfill-unscoped-rule {
  8310. * content: 'menu-item';
  8311. * ... }
  8312. *
  8313. * to this:
  8314. *
  8315. * menu-item {...}
  8316. *
  8317. **/
  8318. ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
  8319. // Difference with webcomponents.js: does not handle comments
  8320. var r = '';
  8321. var m;
  8322. _cssContentUnscopedRuleRe.lastIndex = 0;
  8323. while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
  8324. var rule = m[0].replace(m[2], '').replace(m[1], m[4]);
  8325. r += rule + '\n\n';
  8326. }
  8327. return r;
  8328. };
  8329. /*
  8330. * convert a rule like :host(.foo) > .bar { }
  8331. *
  8332. * to
  8333. *
  8334. * .foo<scopeName> > .bar
  8335. */
  8336. ShadowCss.prototype._convertColonHost = function (cssText) {
  8337. return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
  8338. };
  8339. /*
  8340. * convert a rule like :host-context(.foo) > .bar { }
  8341. *
  8342. * to
  8343. *
  8344. * .foo<scopeName> > .bar, .foo scopeName > .bar { }
  8345. *
  8346. * and
  8347. *
  8348. * :host-context(.foo:host) .bar { ... }
  8349. *
  8350. * to
  8351. *
  8352. * .foo<scopeName> .bar { ... }
  8353. */
  8354. ShadowCss.prototype._convertColonHostContext = function (cssText) {
  8355. return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
  8356. };
  8357. ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) {
  8358. // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
  8359. return cssText.replace(regExp, function () {
  8360. var m = [];
  8361. for (var _i = 0; _i < arguments.length; _i++) {
  8362. m[_i] = arguments[_i];
  8363. }
  8364. if (m[2]) {
  8365. var parts = m[2].split(',');
  8366. var r = [];
  8367. for (var i = 0; i < parts.length; i++) {
  8368. var p = parts[i].trim();
  8369. if (!p)
  8370. break;
  8371. r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
  8372. }
  8373. return r.join(',');
  8374. }
  8375. else {
  8376. return _polyfillHostNoCombinator + m[3];
  8377. }
  8378. });
  8379. };
  8380. ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) {
  8381. if (part.indexOf(_polyfillHost) > -1) {
  8382. return this._colonHostPartReplacer(host, part, suffix);
  8383. }
  8384. else {
  8385. return host + part + suffix + ', ' + part + ' ' + host + suffix;
  8386. }
  8387. };
  8388. ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) {
  8389. return host + part.replace(_polyfillHost, '') + suffix;
  8390. };
  8391. /*
  8392. * Convert combinators like ::shadow and pseudo-elements like ::content
  8393. * by replacing with space.
  8394. */
  8395. ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
  8396. return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText);
  8397. };
  8398. // change a selector like 'div' to 'name div'
  8399. ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
  8400. var _this = this;
  8401. return processRules(cssText, function (rule) {
  8402. var selector = rule.selector;
  8403. var content = rule.content;
  8404. if (rule.selector[0] != '@') {
  8405. selector =
  8406. _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
  8407. }
  8408. else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
  8409. rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
  8410. content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
  8411. }
  8412. return new CssRule(selector, content);
  8413. });
  8414. };
  8415. ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
  8416. var _this = this;
  8417. return selector.split(',')
  8418. .map(function (part) { return part.trim().split(_shadowDeepSelectors); })
  8419. .map(function (deepParts) {
  8420. var _a = __read(deepParts), shallowPart = _a[0], otherParts = _a.slice(1);
  8421. var applyScope = function (shallowPart) {
  8422. if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) {
  8423. return strict ?
  8424. _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
  8425. _this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
  8426. }
  8427. else {
  8428. return shallowPart;
  8429. }
  8430. };
  8431. return __spread([applyScope(shallowPart)], otherParts).join(' ');
  8432. })
  8433. .join(', ');
  8434. };
  8435. ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
  8436. var re = this._makeScopeMatcher(scopeSelector);
  8437. return !re.test(selector);
  8438. };
  8439. ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
  8440. var lre = /\[/g;
  8441. var rre = /\]/g;
  8442. scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
  8443. return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
  8444. };
  8445. ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
  8446. // Difference from webcomponents.js: scopeSelector could not be an array
  8447. return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
  8448. };
  8449. // scope via name and [is=name]
  8450. ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
  8451. // In Android browser, the lastIndex is not reset when the regex is used in String.replace()
  8452. _polyfillHostRe.lastIndex = 0;
  8453. if (_polyfillHostRe.test(selector)) {
  8454. var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
  8455. return selector
  8456. .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) {
  8457. return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) {
  8458. return before + replaceBy_1 + colon + after;
  8459. });
  8460. })
  8461. .replace(_polyfillHostRe, replaceBy_1 + ' ');
  8462. }
  8463. return scopeSelector + ' ' + selector;
  8464. };
  8465. // return a selector with [name] suffix on each simple selector
  8466. // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
  8467. ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) {
  8468. var _this = this;
  8469. var isRe = /\[is=([^\]]*)\]/g;
  8470. scopeSelector = scopeSelector.replace(isRe, function (_) {
  8471. var parts = [];
  8472. for (var _i = 1; _i < arguments.length; _i++) {
  8473. parts[_i - 1] = arguments[_i];
  8474. }
  8475. return parts[0];
  8476. });
  8477. var attrName = '[' + scopeSelector + ']';
  8478. var _scopeSelectorPart = function (p) {
  8479. var scopedP = p.trim();
  8480. if (!scopedP) {
  8481. return '';
  8482. }
  8483. if (p.indexOf(_polyfillHostNoCombinator) > -1) {
  8484. scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
  8485. }
  8486. else {
  8487. // remove :host since it should be unnecessary
  8488. var t = p.replace(_polyfillHostRe, '');
  8489. if (t.length > 0) {
  8490. var matches = t.match(/([^:]*)(:*)(.*)/);
  8491. if (matches) {
  8492. scopedP = matches[1] + attrName + matches[2] + matches[3];
  8493. }
  8494. }
  8495. }
  8496. return scopedP;
  8497. };
  8498. var safeContent = new SafeSelector(selector);
  8499. selector = safeContent.content();
  8500. var scopedSelector = '';
  8501. var startIndex = 0;
  8502. var res;
  8503. var sep = /( |>|\+|~(?!=))\s*/g;
  8504. // If a selector appears before :host it should not be shimmed as it
  8505. // matches on ancestor elements and not on elements in the host's shadow
  8506. // `:host-context(div)` is transformed to
  8507. // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
  8508. // the `div` is not part of the component in the 2nd selectors and should not be scoped.
  8509. // Historically `component-tag:host` was matching the component so we also want to preserve
  8510. // this behavior to avoid breaking legacy apps (it should not match).
  8511. // The behavior should be:
  8512. // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
  8513. // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
  8514. // `:host-context(tag)`)
  8515. var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
  8516. // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
  8517. var shouldScope = !hasHost;
  8518. while ((res = sep.exec(selector)) !== null) {
  8519. var separator = res[1];
  8520. var part_1 = selector.slice(startIndex, res.index).trim();
  8521. shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1;
  8522. var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1;
  8523. scopedSelector += scopedPart + " " + separator + " ";
  8524. startIndex = sep.lastIndex;
  8525. }
  8526. var part = selector.substring(startIndex);
  8527. shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
  8528. scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
  8529. // replace the placeholders with their original values
  8530. return safeContent.restore(scopedSelector);
  8531. };
  8532. ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
  8533. return selector.replace(_colonHostContextRe, _polyfillHostContext)
  8534. .replace(_colonHostRe, _polyfillHost);
  8535. };
  8536. return ShadowCss;
  8537. }());
  8538. var SafeSelector = /** @class */ (function () {
  8539. function SafeSelector(selector) {
  8540. var _this = this;
  8541. this.placeholders = [];
  8542. this.index = 0;
  8543. // Replaces attribute selectors with placeholders.
  8544. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
  8545. selector = selector.replace(/(\[[^\]]*\])/g, function (_, keep) {
  8546. var replaceBy = "__ph-" + _this.index + "__";
  8547. _this.placeholders.push(keep);
  8548. _this.index++;
  8549. return replaceBy;
  8550. });
  8551. // Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
  8552. // WS and "+" would otherwise be interpreted as selector separators.
  8553. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) {
  8554. var replaceBy = "__ph-" + _this.index + "__";
  8555. _this.placeholders.push(exp);
  8556. _this.index++;
  8557. return pseudo + replaceBy;
  8558. });
  8559. }
  8560. SafeSelector.prototype.restore = function (content) {
  8561. var _this = this;
  8562. return content.replace(/__ph-(\d+)__/g, function (ph, index) { return _this.placeholders[+index]; });
  8563. };
  8564. SafeSelector.prototype.content = function () { return this._content; };
  8565. return SafeSelector;
  8566. }());
  8567. var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
  8568. var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8569. var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8570. var _polyfillHost = '-shadowcsshost';
  8571. // note: :host-context pre-processed to -shadowcsshostcontext.
  8572. var _polyfillHostContext = '-shadowcsscontext';
  8573. var _parenSuffix = ')(?:\\((' +
  8574. '(?:\\([^)(]*\\)|[^)(]*)+?' +
  8575. ')\\))?([^,{]*)';
  8576. var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
  8577. var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
  8578. var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
  8579. var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
  8580. var _shadowDOMSelectorsRe = [
  8581. /::shadow/g,
  8582. /::content/g,
  8583. // Deprecated selectors
  8584. /\/shadow-deep\//g,
  8585. /\/shadow\//g,
  8586. ];
  8587. // The deep combinator is deprecated in the CSS spec
  8588. // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
  8589. // see https://github.com/angular/angular/pull/17677
  8590. var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
  8591. var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
  8592. var _polyfillHostRe = /-shadowcsshost/gim;
  8593. var _colonHostRe = /:host/gim;
  8594. var _colonHostContextRe = /:host-context/gim;
  8595. var _commentRe = /\/\*\s*[\s\S]*?\*\//g;
  8596. function stripComments(input) {
  8597. return input.replace(_commentRe, '');
  8598. }
  8599. var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
  8600. function extractCommentsWithHash(input) {
  8601. return input.match(_commentWithHashRe) || [];
  8602. }
  8603. var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
  8604. var _curlyRe = /([{}])/g;
  8605. var OPEN_CURLY = '{';
  8606. var CLOSE_CURLY = '}';
  8607. var BLOCK_PLACEHOLDER = '%BLOCK%';
  8608. var CssRule = /** @class */ (function () {
  8609. function CssRule(selector, content) {
  8610. this.selector = selector;
  8611. this.content = content;
  8612. }
  8613. return CssRule;
  8614. }());
  8615. function processRules(input, ruleCallback) {
  8616. var inputWithEscapedBlocks = escapeBlocks(input);
  8617. var nextBlockIndex = 0;
  8618. return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () {
  8619. var m = [];
  8620. for (var _i = 0; _i < arguments.length; _i++) {
  8621. m[_i] = arguments[_i];
  8622. }
  8623. var selector = m[2];
  8624. var content = '';
  8625. var suffix = m[4];
  8626. var contentPrefix = '';
  8627. if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
  8628. content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
  8629. suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
  8630. contentPrefix = '{';
  8631. }
  8632. var rule = ruleCallback(new CssRule(selector, content));
  8633. return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
  8634. });
  8635. }
  8636. var StringWithEscapedBlocks = /** @class */ (function () {
  8637. function StringWithEscapedBlocks(escapedString, blocks) {
  8638. this.escapedString = escapedString;
  8639. this.blocks = blocks;
  8640. }
  8641. return StringWithEscapedBlocks;
  8642. }());
  8643. function escapeBlocks(input) {
  8644. var inputParts = input.split(_curlyRe);
  8645. var resultParts = [];
  8646. var escapedBlocks = [];
  8647. var bracketCount = 0;
  8648. var currentBlockParts = [];
  8649. for (var partIndex = 0; partIndex < inputParts.length; partIndex++) {
  8650. var part = inputParts[partIndex];
  8651. if (part == CLOSE_CURLY) {
  8652. bracketCount--;
  8653. }
  8654. if (bracketCount > 0) {
  8655. currentBlockParts.push(part);
  8656. }
  8657. else {
  8658. if (currentBlockParts.length > 0) {
  8659. escapedBlocks.push(currentBlockParts.join(''));
  8660. resultParts.push(BLOCK_PLACEHOLDER);
  8661. currentBlockParts = [];
  8662. }
  8663. resultParts.push(part);
  8664. }
  8665. if (part == OPEN_CURLY) {
  8666. bracketCount++;
  8667. }
  8668. }
  8669. if (currentBlockParts.length > 0) {
  8670. escapedBlocks.push(currentBlockParts.join(''));
  8671. resultParts.push(BLOCK_PLACEHOLDER);
  8672. }
  8673. return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
  8674. }
  8675. /**
  8676. * @license
  8677. * Copyright Google Inc. All Rights Reserved.
  8678. *
  8679. * Use of this source code is governed by an MIT-style license that can be
  8680. * found in the LICENSE file at https://angular.io/license
  8681. */
  8682. var COMPONENT_VARIABLE = '%COMP%';
  8683. var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
  8684. var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
  8685. /**
  8686. * @license
  8687. * Copyright Google Inc. All Rights Reserved.
  8688. *
  8689. * Use of this source code is governed by an MIT-style license that can be
  8690. * found in the LICENSE file at https://angular.io/license
  8691. */
  8692. /**
  8693. * A path is an ordered set of elements. Typically a path is to a
  8694. * particular offset in a source file. The head of the list is the top
  8695. * most node. The tail is the node that contains the offset directly.
  8696. *
  8697. * For example, the expression `a + b + c` might have an ast that looks
  8698. * like:
  8699. * +
  8700. * / \
  8701. * a +
  8702. * / \
  8703. * b c
  8704. *
  8705. * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
  8706. * 'c' at 9-10]` and the path the node at offset 1 would be
  8707. * `['+' at 1-10, 'a' at 1-2]`.
  8708. */
  8709. var AstPath = /** @class */ (function () {
  8710. function AstPath(path, position) {
  8711. if (position === void 0) { position = -1; }
  8712. this.path = path;
  8713. this.position = position;
  8714. }
  8715. Object.defineProperty(AstPath.prototype, "empty", {
  8716. get: function () { return !this.path || !this.path.length; },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Object.defineProperty(AstPath.prototype, "head", {
  8721. get: function () { return this.path[0]; },
  8722. enumerable: true,
  8723. configurable: true
  8724. });
  8725. Object.defineProperty(AstPath.prototype, "tail", {
  8726. get: function () { return this.path[this.path.length - 1]; },
  8727. enumerable: true,
  8728. configurable: true
  8729. });
  8730. AstPath.prototype.parentOf = function (node) {
  8731. return node && this.path[this.path.indexOf(node) - 1];
  8732. };
  8733. AstPath.prototype.childOf = function (node) { return this.path[this.path.indexOf(node) + 1]; };
  8734. AstPath.prototype.first = function (ctor) {
  8735. for (var i = this.path.length - 1; i >= 0; i--) {
  8736. var item = this.path[i];
  8737. if (item instanceof ctor)
  8738. return item;
  8739. }
  8740. };
  8741. AstPath.prototype.push = function (node) { this.path.push(node); };
  8742. AstPath.prototype.pop = function () { return this.path.pop(); };
  8743. return AstPath;
  8744. }());
  8745. /**
  8746. * @license
  8747. * Copyright Google Inc. All Rights Reserved.
  8748. *
  8749. * Use of this source code is governed by an MIT-style license that can be
  8750. * found in the LICENSE file at https://angular.io/license
  8751. */
  8752. var Text$3 = /** @class */ (function () {
  8753. function Text(value, sourceSpan, i18n) {
  8754. this.value = value;
  8755. this.sourceSpan = sourceSpan;
  8756. this.i18n = i18n;
  8757. }
  8758. Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  8759. return Text;
  8760. }());
  8761. var Expansion = /** @class */ (function () {
  8762. function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
  8763. this.switchValue = switchValue;
  8764. this.type = type;
  8765. this.cases = cases;
  8766. this.sourceSpan = sourceSpan;
  8767. this.switchValueSourceSpan = switchValueSourceSpan;
  8768. this.i18n = i18n;
  8769. }
  8770. Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); };
  8771. return Expansion;
  8772. }());
  8773. var ExpansionCase = /** @class */ (function () {
  8774. function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
  8775. this.value = value;
  8776. this.expression = expression;
  8777. this.sourceSpan = sourceSpan;
  8778. this.valueSourceSpan = valueSourceSpan;
  8779. this.expSourceSpan = expSourceSpan;
  8780. }
  8781. ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); };
  8782. return ExpansionCase;
  8783. }());
  8784. var Attribute = /** @class */ (function () {
  8785. function Attribute(name, value, sourceSpan, valueSpan, i18n) {
  8786. this.name = name;
  8787. this.value = value;
  8788. this.sourceSpan = sourceSpan;
  8789. this.valueSpan = valueSpan;
  8790. this.i18n = i18n;
  8791. }
  8792. Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); };
  8793. return Attribute;
  8794. }());
  8795. var Element$1 = /** @class */ (function () {
  8796. function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  8797. if (startSourceSpan === void 0) { startSourceSpan = null; }
  8798. if (endSourceSpan === void 0) { endSourceSpan = null; }
  8799. this.name = name;
  8800. this.attrs = attrs;
  8801. this.children = children;
  8802. this.sourceSpan = sourceSpan;
  8803. this.startSourceSpan = startSourceSpan;
  8804. this.endSourceSpan = endSourceSpan;
  8805. this.i18n = i18n;
  8806. }
  8807. Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); };
  8808. return Element;
  8809. }());
  8810. var Comment = /** @class */ (function () {
  8811. function Comment(value, sourceSpan) {
  8812. this.value = value;
  8813. this.sourceSpan = sourceSpan;
  8814. }
  8815. Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); };
  8816. return Comment;
  8817. }());
  8818. function visitAll$1(visitor, nodes, context) {
  8819. if (context === void 0) { context = null; }
  8820. var result = [];
  8821. var visit = visitor.visit ?
  8822. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  8823. function (ast) { return ast.visit(visitor, context); };
  8824. nodes.forEach(function (ast) {
  8825. var astResult = visit(ast);
  8826. if (astResult) {
  8827. result.push(astResult);
  8828. }
  8829. });
  8830. return result;
  8831. }
  8832. var RecursiveVisitor = /** @class */ (function () {
  8833. function RecursiveVisitor() {
  8834. }
  8835. RecursiveVisitor.prototype.visitElement = function (ast, context) {
  8836. this.visitChildren(context, function (visit) {
  8837. visit(ast.attrs);
  8838. visit(ast.children);
  8839. });
  8840. };
  8841. RecursiveVisitor.prototype.visitAttribute = function (ast, context) { };
  8842. RecursiveVisitor.prototype.visitText = function (ast, context) { };
  8843. RecursiveVisitor.prototype.visitComment = function (ast, context) { };
  8844. RecursiveVisitor.prototype.visitExpansion = function (ast, context) {
  8845. return this.visitChildren(context, function (visit) { visit(ast.cases); });
  8846. };
  8847. RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { };
  8848. RecursiveVisitor.prototype.visitChildren = function (context, cb) {
  8849. var results = [];
  8850. var t = this;
  8851. function visit(children) {
  8852. if (children)
  8853. results.push(visitAll$1(t, children, context));
  8854. }
  8855. cb(visit);
  8856. return [].concat.apply([], results);
  8857. };
  8858. return RecursiveVisitor;
  8859. }());
  8860. function spanOf(ast) {
  8861. var start = ast.sourceSpan.start.offset;
  8862. var end = ast.sourceSpan.end.offset;
  8863. if (ast instanceof Element$1) {
  8864. if (ast.endSourceSpan) {
  8865. end = ast.endSourceSpan.end.offset;
  8866. }
  8867. else if (ast.children && ast.children.length) {
  8868. end = spanOf(ast.children[ast.children.length - 1]).end;
  8869. }
  8870. }
  8871. return { start: start, end: end };
  8872. }
  8873. function findNode(nodes, position) {
  8874. var path = [];
  8875. var visitor = new /** @class */ (function (_super) {
  8876. __extends(class_1, _super);
  8877. function class_1() {
  8878. return _super !== null && _super.apply(this, arguments) || this;
  8879. }
  8880. class_1.prototype.visit = function (ast, context) {
  8881. var span = spanOf(ast);
  8882. if (span.start <= position && position < span.end) {
  8883. path.push(ast);
  8884. }
  8885. else {
  8886. // Returning a value here will result in the children being skipped.
  8887. return true;
  8888. }
  8889. };
  8890. return class_1;
  8891. }(RecursiveVisitor));
  8892. visitAll$1(visitor, nodes);
  8893. return new AstPath(path, position);
  8894. }
  8895. /**
  8896. * @license
  8897. * Copyright Google Inc. All Rights Reserved.
  8898. *
  8899. * Use of this source code is governed by an MIT-style license that can be
  8900. * found in the LICENSE file at https://angular.io/license
  8901. */
  8902. var TokenType;
  8903. (function (TokenType) {
  8904. TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
  8905. TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
  8906. TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
  8907. TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
  8908. TokenType[TokenType["TEXT"] = 4] = "TEXT";
  8909. TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT";
  8910. TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT";
  8911. TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START";
  8912. TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END";
  8913. TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START";
  8914. TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END";
  8915. TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME";
  8916. TokenType[TokenType["ATTR_QUOTE"] = 12] = "ATTR_QUOTE";
  8917. TokenType[TokenType["ATTR_VALUE"] = 13] = "ATTR_VALUE";
  8918. TokenType[TokenType["DOC_TYPE"] = 14] = "DOC_TYPE";
  8919. TokenType[TokenType["EXPANSION_FORM_START"] = 15] = "EXPANSION_FORM_START";
  8920. TokenType[TokenType["EXPANSION_CASE_VALUE"] = 16] = "EXPANSION_CASE_VALUE";
  8921. TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 17] = "EXPANSION_CASE_EXP_START";
  8922. TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 18] = "EXPANSION_CASE_EXP_END";
  8923. TokenType[TokenType["EXPANSION_FORM_END"] = 19] = "EXPANSION_FORM_END";
  8924. TokenType[TokenType["EOF"] = 20] = "EOF";
  8925. })(TokenType || (TokenType = {}));
  8926. var Token = /** @class */ (function () {
  8927. function Token(type, parts, sourceSpan) {
  8928. this.type = type;
  8929. this.parts = parts;
  8930. this.sourceSpan = sourceSpan;
  8931. }
  8932. return Token;
  8933. }());
  8934. var TokenError = /** @class */ (function (_super) {
  8935. __extends(TokenError, _super);
  8936. function TokenError(errorMsg, tokenType, span) {
  8937. var _this = _super.call(this, span, errorMsg) || this;
  8938. _this.tokenType = tokenType;
  8939. return _this;
  8940. }
  8941. return TokenError;
  8942. }(ParseError));
  8943. var TokenizeResult = /** @class */ (function () {
  8944. function TokenizeResult(tokens, errors) {
  8945. this.tokens = tokens;
  8946. this.errors = errors;
  8947. }
  8948. return TokenizeResult;
  8949. }());
  8950. function tokenize(source, url, getTagDefinition, options) {
  8951. if (options === void 0) { options = {}; }
  8952. return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options).tokenize();
  8953. }
  8954. var _CR_OR_CRLF_REGEXP = /\r\n?/g;
  8955. function _unexpectedCharacterErrorMsg(charCode) {
  8956. var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
  8957. return "Unexpected character \"" + char + "\"";
  8958. }
  8959. function _unknownEntityErrorMsg(entitySrc) {
  8960. return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
  8961. }
  8962. var _ControlFlowError = /** @class */ (function () {
  8963. function _ControlFlowError(error) {
  8964. this.error = error;
  8965. }
  8966. return _ControlFlowError;
  8967. }());
  8968. // See http://www.w3.org/TR/html51/syntax.html#writing
  8969. var _Tokenizer = /** @class */ (function () {
  8970. /**
  8971. * @param _file The html source file being tokenized.
  8972. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
  8973. * @param options Configuration of the tokenization.
  8974. */
  8975. function _Tokenizer(_file, _getTagDefinition, options) {
  8976. this._getTagDefinition = _getTagDefinition;
  8977. this._currentTokenStart = null;
  8978. this._currentTokenType = null;
  8979. this._expansionCaseStack = [];
  8980. this._inInterpolation = false;
  8981. this.tokens = [];
  8982. this.errors = [];
  8983. this._tokenizeIcu = options.tokenizeExpansionForms || false;
  8984. this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  8985. this._leadingTriviaCodePoints =
  8986. options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; });
  8987. var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
  8988. this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
  8989. new PlainCharacterCursor(_file, range);
  8990. try {
  8991. this._cursor.init();
  8992. }
  8993. catch (e) {
  8994. this.handleError(e);
  8995. }
  8996. }
  8997. _Tokenizer.prototype._processCarriageReturns = function (content) {
  8998. // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
  8999. // In order to keep the original position in the source, we can not
  9000. // pre-process it.
  9001. // Instead CRs are processed right before instantiating the tokens.
  9002. return content.replace(_CR_OR_CRLF_REGEXP, '\n');
  9003. };
  9004. _Tokenizer.prototype.tokenize = function () {
  9005. while (this._cursor.peek() !== $EOF) {
  9006. var start = this._cursor.clone();
  9007. try {
  9008. if (this._attemptCharCode($LT)) {
  9009. if (this._attemptCharCode($BANG)) {
  9010. if (this._attemptCharCode($LBRACKET)) {
  9011. this._consumeCdata(start);
  9012. }
  9013. else if (this._attemptCharCode($MINUS)) {
  9014. this._consumeComment(start);
  9015. }
  9016. else {
  9017. this._consumeDocType(start);
  9018. }
  9019. }
  9020. else if (this._attemptCharCode($SLASH)) {
  9021. this._consumeTagClose(start);
  9022. }
  9023. else {
  9024. this._consumeTagOpen(start);
  9025. }
  9026. }
  9027. else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
  9028. this._consumeText();
  9029. }
  9030. }
  9031. catch (e) {
  9032. this.handleError(e);
  9033. }
  9034. }
  9035. this._beginToken(TokenType.EOF);
  9036. this._endToken([]);
  9037. return new TokenizeResult(mergeTextTokens(this.tokens), this.errors);
  9038. };
  9039. /**
  9040. * @returns whether an ICU token has been created
  9041. * @internal
  9042. */
  9043. _Tokenizer.prototype._tokenizeExpansionForm = function () {
  9044. if (this.isExpansionFormStart()) {
  9045. this._consumeExpansionFormStart();
  9046. return true;
  9047. }
  9048. if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
  9049. this._consumeExpansionCaseStart();
  9050. return true;
  9051. }
  9052. if (this._cursor.peek() === $RBRACE) {
  9053. if (this._isInExpansionCase()) {
  9054. this._consumeExpansionCaseEnd();
  9055. return true;
  9056. }
  9057. if (this._isInExpansionForm()) {
  9058. this._consumeExpansionFormEnd();
  9059. return true;
  9060. }
  9061. }
  9062. return false;
  9063. };
  9064. _Tokenizer.prototype._beginToken = function (type, start) {
  9065. if (start === void 0) { start = this._cursor.clone(); }
  9066. this._currentTokenStart = start;
  9067. this._currentTokenType = type;
  9068. };
  9069. _Tokenizer.prototype._endToken = function (parts, end) {
  9070. if (end === void 0) { end = this._cursor.clone(); }
  9071. if (this._currentTokenStart === null) {
  9072. throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
  9073. }
  9074. if (this._currentTokenType === null) {
  9075. throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
  9076. }
  9077. var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
  9078. this.tokens.push(token);
  9079. this._currentTokenStart = null;
  9080. this._currentTokenType = null;
  9081. return token;
  9082. };
  9083. _Tokenizer.prototype._createError = function (msg, span) {
  9084. if (this._isInExpansionForm()) {
  9085. msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)";
  9086. }
  9087. var error = new TokenError(msg, this._currentTokenType, span);
  9088. this._currentTokenStart = null;
  9089. this._currentTokenType = null;
  9090. return new _ControlFlowError(error);
  9091. };
  9092. _Tokenizer.prototype.handleError = function (e) {
  9093. if (e instanceof CursorError) {
  9094. e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
  9095. }
  9096. if (e instanceof _ControlFlowError) {
  9097. this.errors.push(e.error);
  9098. }
  9099. else {
  9100. throw e;
  9101. }
  9102. };
  9103. _Tokenizer.prototype._attemptCharCode = function (charCode) {
  9104. if (this._cursor.peek() === charCode) {
  9105. this._cursor.advance();
  9106. return true;
  9107. }
  9108. return false;
  9109. };
  9110. _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) {
  9111. if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
  9112. this._cursor.advance();
  9113. return true;
  9114. }
  9115. return false;
  9116. };
  9117. _Tokenizer.prototype._requireCharCode = function (charCode) {
  9118. var location = this._cursor.clone();
  9119. if (!this._attemptCharCode(charCode)) {
  9120. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  9121. }
  9122. };
  9123. _Tokenizer.prototype._attemptStr = function (chars) {
  9124. var len = chars.length;
  9125. if (this._cursor.charsLeft() < len) {
  9126. return false;
  9127. }
  9128. var initialPosition = this._cursor.clone();
  9129. for (var i = 0; i < len; i++) {
  9130. if (!this._attemptCharCode(chars.charCodeAt(i))) {
  9131. // If attempting to parse the string fails, we want to reset the parser
  9132. // to where it was before the attempt
  9133. this._cursor = initialPosition;
  9134. return false;
  9135. }
  9136. }
  9137. return true;
  9138. };
  9139. _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) {
  9140. for (var i = 0; i < chars.length; i++) {
  9141. if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
  9142. return false;
  9143. }
  9144. }
  9145. return true;
  9146. };
  9147. _Tokenizer.prototype._requireStr = function (chars) {
  9148. var location = this._cursor.clone();
  9149. if (!this._attemptStr(chars)) {
  9150. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  9151. }
  9152. };
  9153. _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) {
  9154. while (!predicate(this._cursor.peek())) {
  9155. this._cursor.advance();
  9156. }
  9157. };
  9158. _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) {
  9159. var start = this._cursor.clone();
  9160. this._attemptCharCodeUntilFn(predicate);
  9161. var end = this._cursor.clone();
  9162. if (end.diff(start) < len) {
  9163. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  9164. }
  9165. };
  9166. _Tokenizer.prototype._attemptUntilChar = function (char) {
  9167. while (this._cursor.peek() !== char) {
  9168. this._cursor.advance();
  9169. }
  9170. };
  9171. _Tokenizer.prototype._readChar = function (decodeEntities) {
  9172. if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
  9173. return this._decodeEntity();
  9174. }
  9175. else {
  9176. // Don't rely upon reading directly from `_input` as the actual char value
  9177. // may have been generated from an escape sequence.
  9178. var char = String.fromCodePoint(this._cursor.peek());
  9179. this._cursor.advance();
  9180. return char;
  9181. }
  9182. };
  9183. _Tokenizer.prototype._decodeEntity = function () {
  9184. var start = this._cursor.clone();
  9185. this._cursor.advance();
  9186. if (this._attemptCharCode($HASH)) {
  9187. var isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
  9188. var codeStart = this._cursor.clone();
  9189. this._attemptCharCodeUntilFn(isDigitEntityEnd);
  9190. if (this._cursor.peek() != $SEMICOLON) {
  9191. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan());
  9192. }
  9193. var strNum = this._cursor.getChars(codeStart);
  9194. this._cursor.advance();
  9195. try {
  9196. var charCode = parseInt(strNum, isHex ? 16 : 10);
  9197. return String.fromCharCode(charCode);
  9198. }
  9199. catch (_a) {
  9200. throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
  9201. }
  9202. }
  9203. else {
  9204. var nameStart = this._cursor.clone();
  9205. this._attemptCharCodeUntilFn(isNamedEntityEnd);
  9206. if (this._cursor.peek() != $SEMICOLON) {
  9207. this._cursor = nameStart;
  9208. return '&';
  9209. }
  9210. var name_1 = this._cursor.getChars(nameStart);
  9211. this._cursor.advance();
  9212. var char = NAMED_ENTITIES[name_1];
  9213. if (!char) {
  9214. throw this._createError(_unknownEntityErrorMsg(name_1), this._cursor.getSpan(start));
  9215. }
  9216. return char;
  9217. }
  9218. };
  9219. _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) {
  9220. this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
  9221. var parts = [];
  9222. while (true) {
  9223. var tagCloseStart = this._cursor.clone();
  9224. var foundEndMarker = endMarkerPredicate();
  9225. this._cursor = tagCloseStart;
  9226. if (foundEndMarker) {
  9227. break;
  9228. }
  9229. parts.push(this._readChar(decodeEntities));
  9230. }
  9231. return this._endToken([this._processCarriageReturns(parts.join(''))]);
  9232. };
  9233. _Tokenizer.prototype._consumeComment = function (start) {
  9234. var _this = this;
  9235. this._beginToken(TokenType.COMMENT_START, start);
  9236. this._requireCharCode($MINUS);
  9237. this._endToken([]);
  9238. this._consumeRawText(false, function () { return _this._attemptStr('-->'); });
  9239. this._beginToken(TokenType.COMMENT_END);
  9240. this._requireStr('-->');
  9241. this._endToken([]);
  9242. };
  9243. _Tokenizer.prototype._consumeCdata = function (start) {
  9244. var _this = this;
  9245. this._beginToken(TokenType.CDATA_START, start);
  9246. this._requireStr('CDATA[');
  9247. this._endToken([]);
  9248. this._consumeRawText(false, function () { return _this._attemptStr(']]>'); });
  9249. this._beginToken(TokenType.CDATA_END);
  9250. this._requireStr(']]>');
  9251. this._endToken([]);
  9252. };
  9253. _Tokenizer.prototype._consumeDocType = function (start) {
  9254. this._beginToken(TokenType.DOC_TYPE, start);
  9255. var contentStart = this._cursor.clone();
  9256. this._attemptUntilChar($GT);
  9257. var content = this._cursor.getChars(contentStart);
  9258. this._cursor.advance();
  9259. this._endToken([content]);
  9260. };
  9261. _Tokenizer.prototype._consumePrefixAndName = function () {
  9262. var nameOrPrefixStart = this._cursor.clone();
  9263. var prefix = '';
  9264. while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
  9265. this._cursor.advance();
  9266. }
  9267. var nameStart;
  9268. if (this._cursor.peek() === $COLON) {
  9269. prefix = this._cursor.getChars(nameOrPrefixStart);
  9270. this._cursor.advance();
  9271. nameStart = this._cursor.clone();
  9272. }
  9273. else {
  9274. nameStart = nameOrPrefixStart;
  9275. }
  9276. this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
  9277. var name = this._cursor.getChars(nameStart);
  9278. return [prefix, name];
  9279. };
  9280. _Tokenizer.prototype._consumeTagOpen = function (start) {
  9281. var tagName;
  9282. var prefix;
  9283. var openTagToken;
  9284. var tokensBeforeTagOpen = this.tokens.length;
  9285. var innerStart = this._cursor.clone();
  9286. try {
  9287. if (!isAsciiLetter(this._cursor.peek())) {
  9288. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  9289. }
  9290. openTagToken = this._consumeTagOpenStart(start);
  9291. prefix = openTagToken.parts[0];
  9292. tagName = openTagToken.parts[1];
  9293. this._attemptCharCodeUntilFn(isNotWhitespace);
  9294. while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT) {
  9295. this._consumeAttributeName();
  9296. this._attemptCharCodeUntilFn(isNotWhitespace);
  9297. if (this._attemptCharCode($EQ)) {
  9298. this._attemptCharCodeUntilFn(isNotWhitespace);
  9299. this._consumeAttributeValue();
  9300. }
  9301. this._attemptCharCodeUntilFn(isNotWhitespace);
  9302. }
  9303. this._consumeTagOpenEnd();
  9304. }
  9305. catch (e) {
  9306. if (e instanceof _ControlFlowError) {
  9307. // When the start tag is invalid (including invalid "attributes"), assume we want a "<"
  9308. this._cursor = innerStart;
  9309. if (openTagToken) {
  9310. this.tokens.length = tokensBeforeTagOpen;
  9311. }
  9312. // Back to back text tokens are merged at the end
  9313. this._beginToken(TokenType.TEXT, start);
  9314. this._endToken(['<']);
  9315. return;
  9316. }
  9317. throw e;
  9318. }
  9319. var contentTokenType = this._getTagDefinition(tagName).contentType;
  9320. if (contentTokenType === TagContentType.RAW_TEXT) {
  9321. this._consumeRawTextWithTagClose(prefix, tagName, false);
  9322. }
  9323. else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
  9324. this._consumeRawTextWithTagClose(prefix, tagName, true);
  9325. }
  9326. };
  9327. _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) {
  9328. var _this = this;
  9329. var textToken = this._consumeRawText(decodeEntities, function () {
  9330. if (!_this._attemptCharCode($LT))
  9331. return false;
  9332. if (!_this._attemptCharCode($SLASH))
  9333. return false;
  9334. _this._attemptCharCodeUntilFn(isNotWhitespace);
  9335. if (!_this._attemptStrCaseInsensitive(tagName))
  9336. return false;
  9337. _this._attemptCharCodeUntilFn(isNotWhitespace);
  9338. return _this._attemptCharCode($GT);
  9339. });
  9340. this._beginToken(TokenType.TAG_CLOSE);
  9341. this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3);
  9342. this._cursor.advance(); // Consume the `>`
  9343. this._endToken([prefix, tagName]);
  9344. };
  9345. _Tokenizer.prototype._consumeTagOpenStart = function (start) {
  9346. this._beginToken(TokenType.TAG_OPEN_START, start);
  9347. var parts = this._consumePrefixAndName();
  9348. return this._endToken(parts);
  9349. };
  9350. _Tokenizer.prototype._consumeAttributeName = function () {
  9351. var attrNameStart = this._cursor.peek();
  9352. if (attrNameStart === $SQ || attrNameStart === $DQ) {
  9353. throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
  9354. }
  9355. this._beginToken(TokenType.ATTR_NAME);
  9356. var prefixAndName = this._consumePrefixAndName();
  9357. this._endToken(prefixAndName);
  9358. };
  9359. _Tokenizer.prototype._consumeAttributeValue = function () {
  9360. var value;
  9361. if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
  9362. this._beginToken(TokenType.ATTR_QUOTE);
  9363. var quoteChar = this._cursor.peek();
  9364. this._cursor.advance();
  9365. this._endToken([String.fromCodePoint(quoteChar)]);
  9366. this._beginToken(TokenType.ATTR_VALUE);
  9367. var parts = [];
  9368. while (this._cursor.peek() !== quoteChar) {
  9369. parts.push(this._readChar(true));
  9370. }
  9371. value = parts.join('');
  9372. this._endToken([this._processCarriageReturns(value)]);
  9373. this._beginToken(TokenType.ATTR_QUOTE);
  9374. this._cursor.advance();
  9375. this._endToken([String.fromCodePoint(quoteChar)]);
  9376. }
  9377. else {
  9378. this._beginToken(TokenType.ATTR_VALUE);
  9379. var valueStart = this._cursor.clone();
  9380. this._requireCharCodeUntilFn(isNameEnd, 1);
  9381. value = this._cursor.getChars(valueStart);
  9382. this._endToken([this._processCarriageReturns(value)]);
  9383. }
  9384. };
  9385. _Tokenizer.prototype._consumeTagOpenEnd = function () {
  9386. var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
  9387. this._beginToken(tokenType);
  9388. this._requireCharCode($GT);
  9389. this._endToken([]);
  9390. };
  9391. _Tokenizer.prototype._consumeTagClose = function (start) {
  9392. this._beginToken(TokenType.TAG_CLOSE, start);
  9393. this._attemptCharCodeUntilFn(isNotWhitespace);
  9394. var prefixAndName = this._consumePrefixAndName();
  9395. this._attemptCharCodeUntilFn(isNotWhitespace);
  9396. this._requireCharCode($GT);
  9397. this._endToken(prefixAndName);
  9398. };
  9399. _Tokenizer.prototype._consumeExpansionFormStart = function () {
  9400. this._beginToken(TokenType.EXPANSION_FORM_START);
  9401. this._requireCharCode($LBRACE);
  9402. this._endToken([]);
  9403. this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
  9404. this._beginToken(TokenType.RAW_TEXT);
  9405. var condition = this._readUntil($COMMA);
  9406. this._endToken([condition]);
  9407. this._requireCharCode($COMMA);
  9408. this._attemptCharCodeUntilFn(isNotWhitespace);
  9409. this._beginToken(TokenType.RAW_TEXT);
  9410. var type = this._readUntil($COMMA);
  9411. this._endToken([type]);
  9412. this._requireCharCode($COMMA);
  9413. this._attemptCharCodeUntilFn(isNotWhitespace);
  9414. };
  9415. _Tokenizer.prototype._consumeExpansionCaseStart = function () {
  9416. this._beginToken(TokenType.EXPANSION_CASE_VALUE);
  9417. var value = this._readUntil($LBRACE).trim();
  9418. this._endToken([value]);
  9419. this._attemptCharCodeUntilFn(isNotWhitespace);
  9420. this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
  9421. this._requireCharCode($LBRACE);
  9422. this._endToken([]);
  9423. this._attemptCharCodeUntilFn(isNotWhitespace);
  9424. this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
  9425. };
  9426. _Tokenizer.prototype._consumeExpansionCaseEnd = function () {
  9427. this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
  9428. this._requireCharCode($RBRACE);
  9429. this._endToken([]);
  9430. this._attemptCharCodeUntilFn(isNotWhitespace);
  9431. this._expansionCaseStack.pop();
  9432. };
  9433. _Tokenizer.prototype._consumeExpansionFormEnd = function () {
  9434. this._beginToken(TokenType.EXPANSION_FORM_END);
  9435. this._requireCharCode($RBRACE);
  9436. this._endToken([]);
  9437. this._expansionCaseStack.pop();
  9438. };
  9439. _Tokenizer.prototype._consumeText = function () {
  9440. var start = this._cursor.clone();
  9441. this._beginToken(TokenType.TEXT, start);
  9442. var parts = [];
  9443. do {
  9444. if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
  9445. parts.push(this._interpolationConfig.start);
  9446. this._inInterpolation = true;
  9447. }
  9448. else if (this._interpolationConfig && this._inInterpolation &&
  9449. this._attemptStr(this._interpolationConfig.end)) {
  9450. parts.push(this._interpolationConfig.end);
  9451. this._inInterpolation = false;
  9452. }
  9453. else {
  9454. parts.push(this._readChar(true));
  9455. }
  9456. } while (!this._isTextEnd());
  9457. this._endToken([this._processCarriageReturns(parts.join(''))]);
  9458. };
  9459. _Tokenizer.prototype._isTextEnd = function () {
  9460. if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
  9461. return true;
  9462. }
  9463. if (this._tokenizeIcu && !this._inInterpolation) {
  9464. if (this.isExpansionFormStart()) {
  9465. // start of an expansion form
  9466. return true;
  9467. }
  9468. if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
  9469. // end of and expansion case
  9470. return true;
  9471. }
  9472. }
  9473. return false;
  9474. };
  9475. _Tokenizer.prototype._readUntil = function (char) {
  9476. var start = this._cursor.clone();
  9477. this._attemptUntilChar(char);
  9478. return this._cursor.getChars(start);
  9479. };
  9480. _Tokenizer.prototype._isInExpansionCase = function () {
  9481. return this._expansionCaseStack.length > 0 &&
  9482. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9483. TokenType.EXPANSION_CASE_EXP_START;
  9484. };
  9485. _Tokenizer.prototype._isInExpansionForm = function () {
  9486. return this._expansionCaseStack.length > 0 &&
  9487. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9488. TokenType.EXPANSION_FORM_START;
  9489. };
  9490. _Tokenizer.prototype.isExpansionFormStart = function () {
  9491. if (this._cursor.peek() !== $LBRACE) {
  9492. return false;
  9493. }
  9494. if (this._interpolationConfig) {
  9495. var start = this._cursor.clone();
  9496. var isInterpolation = this._attemptStr(this._interpolationConfig.start);
  9497. this._cursor = start;
  9498. return !isInterpolation;
  9499. }
  9500. return true;
  9501. };
  9502. return _Tokenizer;
  9503. }());
  9504. function isNotWhitespace(code) {
  9505. return !isWhitespace(code) || code === $EOF;
  9506. }
  9507. function isNameEnd(code) {
  9508. return isWhitespace(code) || code === $GT || code === $SLASH ||
  9509. code === $SQ || code === $DQ || code === $EQ;
  9510. }
  9511. function isPrefixEnd(code) {
  9512. return (code < $a || $z < code) && (code < $A || $Z < code) &&
  9513. (code < $0 || code > $9);
  9514. }
  9515. function isDigitEntityEnd(code) {
  9516. return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
  9517. }
  9518. function isNamedEntityEnd(code) {
  9519. return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
  9520. }
  9521. function isExpansionCaseStart(peek) {
  9522. return peek === $EQ || isAsciiLetter(peek) || isDigit(peek);
  9523. }
  9524. function compareCharCodeCaseInsensitive(code1, code2) {
  9525. return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
  9526. }
  9527. function toUpperCaseCharCode(code) {
  9528. return code >= $a && code <= $z ? code - $a + $A : code;
  9529. }
  9530. function mergeTextTokens(srcTokens) {
  9531. var dstTokens = [];
  9532. var lastDstToken = undefined;
  9533. for (var i = 0; i < srcTokens.length; i++) {
  9534. var token = srcTokens[i];
  9535. if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
  9536. lastDstToken.parts[0] += token.parts[0];
  9537. lastDstToken.sourceSpan.end = token.sourceSpan.end;
  9538. }
  9539. else {
  9540. lastDstToken = token;
  9541. dstTokens.push(lastDstToken);
  9542. }
  9543. }
  9544. return dstTokens;
  9545. }
  9546. var PlainCharacterCursor = /** @class */ (function () {
  9547. function PlainCharacterCursor(fileOrCursor, range) {
  9548. if (fileOrCursor instanceof PlainCharacterCursor) {
  9549. this.file = fileOrCursor.file;
  9550. this.input = fileOrCursor.input;
  9551. this.end = fileOrCursor.end;
  9552. this.state = __assign({}, fileOrCursor.state);
  9553. }
  9554. else {
  9555. if (!range) {
  9556. throw new Error('Programming error: the range argument must be provided with a file argument.');
  9557. }
  9558. this.file = fileOrCursor;
  9559. this.input = fileOrCursor.content;
  9560. this.end = range.endPos;
  9561. this.state = {
  9562. peek: -1,
  9563. offset: range.startPos,
  9564. line: range.startLine,
  9565. column: range.startCol,
  9566. };
  9567. }
  9568. }
  9569. PlainCharacterCursor.prototype.clone = function () { return new PlainCharacterCursor(this); };
  9570. PlainCharacterCursor.prototype.peek = function () { return this.state.peek; };
  9571. PlainCharacterCursor.prototype.charsLeft = function () { return this.end - this.state.offset; };
  9572. PlainCharacterCursor.prototype.diff = function (other) { return this.state.offset - other.state.offset; };
  9573. PlainCharacterCursor.prototype.advance = function () { this.advanceState(this.state); };
  9574. PlainCharacterCursor.prototype.init = function () { this.updatePeek(this.state); };
  9575. PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) {
  9576. start = start || this;
  9577. if (leadingTriviaCodePoints) {
  9578. start = start.clone();
  9579. while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
  9580. start.advance();
  9581. }
  9582. }
  9583. return new ParseSourceSpan(new ParseLocation(start.file, start.state.offset, start.state.line, start.state.column), new ParseLocation(this.file, this.state.offset, this.state.line, this.state.column));
  9584. };
  9585. PlainCharacterCursor.prototype.getChars = function (start) {
  9586. return this.input.substring(start.state.offset, this.state.offset);
  9587. };
  9588. PlainCharacterCursor.prototype.charAt = function (pos) { return this.input.charCodeAt(pos); };
  9589. PlainCharacterCursor.prototype.advanceState = function (state) {
  9590. if (state.offset >= this.end) {
  9591. this.state = state;
  9592. throw new CursorError('Unexpected character "EOF"', this);
  9593. }
  9594. var currentChar = this.charAt(state.offset);
  9595. if (currentChar === $LF) {
  9596. state.line++;
  9597. state.column = 0;
  9598. }
  9599. else if (!isNewLine(currentChar)) {
  9600. state.column++;
  9601. }
  9602. state.offset++;
  9603. this.updatePeek(state);
  9604. };
  9605. PlainCharacterCursor.prototype.updatePeek = function (state) {
  9606. state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
  9607. };
  9608. return PlainCharacterCursor;
  9609. }());
  9610. var EscapedCharacterCursor = /** @class */ (function (_super) {
  9611. __extends(EscapedCharacterCursor, _super);
  9612. function EscapedCharacterCursor(fileOrCursor, range) {
  9613. var _this = this;
  9614. if (fileOrCursor instanceof EscapedCharacterCursor) {
  9615. _this = _super.call(this, fileOrCursor) || this;
  9616. _this.internalState = __assign({}, fileOrCursor.internalState);
  9617. }
  9618. else {
  9619. _this = _super.call(this, fileOrCursor, range) || this;
  9620. _this.internalState = _this.state;
  9621. }
  9622. return _this;
  9623. }
  9624. EscapedCharacterCursor.prototype.advance = function () {
  9625. this.state = this.internalState;
  9626. _super.prototype.advance.call(this);
  9627. this.processEscapeSequence();
  9628. };
  9629. EscapedCharacterCursor.prototype.init = function () {
  9630. _super.prototype.init.call(this);
  9631. this.processEscapeSequence();
  9632. };
  9633. EscapedCharacterCursor.prototype.clone = function () { return new EscapedCharacterCursor(this); };
  9634. EscapedCharacterCursor.prototype.getChars = function (start) {
  9635. var cursor = start.clone();
  9636. var chars = '';
  9637. while (cursor.internalState.offset < this.internalState.offset) {
  9638. chars += String.fromCodePoint(cursor.peek());
  9639. cursor.advance();
  9640. }
  9641. return chars;
  9642. };
  9643. /**
  9644. * Process the escape sequence that starts at the current position in the text.
  9645. *
  9646. * This method is called to ensure that `peek` has the unescaped value of escape sequences.
  9647. */
  9648. EscapedCharacterCursor.prototype.processEscapeSequence = function () {
  9649. var _this = this;
  9650. var peek = function () { return _this.internalState.peek; };
  9651. if (peek() === $BACKSLASH) {
  9652. // We have hit an escape sequence so we need the internal state to become independent
  9653. // of the external state.
  9654. this.internalState = __assign({}, this.state);
  9655. // Move past the backslash
  9656. this.advanceState(this.internalState);
  9657. // First check for standard control char sequences
  9658. if (peek() === $n) {
  9659. this.state.peek = $LF;
  9660. }
  9661. else if (peek() === $r) {
  9662. this.state.peek = $CR;
  9663. }
  9664. else if (peek() === $v) {
  9665. this.state.peek = $VTAB;
  9666. }
  9667. else if (peek() === $t) {
  9668. this.state.peek = $TAB;
  9669. }
  9670. else if (peek() === $b) {
  9671. this.state.peek = $BSPACE;
  9672. }
  9673. else if (peek() === $f) {
  9674. this.state.peek = $FF;
  9675. }
  9676. // Now consider more complex sequences
  9677. else if (peek() === $u) {
  9678. // Unicode code-point sequence
  9679. this.advanceState(this.internalState); // advance past the `u` char
  9680. if (peek() === $LBRACE) {
  9681. // Variable length Unicode, e.g. `\x{123}`
  9682. this.advanceState(this.internalState); // advance past the `{` char
  9683. // Advance past the variable number of hex digits until we hit a `}` char
  9684. var digitStart = this.clone();
  9685. var length_1 = 0;
  9686. while (peek() !== $RBRACE) {
  9687. this.advanceState(this.internalState);
  9688. length_1++;
  9689. }
  9690. this.state.peek = this.decodeHexDigits(digitStart, length_1);
  9691. }
  9692. else {
  9693. // Fixed length Unicode, e.g. `\u1234`
  9694. var digitStart = this.clone();
  9695. this.advanceState(this.internalState);
  9696. this.advanceState(this.internalState);
  9697. this.advanceState(this.internalState);
  9698. this.state.peek = this.decodeHexDigits(digitStart, 4);
  9699. }
  9700. }
  9701. else if (peek() === $x) {
  9702. // Hex char code, e.g. `\x2F`
  9703. this.advanceState(this.internalState); // advance past the `x` char
  9704. var digitStart = this.clone();
  9705. this.advanceState(this.internalState);
  9706. this.state.peek = this.decodeHexDigits(digitStart, 2);
  9707. }
  9708. else if (isOctalDigit(peek())) {
  9709. // Octal char code, e.g. `\012`,
  9710. var octal = '';
  9711. var length_2 = 0;
  9712. var previous = this.clone();
  9713. while (isOctalDigit(peek()) && length_2 < 3) {
  9714. previous = this.clone();
  9715. octal += String.fromCodePoint(peek());
  9716. this.advanceState(this.internalState);
  9717. length_2++;
  9718. }
  9719. this.state.peek = parseInt(octal, 8);
  9720. // Backup one char
  9721. this.internalState = previous.internalState;
  9722. }
  9723. else if (isNewLine(this.internalState.peek)) {
  9724. // Line continuation `\` followed by a new line
  9725. this.advanceState(this.internalState); // advance over the newline
  9726. this.state = this.internalState;
  9727. }
  9728. else {
  9729. // If none of the `if` blocks were executed then we just have an escaped normal character.
  9730. // In that case we just, effectively, skip the backslash from the character.
  9731. this.state.peek = this.internalState.peek;
  9732. }
  9733. }
  9734. };
  9735. EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) {
  9736. var hex = this.input.substr(start.internalState.offset, length);
  9737. var charCode = parseInt(hex, 16);
  9738. if (!isNaN(charCode)) {
  9739. return charCode;
  9740. }
  9741. else {
  9742. start.state = start.internalState;
  9743. throw new CursorError('Invalid hexadecimal escape sequence', start);
  9744. }
  9745. };
  9746. return EscapedCharacterCursor;
  9747. }(PlainCharacterCursor));
  9748. var CursorError = /** @class */ (function () {
  9749. function CursorError(msg, cursor) {
  9750. this.msg = msg;
  9751. this.cursor = cursor;
  9752. }
  9753. return CursorError;
  9754. }());
  9755. /**
  9756. * @license
  9757. * Copyright Google Inc. All Rights Reserved.
  9758. *
  9759. * Use of this source code is governed by an MIT-style license that can be
  9760. * found in the LICENSE file at https://angular.io/license
  9761. */
  9762. var TreeError = /** @class */ (function (_super) {
  9763. __extends(TreeError, _super);
  9764. function TreeError(elementName, span, msg) {
  9765. var _this = _super.call(this, span, msg) || this;
  9766. _this.elementName = elementName;
  9767. return _this;
  9768. }
  9769. TreeError.create = function (elementName, span, msg) {
  9770. return new TreeError(elementName, span, msg);
  9771. };
  9772. return TreeError;
  9773. }(ParseError));
  9774. var ParseTreeResult = /** @class */ (function () {
  9775. function ParseTreeResult(rootNodes, errors) {
  9776. this.rootNodes = rootNodes;
  9777. this.errors = errors;
  9778. }
  9779. return ParseTreeResult;
  9780. }());
  9781. var Parser = /** @class */ (function () {
  9782. function Parser(getTagDefinition) {
  9783. this.getTagDefinition = getTagDefinition;
  9784. }
  9785. Parser.prototype.parse = function (source, url, options) {
  9786. var tokensAndErrors = tokenize(source, url, this.getTagDefinition, options);
  9787. var treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
  9788. return new ParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors));
  9789. };
  9790. return Parser;
  9791. }());
  9792. var _TreeBuilder = /** @class */ (function () {
  9793. function _TreeBuilder(tokens, getTagDefinition) {
  9794. this.tokens = tokens;
  9795. this.getTagDefinition = getTagDefinition;
  9796. this._index = -1;
  9797. this._rootNodes = [];
  9798. this._errors = [];
  9799. this._elementStack = [];
  9800. this._advance();
  9801. }
  9802. _TreeBuilder.prototype.build = function () {
  9803. while (this._peek.type !== TokenType.EOF) {
  9804. if (this._peek.type === TokenType.TAG_OPEN_START) {
  9805. this._consumeStartTag(this._advance());
  9806. }
  9807. else if (this._peek.type === TokenType.TAG_CLOSE) {
  9808. this._consumeEndTag(this._advance());
  9809. }
  9810. else if (this._peek.type === TokenType.CDATA_START) {
  9811. this._closeVoidElement();
  9812. this._consumeCdata(this._advance());
  9813. }
  9814. else if (this._peek.type === TokenType.COMMENT_START) {
  9815. this._closeVoidElement();
  9816. this._consumeComment(this._advance());
  9817. }
  9818. else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
  9819. this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
  9820. this._closeVoidElement();
  9821. this._consumeText(this._advance());
  9822. }
  9823. else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
  9824. this._consumeExpansion(this._advance());
  9825. }
  9826. else {
  9827. // Skip all other tokens...
  9828. this._advance();
  9829. }
  9830. }
  9831. return new ParseTreeResult(this._rootNodes, this._errors);
  9832. };
  9833. _TreeBuilder.prototype._advance = function () {
  9834. var prev = this._peek;
  9835. if (this._index < this.tokens.length - 1) {
  9836. // Note: there is always an EOF token at the end
  9837. this._index++;
  9838. }
  9839. this._peek = this.tokens[this._index];
  9840. return prev;
  9841. };
  9842. _TreeBuilder.prototype._advanceIf = function (type) {
  9843. if (this._peek.type === type) {
  9844. return this._advance();
  9845. }
  9846. return null;
  9847. };
  9848. _TreeBuilder.prototype._consumeCdata = function (startToken) {
  9849. this._consumeText(this._advance());
  9850. this._advanceIf(TokenType.CDATA_END);
  9851. };
  9852. _TreeBuilder.prototype._consumeComment = function (token) {
  9853. var text = this._advanceIf(TokenType.RAW_TEXT);
  9854. this._advanceIf(TokenType.COMMENT_END);
  9855. var value = text != null ? text.parts[0].trim() : null;
  9856. this._addToParent(new Comment(value, token.sourceSpan));
  9857. };
  9858. _TreeBuilder.prototype._consumeExpansion = function (token) {
  9859. var switchValue = this._advance();
  9860. var type = this._advance();
  9861. var cases = [];
  9862. // read =
  9863. while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
  9864. var expCase = this._parseExpansionCase();
  9865. if (!expCase)
  9866. return; // error
  9867. cases.push(expCase);
  9868. }
  9869. // read the final }
  9870. if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
  9871. this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'."));
  9872. return;
  9873. }
  9874. var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
  9875. this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
  9876. this._advance();
  9877. };
  9878. _TreeBuilder.prototype._parseExpansionCase = function () {
  9879. var value = this._advance();
  9880. // read {
  9881. if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
  9882. this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'."));
  9883. return null;
  9884. }
  9885. // read until }
  9886. var start = this._advance();
  9887. var exp = this._collectExpansionExpTokens(start);
  9888. if (!exp)
  9889. return null;
  9890. var end = this._advance();
  9891. exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
  9892. // parse everything in between { and }
  9893. var parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
  9894. if (parsedExp.errors.length > 0) {
  9895. this._errors = this._errors.concat(parsedExp.errors);
  9896. return null;
  9897. }
  9898. var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
  9899. var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
  9900. return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
  9901. };
  9902. _TreeBuilder.prototype._collectExpansionExpTokens = function (start) {
  9903. var exp = [];
  9904. var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
  9905. while (true) {
  9906. if (this._peek.type === TokenType.EXPANSION_FORM_START ||
  9907. this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
  9908. expansionFormStack.push(this._peek.type);
  9909. }
  9910. if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
  9911. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
  9912. expansionFormStack.pop();
  9913. if (expansionFormStack.length == 0)
  9914. return exp;
  9915. }
  9916. else {
  9917. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  9918. return null;
  9919. }
  9920. }
  9921. if (this._peek.type === TokenType.EXPANSION_FORM_END) {
  9922. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
  9923. expansionFormStack.pop();
  9924. }
  9925. else {
  9926. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  9927. return null;
  9928. }
  9929. }
  9930. if (this._peek.type === TokenType.EOF) {
  9931. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  9932. return null;
  9933. }
  9934. exp.push(this._advance());
  9935. }
  9936. };
  9937. _TreeBuilder.prototype._consumeText = function (token) {
  9938. var text = token.parts[0];
  9939. if (text.length > 0 && text[0] == '\n') {
  9940. var parent_1 = this._getParentElement();
  9941. if (parent_1 != null && parent_1.children.length == 0 &&
  9942. this.getTagDefinition(parent_1.name).ignoreFirstLf) {
  9943. text = text.substring(1);
  9944. }
  9945. }
  9946. if (text.length > 0) {
  9947. this._addToParent(new Text$3(text, token.sourceSpan));
  9948. }
  9949. };
  9950. _TreeBuilder.prototype._closeVoidElement = function () {
  9951. var el = this._getParentElement();
  9952. if (el && this.getTagDefinition(el.name).isVoid) {
  9953. this._elementStack.pop();
  9954. }
  9955. };
  9956. _TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
  9957. var prefix = startTagToken.parts[0];
  9958. var name = startTagToken.parts[1];
  9959. var attrs = [];
  9960. while (this._peek.type === TokenType.ATTR_NAME) {
  9961. attrs.push(this._consumeAttr(this._advance()));
  9962. }
  9963. var fullName = this._getElementFullName(prefix, name, this._getParentElement());
  9964. var selfClosing = false;
  9965. // Note: There could have been a tokenizer error
  9966. // so that we don't get a token for the end tag...
  9967. if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
  9968. this._advance();
  9969. selfClosing = true;
  9970. var tagDef = this.getTagDefinition(fullName);
  9971. if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
  9972. this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
  9973. }
  9974. }
  9975. else if (this._peek.type === TokenType.TAG_OPEN_END) {
  9976. this._advance();
  9977. selfClosing = false;
  9978. }
  9979. var end = this._peek.sourceSpan.start;
  9980. var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
  9981. var el = new Element$1(fullName, attrs, [], span, span, undefined);
  9982. this._pushElement(el);
  9983. if (selfClosing) {
  9984. this._popElement(fullName);
  9985. el.endSourceSpan = span;
  9986. }
  9987. };
  9988. _TreeBuilder.prototype._pushElement = function (el) {
  9989. var parentEl = this._getParentElement();
  9990. if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
  9991. this._elementStack.pop();
  9992. }
  9993. this._addToParent(el);
  9994. this._elementStack.push(el);
  9995. };
  9996. _TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
  9997. var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
  9998. if (this._getParentElement()) {
  9999. this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
  10000. }
  10001. if (this.getTagDefinition(fullName).isVoid) {
  10002. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
  10003. }
  10004. else if (!this._popElement(fullName)) {
  10005. var errMsg = "Unexpected closing tag \"" + fullName + "\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags";
  10006. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
  10007. }
  10008. };
  10009. _TreeBuilder.prototype._popElement = function (fullName) {
  10010. for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
  10011. var el = this._elementStack[stackIndex];
  10012. if (el.name == fullName) {
  10013. this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
  10014. return true;
  10015. }
  10016. if (!this.getTagDefinition(el.name).closedByParent) {
  10017. return false;
  10018. }
  10019. }
  10020. return false;
  10021. };
  10022. _TreeBuilder.prototype._consumeAttr = function (attrName) {
  10023. var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
  10024. var end = attrName.sourceSpan.end;
  10025. var value = '';
  10026. var valueSpan = undefined;
  10027. if (this._peek.type === TokenType.ATTR_QUOTE) {
  10028. this._advance();
  10029. }
  10030. if (this._peek.type === TokenType.ATTR_VALUE) {
  10031. var valueToken = this._advance();
  10032. value = valueToken.parts[0];
  10033. end = valueToken.sourceSpan.end;
  10034. valueSpan = valueToken.sourceSpan;
  10035. }
  10036. if (this._peek.type === TokenType.ATTR_QUOTE) {
  10037. var quoteToken = this._advance();
  10038. end = quoteToken.sourceSpan.end;
  10039. }
  10040. return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan);
  10041. };
  10042. _TreeBuilder.prototype._getParentElement = function () {
  10043. return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
  10044. };
  10045. /**
  10046. * Returns the parent in the DOM and the container.
  10047. *
  10048. * `<ng-container>` elements are skipped as they are not rendered as DOM element.
  10049. */
  10050. _TreeBuilder.prototype._getParentElementSkippingContainers = function () {
  10051. var container = null;
  10052. for (var i = this._elementStack.length - 1; i >= 0; i--) {
  10053. if (!isNgContainer(this._elementStack[i].name)) {
  10054. return { parent: this._elementStack[i], container: container };
  10055. }
  10056. container = this._elementStack[i];
  10057. }
  10058. return { parent: null, container: container };
  10059. };
  10060. _TreeBuilder.prototype._addToParent = function (node) {
  10061. var parent = this._getParentElement();
  10062. if (parent != null) {
  10063. parent.children.push(node);
  10064. }
  10065. else {
  10066. this._rootNodes.push(node);
  10067. }
  10068. };
  10069. /**
  10070. * Insert a node between the parent and the container.
  10071. * When no container is given, the node is appended as a child of the parent.
  10072. * Also updates the element stack accordingly.
  10073. *
  10074. * @internal
  10075. */
  10076. _TreeBuilder.prototype._insertBeforeContainer = function (parent, container, node) {
  10077. if (!container) {
  10078. this._addToParent(node);
  10079. this._elementStack.push(node);
  10080. }
  10081. else {
  10082. if (parent) {
  10083. // replace the container with the new node in the children
  10084. var index = parent.children.indexOf(container);
  10085. parent.children[index] = node;
  10086. }
  10087. else {
  10088. this._rootNodes.push(node);
  10089. }
  10090. node.children.push(container);
  10091. this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
  10092. }
  10093. };
  10094. _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) {
  10095. if (prefix === '') {
  10096. prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
  10097. if (prefix === '' && parentElement != null) {
  10098. prefix = getNsPrefix(parentElement.name);
  10099. }
  10100. }
  10101. return mergeNsAndName(prefix, localName);
  10102. };
  10103. return _TreeBuilder;
  10104. }());
  10105. function lastOnStack(stack, element) {
  10106. return stack.length > 0 && stack[stack.length - 1] === element;
  10107. }
  10108. /**
  10109. * @license
  10110. * Copyright Google Inc. All Rights Reserved.
  10111. *
  10112. * Use of this source code is governed by an MIT-style license that can be
  10113. * found in the LICENSE file at https://angular.io/license
  10114. */
  10115. var HtmlParser = /** @class */ (function (_super) {
  10116. __extends(HtmlParser, _super);
  10117. function HtmlParser() {
  10118. return _super.call(this, getHtmlTagDefinition) || this;
  10119. }
  10120. HtmlParser.prototype.parse = function (source, url, options) {
  10121. return _super.prototype.parse.call(this, source, url, options);
  10122. };
  10123. return HtmlParser;
  10124. }(Parser));
  10125. /**
  10126. * @license
  10127. * Copyright Google Inc. All Rights Reserved.
  10128. *
  10129. * Use of this source code is governed by an MIT-style license that can be
  10130. * found in the LICENSE file at https://angular.io/license
  10131. */
  10132. var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
  10133. var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
  10134. // Equivalent to \s with \u00a0 (non-breaking space) excluded.
  10135. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  10136. var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
  10137. var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]");
  10138. var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g');
  10139. function hasPreserveWhitespacesAttr(attrs) {
  10140. return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; });
  10141. }
  10142. /**
  10143. * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
  10144. * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
  10145. * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
  10146. * and later on replaced by a space. We are re-implementing the same idea here.
  10147. */
  10148. function replaceNgsp(value) {
  10149. // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
  10150. return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
  10151. }
  10152. /**
  10153. * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
  10154. * - consider spaces, tabs and new lines as whitespace characters;
  10155. * - drop text nodes consisting of whitespace characters only;
  10156. * - for all other text nodes replace consecutive whitespace characters with one space;
  10157. * - convert &ngsp; pseudo-entity to a single space;
  10158. *
  10159. * Removal and trimming of whitespaces have positive performance impact (less code to generate
  10160. * while compiling templates, faster view creation). At the same time it can be "destructive"
  10161. * in some cases (whitespaces can influence layout). Because of the potential of breaking layout
  10162. * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
  10163. * whitespace removal. The default option for whitespace removal will be revisited in Angular 6
  10164. * and might be changed to "on" by default.
  10165. */
  10166. var WhitespaceVisitor = /** @class */ (function () {
  10167. function WhitespaceVisitor() {
  10168. }
  10169. WhitespaceVisitor.prototype.visitElement = function (element, context) {
  10170. if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
  10171. // don't descent into elements where we need to preserve whitespaces
  10172. // but still visit all attributes to eliminate one used as a market to preserve WS
  10173. return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  10174. }
  10175. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  10176. };
  10177. WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) {
  10178. return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
  10179. };
  10180. WhitespaceVisitor.prototype.visitText = function (text, context) {
  10181. var isNotBlank = text.value.match(NO_WS_REGEXP);
  10182. if (isNotBlank) {
  10183. return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
  10184. }
  10185. return null;
  10186. };
  10187. WhitespaceVisitor.prototype.visitComment = function (comment, context) { return comment; };
  10188. WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
  10189. WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  10190. return WhitespaceVisitor;
  10191. }());
  10192. function removeWhitespaces(htmlAstWithErrors) {
  10193. return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
  10194. }
  10195. /**
  10196. * @license
  10197. * Copyright Google Inc. All Rights Reserved.
  10198. *
  10199. * Use of this source code is governed by an MIT-style license that can be
  10200. * found in the LICENSE file at https://angular.io/license
  10201. */
  10202. // http://cldr.unicode.org/index/cldr-spec/plural-rules
  10203. var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
  10204. /**
  10205. * Expands special forms into elements.
  10206. *
  10207. * For example,
  10208. *
  10209. * ```
  10210. * { messages.length, plural,
  10211. * =0 {zero}
  10212. * =1 {one}
  10213. * other {more than one}
  10214. * }
  10215. * ```
  10216. *
  10217. * will be expanded into
  10218. *
  10219. * ```
  10220. * <ng-container [ngPlural]="messages.length">
  10221. * <ng-template ngPluralCase="=0">zero</ng-template>
  10222. * <ng-template ngPluralCase="=1">one</ng-template>
  10223. * <ng-template ngPluralCase="other">more than one</ng-template>
  10224. * </ng-container>
  10225. * ```
  10226. */
  10227. function expandNodes(nodes) {
  10228. var expander = new _Expander();
  10229. return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
  10230. }
  10231. var ExpansionResult = /** @class */ (function () {
  10232. function ExpansionResult(nodes, expanded, errors) {
  10233. this.nodes = nodes;
  10234. this.expanded = expanded;
  10235. this.errors = errors;
  10236. }
  10237. return ExpansionResult;
  10238. }());
  10239. var ExpansionError = /** @class */ (function (_super) {
  10240. __extends(ExpansionError, _super);
  10241. function ExpansionError(span, errorMsg) {
  10242. return _super.call(this, span, errorMsg) || this;
  10243. }
  10244. return ExpansionError;
  10245. }(ParseError));
  10246. /**
  10247. * Expand expansion forms (plural, select) to directives
  10248. *
  10249. * @internal
  10250. */
  10251. var _Expander = /** @class */ (function () {
  10252. function _Expander() {
  10253. this.isExpanded = false;
  10254. this.errors = [];
  10255. }
  10256. _Expander.prototype.visitElement = function (element, context) {
  10257. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
  10258. };
  10259. _Expander.prototype.visitAttribute = function (attribute, context) { return attribute; };
  10260. _Expander.prototype.visitText = function (text, context) { return text; };
  10261. _Expander.prototype.visitComment = function (comment, context) { return comment; };
  10262. _Expander.prototype.visitExpansion = function (icu, context) {
  10263. this.isExpanded = true;
  10264. return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
  10265. _expandDefaultForm(icu, this.errors);
  10266. };
  10267. _Expander.prototype.visitExpansionCase = function (icuCase, context) {
  10268. throw new Error('Should not be reached');
  10269. };
  10270. return _Expander;
  10271. }());
  10272. // Plural forms are expanded to `NgPlural` and `NgPluralCase`s
  10273. function _expandPluralForm(ast, errors) {
  10274. var children = ast.cases.map(function (c) {
  10275. if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
  10276. errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=<number>\" or one of " + PLURAL_CASES.join(", ")));
  10277. }
  10278. var expansionResult = expandNodes(c.expression);
  10279. errors.push.apply(errors, __spread(expansionResult.errors));
  10280. return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10281. });
  10282. var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan);
  10283. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  10284. }
  10285. // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
  10286. function _expandDefaultForm(ast, errors) {
  10287. var children = ast.cases.map(function (c) {
  10288. var expansionResult = expandNodes(c.expression);
  10289. errors.push.apply(errors, __spread(expansionResult.errors));
  10290. if (c.value === 'other') {
  10291. // other is the default case when no values match
  10292. return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10293. }
  10294. return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10295. });
  10296. var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan);
  10297. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  10298. }
  10299. /**
  10300. * @license
  10301. * Copyright Google Inc. All Rights Reserved.
  10302. *
  10303. * Use of this source code is governed by an MIT-style license that can be
  10304. * found in the LICENSE file at https://angular.io/license
  10305. */
  10306. var _a;
  10307. /**
  10308. * A segment of text within the template.
  10309. */
  10310. var TextAst = /** @class */ (function () {
  10311. function TextAst(value, ngContentIndex, sourceSpan) {
  10312. this.value = value;
  10313. this.ngContentIndex = ngContentIndex;
  10314. this.sourceSpan = sourceSpan;
  10315. }
  10316. TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  10317. return TextAst;
  10318. }());
  10319. /**
  10320. * A bound expression within the text of a template.
  10321. */
  10322. var BoundTextAst = /** @class */ (function () {
  10323. function BoundTextAst(value, ngContentIndex, sourceSpan) {
  10324. this.value = value;
  10325. this.ngContentIndex = ngContentIndex;
  10326. this.sourceSpan = sourceSpan;
  10327. }
  10328. BoundTextAst.prototype.visit = function (visitor, context) {
  10329. return visitor.visitBoundText(this, context);
  10330. };
  10331. return BoundTextAst;
  10332. }());
  10333. /**
  10334. * A plain attribute on an element.
  10335. */
  10336. var AttrAst = /** @class */ (function () {
  10337. function AttrAst(name, value, sourceSpan) {
  10338. this.name = name;
  10339. this.value = value;
  10340. this.sourceSpan = sourceSpan;
  10341. }
  10342. AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
  10343. return AttrAst;
  10344. }());
  10345. var BoundPropertyMapping = (_a = {},
  10346. _a[4 /* Animation */] = 4 /* Animation */,
  10347. _a[1 /* Attribute */] = 1 /* Attribute */,
  10348. _a[2 /* Class */] = 2 /* Class */,
  10349. _a[0 /* Property */] = 0 /* Property */,
  10350. _a[3 /* Style */] = 3 /* Style */,
  10351. _a);
  10352. /**
  10353. * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
  10354. * `[@trigger]="stateExp"`)
  10355. */
  10356. var BoundElementPropertyAst = /** @class */ (function () {
  10357. function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) {
  10358. this.name = name;
  10359. this.type = type;
  10360. this.securityContext = securityContext;
  10361. this.value = value;
  10362. this.unit = unit;
  10363. this.sourceSpan = sourceSpan;
  10364. this.isAnimation = this.type === 4 /* Animation */;
  10365. }
  10366. BoundElementPropertyAst.fromBoundProperty = function (prop) {
  10367. var type = BoundPropertyMapping[prop.type];
  10368. return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
  10369. };
  10370. BoundElementPropertyAst.prototype.visit = function (visitor, context) {
  10371. return visitor.visitElementProperty(this, context);
  10372. };
  10373. return BoundElementPropertyAst;
  10374. }());
  10375. /**
  10376. * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
  10377. * `(@trigger.phase)="callback($event)"`).
  10378. */
  10379. var BoundEventAst = /** @class */ (function () {
  10380. function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) {
  10381. this.name = name;
  10382. this.target = target;
  10383. this.phase = phase;
  10384. this.handler = handler;
  10385. this.sourceSpan = sourceSpan;
  10386. this.handlerSpan = handlerSpan;
  10387. this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
  10388. this.isAnimation = !!this.phase;
  10389. }
  10390. BoundEventAst.calcFullName = function (name, target, phase) {
  10391. if (target) {
  10392. return target + ":" + name;
  10393. }
  10394. if (phase) {
  10395. return "@" + name + "." + phase;
  10396. }
  10397. return name;
  10398. };
  10399. BoundEventAst.fromParsedEvent = function (event) {
  10400. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  10401. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  10402. return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
  10403. };
  10404. BoundEventAst.prototype.visit = function (visitor, context) {
  10405. return visitor.visitEvent(this, context);
  10406. };
  10407. return BoundEventAst;
  10408. }());
  10409. /**
  10410. * A reference declaration on an element (e.g. `let someName="expression"`).
  10411. */
  10412. var ReferenceAst = /** @class */ (function () {
  10413. function ReferenceAst(name, value, originalValue, sourceSpan) {
  10414. this.name = name;
  10415. this.value = value;
  10416. this.originalValue = originalValue;
  10417. this.sourceSpan = sourceSpan;
  10418. }
  10419. ReferenceAst.prototype.visit = function (visitor, context) {
  10420. return visitor.visitReference(this, context);
  10421. };
  10422. return ReferenceAst;
  10423. }());
  10424. /**
  10425. * A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
  10426. */
  10427. var VariableAst = /** @class */ (function () {
  10428. function VariableAst(name, value, sourceSpan) {
  10429. this.name = name;
  10430. this.value = value;
  10431. this.sourceSpan = sourceSpan;
  10432. }
  10433. VariableAst.fromParsedVariable = function (v) {
  10434. return new VariableAst(v.name, v.value, v.sourceSpan);
  10435. };
  10436. VariableAst.prototype.visit = function (visitor, context) {
  10437. return visitor.visitVariable(this, context);
  10438. };
  10439. return VariableAst;
  10440. }());
  10441. /**
  10442. * An element declaration in a template.
  10443. */
  10444. var ElementAst = /** @class */ (function () {
  10445. function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
  10446. this.name = name;
  10447. this.attrs = attrs;
  10448. this.inputs = inputs;
  10449. this.outputs = outputs;
  10450. this.references = references;
  10451. this.directives = directives;
  10452. this.providers = providers;
  10453. this.hasViewContainer = hasViewContainer;
  10454. this.queryMatches = queryMatches;
  10455. this.children = children;
  10456. this.ngContentIndex = ngContentIndex;
  10457. this.sourceSpan = sourceSpan;
  10458. this.endSourceSpan = endSourceSpan;
  10459. }
  10460. ElementAst.prototype.visit = function (visitor, context) {
  10461. return visitor.visitElement(this, context);
  10462. };
  10463. return ElementAst;
  10464. }());
  10465. /**
  10466. * A `<ng-template>` element included in an Angular template.
  10467. */
  10468. var EmbeddedTemplateAst = /** @class */ (function () {
  10469. function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
  10470. this.attrs = attrs;
  10471. this.outputs = outputs;
  10472. this.references = references;
  10473. this.variables = variables;
  10474. this.directives = directives;
  10475. this.providers = providers;
  10476. this.hasViewContainer = hasViewContainer;
  10477. this.queryMatches = queryMatches;
  10478. this.children = children;
  10479. this.ngContentIndex = ngContentIndex;
  10480. this.sourceSpan = sourceSpan;
  10481. }
  10482. EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
  10483. return visitor.visitEmbeddedTemplate(this, context);
  10484. };
  10485. return EmbeddedTemplateAst;
  10486. }());
  10487. /**
  10488. * A directive property with a bound value (e.g. `*ngIf="condition").
  10489. */
  10490. var BoundDirectivePropertyAst = /** @class */ (function () {
  10491. function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
  10492. this.directiveName = directiveName;
  10493. this.templateName = templateName;
  10494. this.value = value;
  10495. this.sourceSpan = sourceSpan;
  10496. }
  10497. BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
  10498. return visitor.visitDirectiveProperty(this, context);
  10499. };
  10500. return BoundDirectivePropertyAst;
  10501. }());
  10502. /**
  10503. * A directive declared on an element.
  10504. */
  10505. var DirectiveAst = /** @class */ (function () {
  10506. function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
  10507. this.directive = directive;
  10508. this.inputs = inputs;
  10509. this.hostProperties = hostProperties;
  10510. this.hostEvents = hostEvents;
  10511. this.contentQueryStartId = contentQueryStartId;
  10512. this.sourceSpan = sourceSpan;
  10513. }
  10514. DirectiveAst.prototype.visit = function (visitor, context) {
  10515. return visitor.visitDirective(this, context);
  10516. };
  10517. return DirectiveAst;
  10518. }());
  10519. /**
  10520. * A provider declared on an element
  10521. */
  10522. var ProviderAst = /** @class */ (function () {
  10523. function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
  10524. this.token = token;
  10525. this.multiProvider = multiProvider;
  10526. this.eager = eager;
  10527. this.providers = providers;
  10528. this.providerType = providerType;
  10529. this.lifecycleHooks = lifecycleHooks;
  10530. this.sourceSpan = sourceSpan;
  10531. this.isModule = isModule;
  10532. }
  10533. ProviderAst.prototype.visit = function (visitor, context) {
  10534. // No visit method in the visitor for now...
  10535. return null;
  10536. };
  10537. return ProviderAst;
  10538. }());
  10539. var ProviderAstType;
  10540. (function (ProviderAstType) {
  10541. ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
  10542. ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
  10543. ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
  10544. ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
  10545. ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
  10546. })(ProviderAstType || (ProviderAstType = {}));
  10547. /**
  10548. * Position where content is to be projected (instance of `<ng-content>` in a template).
  10549. */
  10550. var NgContentAst = /** @class */ (function () {
  10551. function NgContentAst(index, ngContentIndex, sourceSpan) {
  10552. this.index = index;
  10553. this.ngContentIndex = ngContentIndex;
  10554. this.sourceSpan = sourceSpan;
  10555. }
  10556. NgContentAst.prototype.visit = function (visitor, context) {
  10557. return visitor.visitNgContent(this, context);
  10558. };
  10559. return NgContentAst;
  10560. }());
  10561. /**
  10562. * A visitor that accepts each node but doesn't do anything. It is intended to be used
  10563. * as the base class for a visitor that is only interested in a subset of the node types.
  10564. */
  10565. var NullTemplateVisitor = /** @class */ (function () {
  10566. function NullTemplateVisitor() {
  10567. }
  10568. NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { };
  10569. NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { };
  10570. NullTemplateVisitor.prototype.visitElement = function (ast, context) { };
  10571. NullTemplateVisitor.prototype.visitReference = function (ast, context) { };
  10572. NullTemplateVisitor.prototype.visitVariable = function (ast, context) { };
  10573. NullTemplateVisitor.prototype.visitEvent = function (ast, context) { };
  10574. NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { };
  10575. NullTemplateVisitor.prototype.visitAttr = function (ast, context) { };
  10576. NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { };
  10577. NullTemplateVisitor.prototype.visitText = function (ast, context) { };
  10578. NullTemplateVisitor.prototype.visitDirective = function (ast, context) { };
  10579. NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { };
  10580. return NullTemplateVisitor;
  10581. }());
  10582. /**
  10583. * Base class that can be used to build a visitor that visits each node
  10584. * in an template ast recursively.
  10585. */
  10586. var RecursiveTemplateAstVisitor = /** @class */ (function (_super) {
  10587. __extends(RecursiveTemplateAstVisitor, _super);
  10588. function RecursiveTemplateAstVisitor() {
  10589. return _super.call(this) || this;
  10590. }
  10591. // Nodes with children
  10592. RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
  10593. return this.visitChildren(context, function (visit) {
  10594. visit(ast.attrs);
  10595. visit(ast.references);
  10596. visit(ast.variables);
  10597. visit(ast.directives);
  10598. visit(ast.providers);
  10599. visit(ast.children);
  10600. });
  10601. };
  10602. RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) {
  10603. return this.visitChildren(context, function (visit) {
  10604. visit(ast.attrs);
  10605. visit(ast.inputs);
  10606. visit(ast.outputs);
  10607. visit(ast.references);
  10608. visit(ast.directives);
  10609. visit(ast.providers);
  10610. visit(ast.children);
  10611. });
  10612. };
  10613. RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) {
  10614. return this.visitChildren(context, function (visit) {
  10615. visit(ast.inputs);
  10616. visit(ast.hostProperties);
  10617. visit(ast.hostEvents);
  10618. });
  10619. };
  10620. RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) {
  10621. var results = [];
  10622. var t = this;
  10623. function visit(children) {
  10624. if (children && children.length)
  10625. results.push(templateVisitAll(t, children, context));
  10626. }
  10627. cb(visit);
  10628. return [].concat.apply([], results);
  10629. };
  10630. return RecursiveTemplateAstVisitor;
  10631. }(NullTemplateVisitor));
  10632. /**
  10633. * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
  10634. */
  10635. function templateVisitAll(visitor, asts, context) {
  10636. if (context === void 0) { context = null; }
  10637. var result = [];
  10638. var visit = visitor.visit ?
  10639. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  10640. function (ast) { return ast.visit(visitor, context); };
  10641. asts.forEach(function (ast) {
  10642. var astResult = visit(ast);
  10643. if (astResult) {
  10644. result.push(astResult);
  10645. }
  10646. });
  10647. return result;
  10648. }
  10649. /**
  10650. * @license
  10651. * Copyright Google Inc. All Rights Reserved.
  10652. *
  10653. * Use of this source code is governed by an MIT-style license that can be
  10654. * found in the LICENSE file at https://angular.io/license
  10655. */
  10656. var ProviderError = /** @class */ (function (_super) {
  10657. __extends(ProviderError, _super);
  10658. function ProviderError(message, span) {
  10659. return _super.call(this, span, message) || this;
  10660. }
  10661. return ProviderError;
  10662. }(ParseError));
  10663. var ProviderViewContext = /** @class */ (function () {
  10664. function ProviderViewContext(reflector, component) {
  10665. var _this = this;
  10666. this.reflector = reflector;
  10667. this.component = component;
  10668. this.errors = [];
  10669. this.viewQueries = _getViewQueries(component);
  10670. this.viewProviders = new Map();
  10671. component.viewProviders.forEach(function (provider) {
  10672. if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
  10673. _this.viewProviders.set(tokenReference(provider.token), true);
  10674. }
  10675. });
  10676. }
  10677. return ProviderViewContext;
  10678. }());
  10679. var ProviderElementContext = /** @class */ (function () {
  10680. function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
  10681. var _this = this;
  10682. this.viewContext = viewContext;
  10683. this._parent = _parent;
  10684. this._isViewRoot = _isViewRoot;
  10685. this._directiveAsts = _directiveAsts;
  10686. this._sourceSpan = _sourceSpan;
  10687. this._transformedProviders = new Map();
  10688. this._seenProviders = new Map();
  10689. this._queriedTokens = new Map();
  10690. this.transformedHasViewContainer = false;
  10691. this._attrs = {};
  10692. attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
  10693. var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
  10694. this._allProviders =
  10695. _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
  10696. this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
  10697. Array.from(this._allProviders.values()).forEach(function (provider) {
  10698. _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
  10699. });
  10700. if (isTemplate) {
  10701. var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
  10702. this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
  10703. }
  10704. refs.forEach(function (refAst) {
  10705. var defaultQueryValue = refAst.value ||
  10706. createTokenForExternalReference(_this.viewContext.reflector, Identifiers.ElementRef);
  10707. _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
  10708. });
  10709. if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {
  10710. this.transformedHasViewContainer = true;
  10711. }
  10712. // create the providers that we know are eager first
  10713. Array.from(this._allProviders.values()).forEach(function (provider) {
  10714. var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
  10715. if (eager) {
  10716. _this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
  10717. }
  10718. });
  10719. }
  10720. ProviderElementContext.prototype.afterElement = function () {
  10721. var _this = this;
  10722. // collect lazy providers
  10723. Array.from(this._allProviders.values()).forEach(function (provider) {
  10724. _this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
  10725. });
  10726. };
  10727. Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
  10728. get: function () {
  10729. // Note: Maps keep their insertion order.
  10730. var lazyProviders = [];
  10731. var eagerProviders = [];
  10732. this._transformedProviders.forEach(function (provider) {
  10733. if (provider.eager) {
  10734. eagerProviders.push(provider);
  10735. }
  10736. else {
  10737. lazyProviders.push(provider);
  10738. }
  10739. });
  10740. return lazyProviders.concat(eagerProviders);
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
  10746. get: function () {
  10747. var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
  10748. var sortedDirectives = this._directiveAsts.slice();
  10749. sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
  10750. sortedProviderTypes.indexOf(dir2.directive.type); });
  10751. return sortedDirectives;
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
  10757. get: function () {
  10758. var allMatches = [];
  10759. this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, __spread(matches)); });
  10760. return allMatches;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
  10766. this._getQueriesFor(token).forEach(function (query) {
  10767. var queryValue = query.meta.read || defaultValue;
  10768. var tokenRef = tokenReference(queryValue);
  10769. var queryMatches = queryReadTokens.get(tokenRef);
  10770. if (!queryMatches) {
  10771. queryMatches = [];
  10772. queryReadTokens.set(tokenRef, queryMatches);
  10773. }
  10774. queryMatches.push({ queryId: query.queryId, value: queryValue });
  10775. });
  10776. };
  10777. ProviderElementContext.prototype._getQueriesFor = function (token) {
  10778. var result = [];
  10779. var currentEl = this;
  10780. var distance = 0;
  10781. var queries;
  10782. while (currentEl !== null) {
  10783. queries = currentEl._contentQueries.get(tokenReference(token));
  10784. if (queries) {
  10785. result.push.apply(result, __spread(queries.filter(function (query) { return query.meta.descendants || distance <= 1; })));
  10786. }
  10787. if (currentEl._directiveAsts.length > 0) {
  10788. distance++;
  10789. }
  10790. currentEl = currentEl._parent;
  10791. }
  10792. queries = this.viewContext.viewQueries.get(tokenReference(token));
  10793. if (queries) {
  10794. result.push.apply(result, __spread(queries));
  10795. }
  10796. return result;
  10797. };
  10798. ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
  10799. var _this = this;
  10800. var resolvedProvider = this._allProviders.get(tokenReference(token));
  10801. if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
  10802. requestingProviderType === ProviderAstType.PublicService) &&
  10803. resolvedProvider.providerType === ProviderAstType.PrivateService) ||
  10804. ((requestingProviderType === ProviderAstType.PrivateService ||
  10805. requestingProviderType === ProviderAstType.PublicService) &&
  10806. resolvedProvider.providerType === ProviderAstType.Builtin)) {
  10807. return null;
  10808. }
  10809. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  10810. if (transformedProviderAst) {
  10811. return transformedProviderAst;
  10812. }
  10813. if (this._seenProviders.get(tokenReference(token)) != null) {
  10814. this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
  10815. return null;
  10816. }
  10817. this._seenProviders.set(tokenReference(token), true);
  10818. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  10819. var transformedUseValue = provider.useValue;
  10820. var transformedUseExisting = provider.useExisting;
  10821. var transformedDeps = undefined;
  10822. if (provider.useExisting != null) {
  10823. var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
  10824. if (existingDiDep.token != null) {
  10825. transformedUseExisting = existingDiDep.token;
  10826. }
  10827. else {
  10828. transformedUseExisting = null;
  10829. transformedUseValue = existingDiDep.value;
  10830. }
  10831. }
  10832. else if (provider.useFactory) {
  10833. var deps = provider.deps || provider.useFactory.diDeps;
  10834. transformedDeps =
  10835. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  10836. }
  10837. else if (provider.useClass) {
  10838. var deps = provider.deps || provider.useClass.diDeps;
  10839. transformedDeps =
  10840. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  10841. }
  10842. return _transformProvider(provider, {
  10843. useExisting: transformedUseExisting,
  10844. useValue: transformedUseValue,
  10845. deps: transformedDeps
  10846. });
  10847. });
  10848. transformedProviderAst =
  10849. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  10850. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  10851. return transformedProviderAst;
  10852. };
  10853. ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
  10854. if (eager === void 0) { eager = false; }
  10855. if (dep.isAttribute) {
  10856. var attrValue = this._attrs[dep.token.value];
  10857. return { isValue: true, value: attrValue == null ? null : attrValue };
  10858. }
  10859. if (dep.token != null) {
  10860. // access builtints
  10861. if ((requestingProviderType === ProviderAstType.Directive ||
  10862. requestingProviderType === ProviderAstType.Component)) {
  10863. if (tokenReference(dep.token) ===
  10864. this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||
  10865. tokenReference(dep.token) ===
  10866. this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||
  10867. tokenReference(dep.token) ===
  10868. this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) ||
  10869. tokenReference(dep.token) ===
  10870. this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  10871. return dep;
  10872. }
  10873. if (tokenReference(dep.token) ===
  10874. this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  10875. this.transformedHasViewContainer = true;
  10876. }
  10877. }
  10878. // access the injector
  10879. if (tokenReference(dep.token) ===
  10880. this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {
  10881. return dep;
  10882. }
  10883. // access providers
  10884. if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
  10885. return dep;
  10886. }
  10887. }
  10888. return null;
  10889. };
  10890. ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
  10891. if (eager === void 0) { eager = false; }
  10892. var currElement = this;
  10893. var currEager = eager;
  10894. var result = null;
  10895. if (!dep.isSkipSelf) {
  10896. result = this._getLocalDependency(requestingProviderType, dep, eager);
  10897. }
  10898. if (dep.isSelf) {
  10899. if (!result && dep.isOptional) {
  10900. result = { isValue: true, value: null };
  10901. }
  10902. }
  10903. else {
  10904. // check parent elements
  10905. while (!result && currElement._parent) {
  10906. var prevElement = currElement;
  10907. currElement = currElement._parent;
  10908. if (prevElement._isViewRoot) {
  10909. currEager = false;
  10910. }
  10911. result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);
  10912. }
  10913. // check @Host restriction
  10914. if (!result) {
  10915. if (!dep.isHost || this.viewContext.component.isHost ||
  10916. this.viewContext.component.type.reference === tokenReference(dep.token) ||
  10917. this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
  10918. result = dep;
  10919. }
  10920. else {
  10921. result = dep.isOptional ? { isValue: true, value: null } : null;
  10922. }
  10923. }
  10924. }
  10925. if (!result) {
  10926. this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan));
  10927. }
  10928. return result;
  10929. };
  10930. return ProviderElementContext;
  10931. }());
  10932. function _transformProvider(provider, _a) {
  10933. var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
  10934. return {
  10935. token: provider.token,
  10936. useClass: provider.useClass,
  10937. useExisting: useExisting,
  10938. useFactory: provider.useFactory,
  10939. useValue: useValue,
  10940. deps: deps,
  10941. multi: provider.multi
  10942. };
  10943. }
  10944. function _transformProviderAst(provider, _a) {
  10945. var eager = _a.eager, providers = _a.providers;
  10946. return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
  10947. }
  10948. function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
  10949. var providersByToken = new Map();
  10950. directives.forEach(function (directive) {
  10951. var dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
  10952. _resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  10953. });
  10954. // Note: directives need to be able to overwrite providers of a component!
  10955. var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
  10956. directivesWithComponentFirst.forEach(function (directive) {
  10957. _resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  10958. _resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  10959. });
  10960. return providersByToken;
  10961. }
  10962. function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
  10963. providers.forEach(function (provider) {
  10964. var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
  10965. if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
  10966. targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
  10967. }
  10968. if (!resolvedProvider) {
  10969. var lifecycleHooks = provider.token.identifier &&
  10970. provider.token.identifier.lifecycleHooks ?
  10971. provider.token.identifier.lifecycleHooks :
  10972. [];
  10973. var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
  10974. resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
  10975. targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
  10976. }
  10977. else {
  10978. if (!provider.multi) {
  10979. resolvedProvider.providers.length = 0;
  10980. }
  10981. resolvedProvider.providers.push(provider);
  10982. }
  10983. });
  10984. }
  10985. function _getViewQueries(component) {
  10986. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  10987. var viewQueryId = 1;
  10988. var viewQueries = new Map();
  10989. if (component.viewQueries) {
  10990. component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
  10991. }
  10992. return viewQueries;
  10993. }
  10994. function _getContentQueries(contentQueryStartId, directives) {
  10995. var contentQueryId = contentQueryStartId;
  10996. var contentQueries = new Map();
  10997. directives.forEach(function (directive, directiveIndex) {
  10998. if (directive.queries) {
  10999. directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
  11000. }
  11001. });
  11002. return contentQueries;
  11003. }
  11004. function _addQueryToTokenMap(map, query) {
  11005. query.meta.selectors.forEach(function (token) {
  11006. var entry = map.get(tokenReference(token));
  11007. if (!entry) {
  11008. entry = [];
  11009. map.set(tokenReference(token), entry);
  11010. }
  11011. entry.push(query);
  11012. });
  11013. }
  11014. /**
  11015. * @license
  11016. * Copyright Google Inc. All Rights Reserved.
  11017. *
  11018. * Use of this source code is governed by an MIT-style license that can be
  11019. * found in the LICENSE file at https://angular.io/license
  11020. */
  11021. var StyleWithImports = /** @class */ (function () {
  11022. function StyleWithImports(style, styleUrls) {
  11023. this.style = style;
  11024. this.styleUrls = styleUrls;
  11025. }
  11026. return StyleWithImports;
  11027. }());
  11028. function isStyleUrlResolvable(url) {
  11029. if (url == null || url.length === 0 || url[0] == '/')
  11030. return false;
  11031. var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
  11032. return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
  11033. }
  11034. /**
  11035. * Rewrites stylesheets by resolving and removing the @import urls that
  11036. * are either relative or don't have a `package:` scheme
  11037. */
  11038. function extractStyleUrls(resolver, baseUrl, cssText) {
  11039. var foundUrls = [];
  11040. var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
  11041. .replace(CSS_IMPORT_REGEXP, function () {
  11042. var m = [];
  11043. for (var _i = 0; _i < arguments.length; _i++) {
  11044. m[_i] = arguments[_i];
  11045. }
  11046. var url = m[1] || m[2];
  11047. if (!isStyleUrlResolvable(url)) {
  11048. // Do not attempt to resolve non-package absolute URLs with URI
  11049. // scheme
  11050. return m[0];
  11051. }
  11052. foundUrls.push(resolver.resolve(baseUrl, url));
  11053. return '';
  11054. });
  11055. return new StyleWithImports(modifiedCssText, foundUrls);
  11056. }
  11057. var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
  11058. var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
  11059. var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
  11060. /**
  11061. * @license
  11062. * Copyright Google Inc. All Rights Reserved.
  11063. *
  11064. * Use of this source code is governed by an MIT-style license that can be
  11065. * found in the LICENSE file at https://angular.io/license
  11066. */
  11067. var PROPERTY_PARTS_SEPARATOR = '.';
  11068. var ATTRIBUTE_PREFIX = 'attr';
  11069. var CLASS_PREFIX = 'class';
  11070. var STYLE_PREFIX = 'style';
  11071. var ANIMATE_PROP_PREFIX = 'animate-';
  11072. /**
  11073. * Parses bindings in templates and in the directive host area.
  11074. */
  11075. var BindingParser = /** @class */ (function () {
  11076. function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
  11077. this._exprParser = _exprParser;
  11078. this._interpolationConfig = _interpolationConfig;
  11079. this._schemaRegistry = _schemaRegistry;
  11080. this.errors = errors;
  11081. this.pipesByName = null;
  11082. this._usedPipes = new Map();
  11083. // When the `pipes` parameter is `null`, do not check for used pipes
  11084. // This is used in IVY when we might not know the available pipes at compile time
  11085. if (pipes) {
  11086. var pipesByName_1 = new Map();
  11087. pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); });
  11088. this.pipesByName = pipesByName_1;
  11089. }
  11090. }
  11091. Object.defineProperty(BindingParser.prototype, "interpolationConfig", {
  11092. get: function () { return this._interpolationConfig; },
  11093. enumerable: true,
  11094. configurable: true
  11095. });
  11096. BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); };
  11097. BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) {
  11098. var _this = this;
  11099. if (dirMeta.hostProperties) {
  11100. var boundProps_1 = [];
  11101. Object.keys(dirMeta.hostProperties).forEach(function (propName) {
  11102. var expression = dirMeta.hostProperties[propName];
  11103. if (typeof expression === 'string') {
  11104. _this.parsePropertyBinding(propName, expression, true, sourceSpan, [], boundProps_1);
  11105. }
  11106. else {
  11107. _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  11108. }
  11109. });
  11110. return boundProps_1;
  11111. }
  11112. return null;
  11113. };
  11114. BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) {
  11115. var _this = this;
  11116. var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
  11117. return boundProps &&
  11118. boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); });
  11119. };
  11120. BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) {
  11121. var _this = this;
  11122. if (dirMeta.hostListeners) {
  11123. var targetEvents_1 = [];
  11124. Object.keys(dirMeta.hostListeners).forEach(function (propName) {
  11125. var expression = dirMeta.hostListeners[propName];
  11126. if (typeof expression === 'string') {
  11127. // TODO: pass a more accurate handlerSpan for this event.
  11128. _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1);
  11129. }
  11130. else {
  11131. _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  11132. }
  11133. });
  11134. return targetEvents_1;
  11135. }
  11136. return null;
  11137. };
  11138. BindingParser.prototype.parseInterpolation = function (value, sourceSpan) {
  11139. var sourceInfo = sourceSpan.start.toString();
  11140. try {
  11141. var ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig);
  11142. if (ast)
  11143. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11144. this._checkPipes(ast, sourceSpan);
  11145. return ast;
  11146. }
  11147. catch (e) {
  11148. this._reportError("" + e, sourceSpan);
  11149. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11150. }
  11151. };
  11152. // Parse an inline template binding. ie `<tag *tplKey="<tplValue>">`
  11153. BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, targetMatchableAttrs, targetProps, targetVars) {
  11154. var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan);
  11155. for (var i = 0; i < bindings.length; i++) {
  11156. var binding = bindings[i];
  11157. if (binding.keyIsVar) {
  11158. targetVars.push(new ParsedVariable(binding.key, binding.name, sourceSpan));
  11159. }
  11160. else if (binding.expression) {
  11161. this._parsePropertyAst(binding.key, binding.expression, sourceSpan, targetMatchableAttrs, targetProps);
  11162. }
  11163. else {
  11164. targetMatchableAttrs.push([binding.key, '']);
  11165. this.parseLiteralAttr(binding.key, null, sourceSpan, targetMatchableAttrs, targetProps);
  11166. }
  11167. }
  11168. };
  11169. BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan) {
  11170. var _this = this;
  11171. var sourceInfo = sourceSpan.start.toString();
  11172. try {
  11173. var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo);
  11174. this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
  11175. bindingsResult.templateBindings.forEach(function (binding) {
  11176. if (binding.expression) {
  11177. _this._checkPipes(binding.expression, sourceSpan);
  11178. }
  11179. });
  11180. bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); });
  11181. return bindingsResult.templateBindings;
  11182. }
  11183. catch (e) {
  11184. this._reportError("" + e, sourceSpan);
  11185. return [];
  11186. }
  11187. };
  11188. BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  11189. if (isAnimationLabel(name)) {
  11190. name = name.substring(1);
  11191. if (value) {
  11192. this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." +
  11193. " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, ParseErrorLevel.ERROR);
  11194. }
  11195. this._parseAnimation(name, value, sourceSpan, targetMatchableAttrs, targetProps);
  11196. }
  11197. else {
  11198. targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), ParsedPropertyType.LITERAL_ATTR, sourceSpan));
  11199. }
  11200. };
  11201. BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, targetMatchableAttrs, targetProps) {
  11202. var isAnimationProp = false;
  11203. if (name.startsWith(ANIMATE_PROP_PREFIX)) {
  11204. isAnimationProp = true;
  11205. name = name.substring(ANIMATE_PROP_PREFIX.length);
  11206. }
  11207. else if (isAnimationLabel(name)) {
  11208. isAnimationProp = true;
  11209. name = name.substring(1);
  11210. }
  11211. if (isAnimationProp) {
  11212. this._parseAnimation(name, expression, sourceSpan, targetMatchableAttrs, targetProps);
  11213. }
  11214. else {
  11215. this._parsePropertyAst(name, this._parseBinding(expression, isHost, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps);
  11216. }
  11217. };
  11218. BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  11219. var expr = this.parseInterpolation(value, sourceSpan);
  11220. if (expr) {
  11221. this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
  11222. return true;
  11223. }
  11224. return false;
  11225. };
  11226. BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, targetMatchableAttrs, targetProps) {
  11227. targetMatchableAttrs.push([name, ast.source]);
  11228. targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.DEFAULT, sourceSpan));
  11229. };
  11230. BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, targetMatchableAttrs, targetProps) {
  11231. // This will occur when a @trigger is not paired with an expression.
  11232. // For animations it is valid to not have an expression since */void
  11233. // states will be applied by angular when the element is attached/detached
  11234. var ast = this._parseBinding(expression || 'undefined', false, sourceSpan);
  11235. targetMatchableAttrs.push([name, ast.source]);
  11236. targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan));
  11237. };
  11238. BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan) {
  11239. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
  11240. try {
  11241. var ast = isHostBinding ?
  11242. this._exprParser.parseSimpleBinding(value, sourceInfo, this._interpolationConfig) :
  11243. this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig);
  11244. if (ast)
  11245. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11246. this._checkPipes(ast, sourceSpan);
  11247. return ast;
  11248. }
  11249. catch (e) {
  11250. this._reportError("" + e, sourceSpan);
  11251. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11252. }
  11253. };
  11254. BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) {
  11255. if (skipValidation === void 0) { skipValidation = false; }
  11256. if (mapPropertyName === void 0) { mapPropertyName = true; }
  11257. if (boundProp.isAnimation) {
  11258. return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan);
  11259. }
  11260. var unit = null;
  11261. var bindingType = undefined;
  11262. var boundPropertyName = null;
  11263. var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  11264. var securityContexts = undefined;
  11265. // Check for special cases (prefix style, attr, class)
  11266. if (parts.length > 1) {
  11267. if (parts[0] == ATTRIBUTE_PREFIX) {
  11268. boundPropertyName = parts[1];
  11269. if (!skipValidation) {
  11270. this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
  11271. }
  11272. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
  11273. var nsSeparatorIdx = boundPropertyName.indexOf(':');
  11274. if (nsSeparatorIdx > -1) {
  11275. var ns = boundPropertyName.substring(0, nsSeparatorIdx);
  11276. var name_1 = boundPropertyName.substring(nsSeparatorIdx + 1);
  11277. boundPropertyName = mergeNsAndName(ns, name_1);
  11278. }
  11279. bindingType = 1 /* Attribute */;
  11280. }
  11281. else if (parts[0] == CLASS_PREFIX) {
  11282. boundPropertyName = parts[1];
  11283. bindingType = 2 /* Class */;
  11284. securityContexts = [SecurityContext.NONE];
  11285. }
  11286. else if (parts[0] == STYLE_PREFIX) {
  11287. unit = parts.length > 2 ? parts[2] : null;
  11288. boundPropertyName = parts[1];
  11289. bindingType = 3 /* Style */;
  11290. securityContexts = [SecurityContext.STYLE];
  11291. }
  11292. }
  11293. // If not a special case, use the full property name
  11294. if (boundPropertyName === null) {
  11295. var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
  11296. boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
  11297. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
  11298. bindingType = 0 /* Property */;
  11299. if (!skipValidation) {
  11300. this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
  11301. }
  11302. }
  11303. return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan);
  11304. };
  11305. BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  11306. if (isAnimationLabel(name)) {
  11307. name = name.substr(1);
  11308. this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents);
  11309. }
  11310. else {
  11311. this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents);
  11312. }
  11313. };
  11314. BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) {
  11315. var prop = this._schemaRegistry.getMappedPropName(propName);
  11316. return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
  11317. };
  11318. BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents) {
  11319. var matches = splitAtPeriod(name, [name, '']);
  11320. var eventName = matches[0];
  11321. var phase = matches[1].toLowerCase();
  11322. if (phase) {
  11323. switch (phase) {
  11324. case 'start':
  11325. case 'done':
  11326. var ast = this._parseAction(expression, handlerSpan);
  11327. targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan));
  11328. break;
  11329. default:
  11330. this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan);
  11331. break;
  11332. }
  11333. }
  11334. else {
  11335. this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan);
  11336. }
  11337. };
  11338. BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  11339. // long format: 'target: eventName'
  11340. var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1];
  11341. var ast = this._parseAction(expression, handlerSpan);
  11342. targetMatchableAttrs.push([name, ast.source]);
  11343. targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan));
  11344. // Don't detect directives for event names for now,
  11345. // so don't add the event name to the matchableAttrs
  11346. };
  11347. BindingParser.prototype._parseAction = function (value, sourceSpan) {
  11348. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
  11349. try {
  11350. var ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig);
  11351. if (ast) {
  11352. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11353. }
  11354. if (!ast || ast.ast instanceof EmptyExpr) {
  11355. this._reportError("Empty expressions are not allowed", sourceSpan);
  11356. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11357. }
  11358. this._checkPipes(ast, sourceSpan);
  11359. return ast;
  11360. }
  11361. catch (e) {
  11362. this._reportError("" + e, sourceSpan);
  11363. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11364. }
  11365. };
  11366. BindingParser.prototype._reportError = function (message, sourceSpan, level) {
  11367. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  11368. this.errors.push(new ParseError(sourceSpan, message, level));
  11369. };
  11370. BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) {
  11371. var e_1, _a;
  11372. try {
  11373. for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) {
  11374. var error = errors_1_1.value;
  11375. this._reportError(error.message, sourceSpan);
  11376. }
  11377. }
  11378. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  11379. finally {
  11380. try {
  11381. if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1);
  11382. }
  11383. finally { if (e_1) throw e_1.error; }
  11384. }
  11385. };
  11386. // Make sure all the used pipes are known in `this.pipesByName`
  11387. BindingParser.prototype._checkPipes = function (ast, sourceSpan) {
  11388. var _this = this;
  11389. if (ast && this.pipesByName) {
  11390. var collector = new PipeCollector();
  11391. ast.visit(collector);
  11392. collector.pipes.forEach(function (ast, pipeName) {
  11393. var pipeMeta = _this.pipesByName.get(pipeName);
  11394. if (!pipeMeta) {
  11395. _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
  11396. }
  11397. else {
  11398. _this._usedPipes.set(pipeName, pipeMeta);
  11399. }
  11400. });
  11401. }
  11402. };
  11403. /**
  11404. * @param propName the name of the property / attribute
  11405. * @param sourceSpan
  11406. * @param isAttr true when binding to an attribute
  11407. */
  11408. BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) {
  11409. var report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
  11410. this._schemaRegistry.validateProperty(propName);
  11411. if (report.error) {
  11412. this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR);
  11413. }
  11414. };
  11415. return BindingParser;
  11416. }());
  11417. var PipeCollector = /** @class */ (function (_super) {
  11418. __extends(PipeCollector, _super);
  11419. function PipeCollector() {
  11420. var _this = _super !== null && _super.apply(this, arguments) || this;
  11421. _this.pipes = new Map();
  11422. return _this;
  11423. }
  11424. PipeCollector.prototype.visitPipe = function (ast, context) {
  11425. this.pipes.set(ast.name, ast);
  11426. ast.exp.visit(this);
  11427. this.visitAll(ast.args, context);
  11428. return null;
  11429. };
  11430. return PipeCollector;
  11431. }(RecursiveAstVisitor$1));
  11432. function isAnimationLabel(name) {
  11433. return name[0] == '@';
  11434. }
  11435. function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
  11436. var ctxs = [];
  11437. CssSelector.parse(selector).forEach(function (selector) {
  11438. var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
  11439. var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); })
  11440. .map(function (selector) { return selector.element; }));
  11441. var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); });
  11442. ctxs.push.apply(ctxs, __spread(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); })));
  11443. });
  11444. return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
  11445. }
  11446. /**
  11447. * @license
  11448. * Copyright Google Inc. All Rights Reserved.
  11449. *
  11450. * Use of this source code is governed by an MIT-style license that can be
  11451. * found in the LICENSE file at https://angular.io/license
  11452. */
  11453. var NG_CONTENT_SELECT_ATTR = 'select';
  11454. var LINK_ELEMENT = 'link';
  11455. var LINK_STYLE_REL_ATTR = 'rel';
  11456. var LINK_STYLE_HREF_ATTR = 'href';
  11457. var LINK_STYLE_REL_VALUE = 'stylesheet';
  11458. var STYLE_ELEMENT = 'style';
  11459. var SCRIPT_ELEMENT = 'script';
  11460. var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
  11461. var NG_PROJECT_AS = 'ngProjectAs';
  11462. function preparseElement(ast) {
  11463. var selectAttr = null;
  11464. var hrefAttr = null;
  11465. var relAttr = null;
  11466. var nonBindable = false;
  11467. var projectAs = '';
  11468. ast.attrs.forEach(function (attr) {
  11469. var lcAttrName = attr.name.toLowerCase();
  11470. if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
  11471. selectAttr = attr.value;
  11472. }
  11473. else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
  11474. hrefAttr = attr.value;
  11475. }
  11476. else if (lcAttrName == LINK_STYLE_REL_ATTR) {
  11477. relAttr = attr.value;
  11478. }
  11479. else if (attr.name == NG_NON_BINDABLE_ATTR) {
  11480. nonBindable = true;
  11481. }
  11482. else if (attr.name == NG_PROJECT_AS) {
  11483. if (attr.value.length > 0) {
  11484. projectAs = attr.value;
  11485. }
  11486. }
  11487. });
  11488. selectAttr = normalizeNgContentSelect(selectAttr);
  11489. var nodeName = ast.name.toLowerCase();
  11490. var type = PreparsedElementType.OTHER;
  11491. if (isNgContent(nodeName)) {
  11492. type = PreparsedElementType.NG_CONTENT;
  11493. }
  11494. else if (nodeName == STYLE_ELEMENT) {
  11495. type = PreparsedElementType.STYLE;
  11496. }
  11497. else if (nodeName == SCRIPT_ELEMENT) {
  11498. type = PreparsedElementType.SCRIPT;
  11499. }
  11500. else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
  11501. type = PreparsedElementType.STYLESHEET;
  11502. }
  11503. return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
  11504. }
  11505. var PreparsedElementType;
  11506. (function (PreparsedElementType) {
  11507. PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
  11508. PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
  11509. PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
  11510. PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
  11511. PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
  11512. })(PreparsedElementType || (PreparsedElementType = {}));
  11513. var PreparsedElement = /** @class */ (function () {
  11514. function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) {
  11515. this.type = type;
  11516. this.selectAttr = selectAttr;
  11517. this.hrefAttr = hrefAttr;
  11518. this.nonBindable = nonBindable;
  11519. this.projectAs = projectAs;
  11520. }
  11521. return PreparsedElement;
  11522. }());
  11523. function normalizeNgContentSelect(selectAttr) {
  11524. if (selectAttr === null || selectAttr.length === 0) {
  11525. return '*';
  11526. }
  11527. return selectAttr;
  11528. }
  11529. /**
  11530. * @license
  11531. * Copyright Google Inc. All Rights Reserved.
  11532. *
  11533. * Use of this source code is governed by an MIT-style license that can be
  11534. * found in the LICENSE file at https://angular.io/license
  11535. */
  11536. var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  11537. // Group 1 = "bind-"
  11538. var KW_BIND_IDX = 1;
  11539. // Group 2 = "let-"
  11540. var KW_LET_IDX = 2;
  11541. // Group 3 = "ref-/#"
  11542. var KW_REF_IDX = 3;
  11543. // Group 4 = "on-"
  11544. var KW_ON_IDX = 4;
  11545. // Group 5 = "bindon-"
  11546. var KW_BINDON_IDX = 5;
  11547. // Group 6 = "@"
  11548. var KW_AT_IDX = 6;
  11549. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  11550. var IDENT_KW_IDX = 7;
  11551. // Group 8 = identifier inside [()]
  11552. var IDENT_BANANA_BOX_IDX = 8;
  11553. // Group 9 = identifier inside []
  11554. var IDENT_PROPERTY_IDX = 9;
  11555. // Group 10 = identifier inside ()
  11556. var IDENT_EVENT_IDX = 10;
  11557. var TEMPLATE_ATTR_PREFIX = '*';
  11558. var CLASS_ATTR = 'class';
  11559. var _TEXT_CSS_SELECTOR;
  11560. function TEXT_CSS_SELECTOR() {
  11561. if (!_TEXT_CSS_SELECTOR) {
  11562. _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
  11563. }
  11564. return _TEXT_CSS_SELECTOR;
  11565. }
  11566. var TemplateParseError = /** @class */ (function (_super) {
  11567. __extends(TemplateParseError, _super);
  11568. function TemplateParseError(message, span, level) {
  11569. return _super.call(this, span, message, level) || this;
  11570. }
  11571. return TemplateParseError;
  11572. }(ParseError));
  11573. var TemplateParseResult = /** @class */ (function () {
  11574. function TemplateParseResult(templateAst, usedPipes, errors) {
  11575. this.templateAst = templateAst;
  11576. this.usedPipes = usedPipes;
  11577. this.errors = errors;
  11578. }
  11579. return TemplateParseResult;
  11580. }());
  11581. var TemplateParser = /** @class */ (function () {
  11582. function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
  11583. this._config = _config;
  11584. this._reflector = _reflector;
  11585. this._exprParser = _exprParser;
  11586. this._schemaRegistry = _schemaRegistry;
  11587. this._htmlParser = _htmlParser;
  11588. this._console = _console;
  11589. this.transforms = transforms;
  11590. }
  11591. Object.defineProperty(TemplateParser.prototype, "expressionParser", {
  11592. get: function () { return this._exprParser; },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11597. var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
  11598. var warnings = result.errors.filter(function (error) { return error.level === ParseErrorLevel.WARNING; });
  11599. var errors = result.errors.filter(function (error) { return error.level === ParseErrorLevel.ERROR; });
  11600. if (warnings.length > 0) {
  11601. this._console.warn("Template parse warnings:\n" + warnings.join('\n'));
  11602. }
  11603. if (errors.length > 0) {
  11604. var errorString = errors.join('\n');
  11605. throw syntaxError("Template parse errors:\n" + errorString, errors);
  11606. }
  11607. return { template: result.templateAst, pipes: result.usedPipes };
  11608. };
  11609. TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11610. var htmlParseResult = typeof template === 'string' ?
  11611. this._htmlParser.parse(template, templateUrl, {
  11612. tokenizeExpansionForms: true,
  11613. interpolationConfig: this.getInterpolationConfig(component)
  11614. }) :
  11615. template;
  11616. if (!preserveWhitespaces) {
  11617. htmlParseResult = removeWhitespaces(htmlParseResult);
  11618. }
  11619. return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
  11620. };
  11621. TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) {
  11622. var result;
  11623. var errors = htmlAstWithErrors.errors;
  11624. var usedPipes = [];
  11625. if (htmlAstWithErrors.rootNodes.length > 0) {
  11626. var uniqDirectives = removeSummaryDuplicates(directives);
  11627. var uniqPipes = removeSummaryDuplicates(pipes);
  11628. var providerViewContext = new ProviderViewContext(this._reflector, component);
  11629. var interpolationConfig = undefined;
  11630. if (component.template && component.template.interpolation) {
  11631. interpolationConfig = {
  11632. start: component.template.interpolation[0],
  11633. end: component.template.interpolation[1]
  11634. };
  11635. }
  11636. var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
  11637. var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
  11638. result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
  11639. errors.push.apply(errors, __spread(providerViewContext.errors));
  11640. usedPipes.push.apply(usedPipes, __spread(bindingParser.getUsedPipes()));
  11641. }
  11642. else {
  11643. result = [];
  11644. }
  11645. this._assertNoReferenceDuplicationOnTemplate(result, errors);
  11646. if (errors.length > 0) {
  11647. return new TemplateParseResult(result, usedPipes, errors);
  11648. }
  11649. if (this.transforms) {
  11650. this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); });
  11651. }
  11652. return new TemplateParseResult(result, usedPipes, errors);
  11653. };
  11654. TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) {
  11655. if (forced === void 0) { forced = false; }
  11656. var errors = htmlAstWithErrors.errors;
  11657. if (errors.length == 0 || forced) {
  11658. // Transform ICU messages to angular directives
  11659. var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
  11660. errors.push.apply(errors, __spread(expandedHtmlAst.errors));
  11661. htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
  11662. }
  11663. return htmlAstWithErrors;
  11664. };
  11665. TemplateParser.prototype.getInterpolationConfig = function (component) {
  11666. if (component.template) {
  11667. return InterpolationConfig.fromArray(component.template.interpolation);
  11668. }
  11669. return undefined;
  11670. };
  11671. /** @internal */
  11672. TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) {
  11673. var existingReferences = [];
  11674. result.filter(function (element) { return !!element.references; })
  11675. .forEach(function (element) { return element.references.forEach(function (reference) {
  11676. var name = reference.name;
  11677. if (existingReferences.indexOf(name) < 0) {
  11678. existingReferences.push(name);
  11679. }
  11680. else {
  11681. var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, ParseErrorLevel.ERROR);
  11682. errors.push(error);
  11683. }
  11684. }); });
  11685. };
  11686. return TemplateParser;
  11687. }());
  11688. var TemplateParseVisitor = /** @class */ (function () {
  11689. function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
  11690. var _this = this;
  11691. this.reflector = reflector;
  11692. this.config = config;
  11693. this.providerViewContext = providerViewContext;
  11694. this._bindingParser = _bindingParser;
  11695. this._schemaRegistry = _schemaRegistry;
  11696. this._schemas = _schemas;
  11697. this._targetErrors = _targetErrors;
  11698. this.selectorMatcher = new SelectorMatcher();
  11699. this.directivesIndex = new Map();
  11700. this.ngContentCount = 0;
  11701. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  11702. this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
  11703. directives.forEach(function (directive, index) {
  11704. var selector = CssSelector.parse(directive.selector);
  11705. _this.selectorMatcher.addSelectables(selector, directive);
  11706. _this.directivesIndex.set(directive, index);
  11707. });
  11708. }
  11709. TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; };
  11710. TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; };
  11711. TemplateParseVisitor.prototype.visitText = function (text, parent) {
  11712. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  11713. var valueNoNgsp = replaceNgsp(text.value);
  11714. var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
  11715. return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
  11716. new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
  11717. };
  11718. TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) {
  11719. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  11720. };
  11721. TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; };
  11722. TemplateParseVisitor.prototype.visitElement = function (element, parent) {
  11723. var _this = this;
  11724. var queryStartIndex = this.contentQueryStartId;
  11725. var elName = element.name;
  11726. var preparsedElement = preparseElement(element);
  11727. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  11728. preparsedElement.type === PreparsedElementType.STYLE) {
  11729. // Skipping <script> for security reasons
  11730. // Skipping <style> as we already processed them
  11731. // in the StyleCompiler
  11732. return null;
  11733. }
  11734. if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  11735. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  11736. // Skipping stylesheets with either relative urls or package scheme as we already processed
  11737. // them in the StyleCompiler
  11738. return null;
  11739. }
  11740. var matchableAttrs = [];
  11741. var elementOrDirectiveProps = [];
  11742. var elementOrDirectiveRefs = [];
  11743. var elementVars = [];
  11744. var events = [];
  11745. var templateElementOrDirectiveProps = [];
  11746. var templateMatchableAttrs = [];
  11747. var templateElementVars = [];
  11748. var hasInlineTemplates = false;
  11749. var attrs = [];
  11750. var isTemplateElement = isNgTemplate(element.name);
  11751. element.attrs.forEach(function (attr) {
  11752. var parsedVariables = [];
  11753. var hasBinding = _this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
  11754. elementVars.push.apply(elementVars, __spread(parsedVariables.map(function (v) { return VariableAst.fromParsedVariable(v); })));
  11755. var templateValue;
  11756. var templateKey;
  11757. var normalizedName = _this._normalizeAttributeName(attr.name);
  11758. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
  11759. templateValue = attr.value;
  11760. templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
  11761. }
  11762. var hasTemplateBinding = templateValue != null;
  11763. if (hasTemplateBinding) {
  11764. if (hasInlineTemplates) {
  11765. _this._reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attr.sourceSpan);
  11766. }
  11767. hasInlineTemplates = true;
  11768. var parsedVariables_1 = [];
  11769. _this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables_1);
  11770. templateElementVars.push.apply(templateElementVars, __spread(parsedVariables_1.map(function (v) { return VariableAst.fromParsedVariable(v); })));
  11771. }
  11772. if (!hasBinding && !hasTemplateBinding) {
  11773. // don't include the bindings as attributes as well in the AST
  11774. attrs.push(_this.visitAttribute(attr, null));
  11775. matchableAttrs.push([attr.name, attr.value]);
  11776. }
  11777. });
  11778. var elementCssSelector = createElementCssSelector(elName, matchableAttrs);
  11779. var _a = this._parseDirectives(this.selectorMatcher, elementCssSelector), directiveMetas = _a.directives, matchElement = _a.matchElement;
  11780. var references = [];
  11781. var boundDirectivePropNames = new Set();
  11782. var directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
  11783. var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
  11784. var isViewRoot = parent.isTemplateElement || hasInlineTemplates;
  11785. var providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
  11786. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
  11787. providerContext.afterElement();
  11788. // Override the actual selector when the `ngProjectAs` attribute is provided
  11789. var projectionSelector = preparsedElement.projectAs != '' ?
  11790. CssSelector.parse(preparsedElement.projectAs)[0] :
  11791. elementCssSelector;
  11792. var ngContentIndex = parent.findNgContentIndex(projectionSelector);
  11793. var parsedElement;
  11794. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  11795. // `<ng-content>` element
  11796. if (element.children && !element.children.every(_isEmptyTextNode)) {
  11797. this._reportError("<ng-content> element cannot have content.", element.sourceSpan);
  11798. }
  11799. parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  11800. }
  11801. else if (isTemplateElement) {
  11802. // `<ng-template>` element
  11803. this._assertAllEventsPublishedByDirectives(directiveAsts, events);
  11804. this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
  11805. parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  11806. }
  11807. else {
  11808. // element other than `<ng-content>` and `<ng-template>`
  11809. this._assertElementExists(matchElement, element);
  11810. this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
  11811. var ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
  11812. parsedElement = new ElementAst(elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex_1, element.sourceSpan, element.endSourceSpan || null);
  11813. }
  11814. if (hasInlineTemplates) {
  11815. // The element as a *-attribute
  11816. var templateQueryStartIndex = this.contentQueryStartId;
  11817. var templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
  11818. var directives = this._parseDirectives(this.selectorMatcher, templateSelector).directives;
  11819. var templateBoundDirectivePropNames = new Set();
  11820. var templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
  11821. var templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
  11822. this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
  11823. var templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
  11824. templateProviderContext.afterElement();
  11825. parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
  11826. }
  11827. return parsedElement;
  11828. };
  11829. TemplateParseVisitor.prototype._parseAttr = function (isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
  11830. var name = this._normalizeAttributeName(attr.name);
  11831. var value = attr.value;
  11832. var srcSpan = attr.sourceSpan;
  11833. var boundEvents = [];
  11834. var bindParts = name.match(BIND_NAME_REGEXP);
  11835. var hasBinding = false;
  11836. if (bindParts !== null) {
  11837. hasBinding = true;
  11838. if (bindParts[KW_BIND_IDX] != null) {
  11839. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11840. }
  11841. else if (bindParts[KW_LET_IDX]) {
  11842. if (isTemplateElement) {
  11843. var identifier = bindParts[IDENT_KW_IDX];
  11844. this._parseVariable(identifier, value, srcSpan, targetVars);
  11845. }
  11846. else {
  11847. this._reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  11848. }
  11849. }
  11850. else if (bindParts[KW_REF_IDX]) {
  11851. var identifier = bindParts[IDENT_KW_IDX];
  11852. this._parseReference(identifier, value, srcSpan, targetRefs);
  11853. }
  11854. else if (bindParts[KW_ON_IDX]) {
  11855. this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11856. }
  11857. else if (bindParts[KW_BINDON_IDX]) {
  11858. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11859. this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11860. }
  11861. else if (bindParts[KW_AT_IDX]) {
  11862. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  11863. }
  11864. else if (bindParts[IDENT_BANANA_BOX_IDX]) {
  11865. this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11866. this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11867. }
  11868. else if (bindParts[IDENT_PROPERTY_IDX]) {
  11869. this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11870. }
  11871. else if (bindParts[IDENT_EVENT_IDX]) {
  11872. this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11873. }
  11874. }
  11875. else {
  11876. hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, targetMatchableAttrs, targetProps);
  11877. }
  11878. if (!hasBinding) {
  11879. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  11880. }
  11881. targetEvents.push.apply(targetEvents, __spread(boundEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); })));
  11882. return hasBinding;
  11883. };
  11884. TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
  11885. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  11886. };
  11887. TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
  11888. if (identifier.indexOf('-') > -1) {
  11889. this._reportError("\"-\" is not allowed in variable names", sourceSpan);
  11890. }
  11891. targetVars.push(new VariableAst(identifier, value, sourceSpan));
  11892. };
  11893. TemplateParseVisitor.prototype._parseReference = function (identifier, value, sourceSpan, targetRefs) {
  11894. if (identifier.indexOf('-') > -1) {
  11895. this._reportError("\"-\" is not allowed in reference names", sourceSpan);
  11896. }
  11897. targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
  11898. };
  11899. TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
  11900. this._bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
  11901. };
  11902. TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
  11903. var _this = this;
  11904. // Need to sort the directives so that we get consistent results throughout,
  11905. // as selectorMatcher uses Maps inside.
  11906. // Also deduplicate directives as they might match more than one time!
  11907. var directives = new Array(this.directivesIndex.size);
  11908. // Whether any directive selector matches on the element name
  11909. var matchElement = false;
  11910. selectorMatcher.match(elementCssSelector, function (selector, directive) {
  11911. directives[_this.directivesIndex.get(directive)] = directive;
  11912. matchElement = matchElement || selector.hasElementSelector();
  11913. });
  11914. return {
  11915. directives: directives.filter(function (dir) { return !!dir; }),
  11916. matchElement: matchElement,
  11917. };
  11918. };
  11919. TemplateParseVisitor.prototype._createDirectiveAsts = function (isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
  11920. var _this = this;
  11921. var matchedReferences = new Set();
  11922. var component = null;
  11923. var directiveAsts = directives.map(function (directive) {
  11924. var sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, "Directive " + identifierName(directive.type));
  11925. if (directive.isComponent) {
  11926. component = directive;
  11927. }
  11928. var directiveProperties = [];
  11929. var boundProperties = _this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
  11930. var hostProperties = boundProperties.map(function (prop) { return BoundElementPropertyAst.fromBoundProperty(prop); });
  11931. // Note: We need to check the host properties here as well,
  11932. // as we don't know the element name in the DirectiveWrapperCompiler yet.
  11933. hostProperties = _this._checkPropertiesInSchema(elementName, hostProperties);
  11934. var parsedEvents = _this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
  11935. _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
  11936. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  11937. if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
  11938. (elOrDirRef.isReferenceToDirective(directive))) {
  11939. targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
  11940. matchedReferences.add(elOrDirRef.name);
  11941. }
  11942. });
  11943. var hostEvents = parsedEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); });
  11944. var contentQueryStartId = _this.contentQueryStartId;
  11945. _this.contentQueryStartId += directive.queries.length;
  11946. return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
  11947. });
  11948. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  11949. if (elOrDirRef.value.length > 0) {
  11950. if (!matchedReferences.has(elOrDirRef.name)) {
  11951. _this._reportError("There is no directive with \"exportAs\" set to \"" + elOrDirRef.value + "\"", elOrDirRef.sourceSpan);
  11952. }
  11953. }
  11954. else if (!component) {
  11955. var refToken = null;
  11956. if (isTemplateElement) {
  11957. refToken = createTokenForExternalReference(_this.reflector, Identifiers.TemplateRef);
  11958. }
  11959. targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
  11960. }
  11961. });
  11962. return directiveAsts;
  11963. };
  11964. TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
  11965. if (directiveProperties) {
  11966. var boundPropsByName_1 = new Map();
  11967. boundProps.forEach(function (boundProp) {
  11968. var prevValue = boundPropsByName_1.get(boundProp.name);
  11969. if (!prevValue || prevValue.isLiteral) {
  11970. // give [a]="b" a higher precedence than a="b" on the same element
  11971. boundPropsByName_1.set(boundProp.name, boundProp);
  11972. }
  11973. });
  11974. Object.keys(directiveProperties).forEach(function (dirProp) {
  11975. var elProp = directiveProperties[dirProp];
  11976. var boundProp = boundPropsByName_1.get(elProp);
  11977. // Bindings are optional, so this binding only needs to be set up if an expression is given.
  11978. if (boundProp) {
  11979. targetBoundDirectivePropNames.add(boundProp.name);
  11980. if (!isEmptyExpression(boundProp.expression)) {
  11981. targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
  11982. }
  11983. }
  11984. });
  11985. }
  11986. };
  11987. TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, boundDirectivePropNames) {
  11988. var _this = this;
  11989. var boundElementProps = [];
  11990. props.forEach(function (prop) {
  11991. if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
  11992. var boundProp = _this._bindingParser.createBoundElementProperty(elementName, prop);
  11993. boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
  11994. }
  11995. });
  11996. return this._checkPropertiesInSchema(elementName, boundElementProps);
  11997. };
  11998. TemplateParseVisitor.prototype._findComponentDirectives = function (directives) {
  11999. return directives.filter(function (directive) { return directive.directive.isComponent; });
  12000. };
  12001. TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
  12002. return this._findComponentDirectives(directives)
  12003. .map(function (directive) { return identifierName(directive.directive.type); });
  12004. };
  12005. TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
  12006. var componentTypeNames = this._findComponentDirectiveNames(directives);
  12007. if (componentTypeNames.length > 1) {
  12008. this._reportError("More than one component matched on this element.\n" +
  12009. "Make sure that only one component's selector can match a given element.\n" +
  12010. ("Conflicting components: " + componentTypeNames.join(',')), sourceSpan);
  12011. }
  12012. };
  12013. /**
  12014. * Make sure that non-angular tags conform to the schemas.
  12015. *
  12016. * Note: An element is considered an angular tag when at least one directive selector matches the
  12017. * tag name.
  12018. *
  12019. * @param matchElement Whether any directive has matched on the tag name
  12020. * @param element the html element
  12021. */
  12022. TemplateParseVisitor.prototype._assertElementExists = function (matchElement, element) {
  12023. var elName = element.name.replace(/^:xhtml:/, '');
  12024. if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
  12025. var errorMsg = "'" + elName + "' is not a known element:\n";
  12026. errorMsg +=
  12027. "1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n";
  12028. if (elName.indexOf('-') > -1) {
  12029. errorMsg +=
  12030. "2. If '" + elName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.";
  12031. }
  12032. else {
  12033. errorMsg +=
  12034. "2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12035. }
  12036. this._reportError(errorMsg, element.sourceSpan);
  12037. }
  12038. };
  12039. TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
  12040. var _this = this;
  12041. var componentTypeNames = this._findComponentDirectiveNames(directives);
  12042. if (componentTypeNames.length > 0) {
  12043. this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
  12044. }
  12045. elementProps.forEach(function (prop) {
  12046. _this._reportError("Property binding " + prop.name + " not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", sourceSpan);
  12047. });
  12048. };
  12049. TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
  12050. var _this = this;
  12051. var allDirectiveEvents = new Set();
  12052. directives.forEach(function (directive) {
  12053. Object.keys(directive.directive.outputs).forEach(function (k) {
  12054. var eventName = directive.directive.outputs[k];
  12055. allDirectiveEvents.add(eventName);
  12056. });
  12057. });
  12058. events.forEach(function (event) {
  12059. if (event.target != null || !allDirectiveEvents.has(event.name)) {
  12060. _this._reportError("Event binding " + event.fullName + " not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", event.sourceSpan);
  12061. }
  12062. });
  12063. };
  12064. TemplateParseVisitor.prototype._checkPropertiesInSchema = function (elementName, boundProps) {
  12065. var _this = this;
  12066. // Note: We can't filter out empty expressions before this method,
  12067. // as we still want to validate them!
  12068. return boundProps.filter(function (boundProp) {
  12069. if (boundProp.type === 0 /* Property */ &&
  12070. !_this._schemaRegistry.hasProperty(elementName, boundProp.name, _this._schemas)) {
  12071. var errorMsg = "Can't bind to '" + boundProp.name + "' since it isn't a known property of '" + elementName + "'.";
  12072. if (elementName.startsWith('ng-')) {
  12073. errorMsg +=
  12074. "\n1. If '" + boundProp.name + "' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component." +
  12075. "\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12076. }
  12077. else if (elementName.indexOf('-') > -1) {
  12078. errorMsg +=
  12079. "\n1. If '" + elementName + "' is an Angular component and it has '" + boundProp.name + "' input, then verify that it is part of this module." +
  12080. ("\n2. If '" + elementName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.") +
  12081. "\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12082. }
  12083. _this._reportError(errorMsg, boundProp.sourceSpan);
  12084. }
  12085. return !isEmptyExpression(boundProp.value);
  12086. });
  12087. };
  12088. TemplateParseVisitor.prototype._reportError = function (message, sourceSpan, level) {
  12089. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  12090. this._targetErrors.push(new ParseError(sourceSpan, message, level));
  12091. };
  12092. return TemplateParseVisitor;
  12093. }());
  12094. var NonBindableVisitor = /** @class */ (function () {
  12095. function NonBindableVisitor() {
  12096. }
  12097. NonBindableVisitor.prototype.visitElement = function (ast, parent) {
  12098. var preparsedElement = preparseElement(ast);
  12099. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  12100. preparsedElement.type === PreparsedElementType.STYLE ||
  12101. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  12102. // Skipping <script> for security reasons
  12103. // Skipping <style> and stylesheets as we already processed them
  12104. // in the StyleCompiler
  12105. return null;
  12106. }
  12107. var attrNameAndValues = ast.attrs.map(function (attr) { return [attr.name, attr.value]; });
  12108. var selector = createElementCssSelector(ast.name, attrNameAndValues);
  12109. var ngContentIndex = parent.findNgContentIndex(selector);
  12110. var children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
  12111. return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
  12112. };
  12113. NonBindableVisitor.prototype.visitComment = function (comment, context) { return null; };
  12114. NonBindableVisitor.prototype.visitAttribute = function (attribute, context) {
  12115. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  12116. };
  12117. NonBindableVisitor.prototype.visitText = function (text, parent) {
  12118. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  12119. return new TextAst(text.value, ngContentIndex, text.sourceSpan);
  12120. };
  12121. NonBindableVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
  12122. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  12123. return NonBindableVisitor;
  12124. }());
  12125. /**
  12126. * A reference to an element or directive in a template. E.g., the reference in this template:
  12127. *
  12128. * <div #myMenu="coolMenu">
  12129. *
  12130. * would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
  12131. */
  12132. var ElementOrDirectiveRef = /** @class */ (function () {
  12133. function ElementOrDirectiveRef(name, value, sourceSpan) {
  12134. this.name = name;
  12135. this.value = value;
  12136. this.sourceSpan = sourceSpan;
  12137. }
  12138. /** Gets whether this is a reference to the given directive. */
  12139. ElementOrDirectiveRef.prototype.isReferenceToDirective = function (directive) {
  12140. return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
  12141. };
  12142. return ElementOrDirectiveRef;
  12143. }());
  12144. /** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
  12145. function splitExportAs(exportAs) {
  12146. return exportAs ? exportAs.split(',').map(function (e) { return e.trim(); }) : [];
  12147. }
  12148. function splitClasses(classAttrValue) {
  12149. return classAttrValue.trim().split(/\s+/g);
  12150. }
  12151. var ElementContext = /** @class */ (function () {
  12152. function ElementContext(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
  12153. this.isTemplateElement = isTemplateElement;
  12154. this._ngContentIndexMatcher = _ngContentIndexMatcher;
  12155. this._wildcardNgContentIndex = _wildcardNgContentIndex;
  12156. this.providerContext = providerContext;
  12157. }
  12158. ElementContext.create = function (isTemplateElement, directives, providerContext) {
  12159. var matcher = new SelectorMatcher();
  12160. var wildcardNgContentIndex = null;
  12161. var component = directives.find(function (directive) { return directive.directive.isComponent; });
  12162. if (component) {
  12163. var ngContentSelectors = component.directive.template.ngContentSelectors;
  12164. for (var i = 0; i < ngContentSelectors.length; i++) {
  12165. var selector = ngContentSelectors[i];
  12166. if (selector === '*') {
  12167. wildcardNgContentIndex = i;
  12168. }
  12169. else {
  12170. matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
  12171. }
  12172. }
  12173. }
  12174. return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
  12175. };
  12176. ElementContext.prototype.findNgContentIndex = function (selector) {
  12177. var ngContentIndices = [];
  12178. this._ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) { ngContentIndices.push(ngContentIndex); });
  12179. ngContentIndices.sort();
  12180. if (this._wildcardNgContentIndex != null) {
  12181. ngContentIndices.push(this._wildcardNgContentIndex);
  12182. }
  12183. return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
  12184. };
  12185. return ElementContext;
  12186. }());
  12187. function createElementCssSelector(elementName, attributes) {
  12188. var cssSelector = new CssSelector();
  12189. var elNameNoNs = splitNsName(elementName)[1];
  12190. cssSelector.setElement(elNameNoNs);
  12191. for (var i = 0; i < attributes.length; i++) {
  12192. var attrName = attributes[i][0];
  12193. var attrNameNoNs = splitNsName(attrName)[1];
  12194. var attrValue = attributes[i][1];
  12195. cssSelector.addAttribute(attrNameNoNs, attrValue);
  12196. if (attrName.toLowerCase() == CLASS_ATTR) {
  12197. var classes = splitClasses(attrValue);
  12198. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  12199. }
  12200. }
  12201. return cssSelector;
  12202. }
  12203. var EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
  12204. var NON_BINDABLE_VISITOR = new NonBindableVisitor();
  12205. function _isEmptyTextNode(node) {
  12206. return node instanceof Text$3 && node.value.trim().length == 0;
  12207. }
  12208. function removeSummaryDuplicates(items) {
  12209. var map = new Map();
  12210. items.forEach(function (item) {
  12211. if (!map.get(item.type.reference)) {
  12212. map.set(item.type.reference, item);
  12213. }
  12214. });
  12215. return Array.from(map.values());
  12216. }
  12217. function isEmptyExpression(ast) {
  12218. if (ast instanceof ASTWithSource) {
  12219. ast = ast.ast;
  12220. }
  12221. return ast instanceof EmptyExpr;
  12222. }
  12223. /**
  12224. * @license
  12225. * Copyright Google Inc. All Rights Reserved.
  12226. *
  12227. * Use of this source code is governed by an MIT-style license that can be
  12228. * found in the LICENSE file at https://angular.io/license
  12229. */
  12230. /**
  12231. * Parses string representation of a style and converts it into object literal.
  12232. *
  12233. * @param value string representation of style as used in the `style` attribute in HTML.
  12234. * Example: `color: red; height: auto`.
  12235. * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
  12236. * 'auto']`
  12237. */
  12238. function parse(value) {
  12239. // we use a string array here instead of a string map
  12240. // because a string-map is not guaranteed to retain the
  12241. // order of the entries whereas a string array can be
  12242. // construted in a [key, value, key, value] format.
  12243. var styles = [];
  12244. var i = 0;
  12245. var parenDepth = 0;
  12246. var quote = 0 /* QuoteNone */;
  12247. var valueStart = 0;
  12248. var propStart = 0;
  12249. var currentProp = null;
  12250. var valueHasQuotes = false;
  12251. while (i < value.length) {
  12252. var token = value.charCodeAt(i++);
  12253. switch (token) {
  12254. case 40 /* OpenParen */:
  12255. parenDepth++;
  12256. break;
  12257. case 41 /* CloseParen */:
  12258. parenDepth--;
  12259. break;
  12260. case 39 /* QuoteSingle */:
  12261. // valueStart needs to be there since prop values don't
  12262. // have quotes in CSS
  12263. valueHasQuotes = valueHasQuotes || valueStart > 0;
  12264. if (quote === 0 /* QuoteNone */) {
  12265. quote = 39 /* QuoteSingle */;
  12266. }
  12267. else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  12268. quote = 0 /* QuoteNone */;
  12269. }
  12270. break;
  12271. case 34 /* QuoteDouble */:
  12272. // same logic as above
  12273. valueHasQuotes = valueHasQuotes || valueStart > 0;
  12274. if (quote === 0 /* QuoteNone */) {
  12275. quote = 34 /* QuoteDouble */;
  12276. }
  12277. else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  12278. quote = 0 /* QuoteNone */;
  12279. }
  12280. break;
  12281. case 58 /* Colon */:
  12282. if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  12283. currentProp = hyphenate(value.substring(propStart, i - 1).trim());
  12284. valueStart = i;
  12285. }
  12286. break;
  12287. case 59 /* Semicolon */:
  12288. if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  12289. var styleVal = value.substring(valueStart, i - 1).trim();
  12290. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  12291. propStart = i;
  12292. valueStart = 0;
  12293. currentProp = null;
  12294. valueHasQuotes = false;
  12295. }
  12296. break;
  12297. }
  12298. }
  12299. if (currentProp && valueStart) {
  12300. var styleVal = value.substr(valueStart).trim();
  12301. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  12302. }
  12303. return styles;
  12304. }
  12305. function stripUnnecessaryQuotes(value) {
  12306. var qS = value.charCodeAt(0);
  12307. var qE = value.charCodeAt(value.length - 1);
  12308. if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
  12309. var tempValue = value.substring(1, value.length - 1);
  12310. // special case to avoid using a multi-quoted string that was just chomped
  12311. // (e.g. `font-family: "Verdana", "sans-serif"`)
  12312. if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
  12313. value = tempValue;
  12314. }
  12315. }
  12316. return value;
  12317. }
  12318. function hyphenate(value) {
  12319. return value.replace(/[a-z][A-Z]/g, function (v) {
  12320. return v.charAt(0) + '-' + v.charAt(1);
  12321. }).toLowerCase();
  12322. }
  12323. /**
  12324. * @license
  12325. * Copyright Google Inc. All Rights Reserved.
  12326. *
  12327. * Use of this source code is governed by an MIT-style license that can be
  12328. * found in the LICENSE file at https://angular.io/license
  12329. */
  12330. var _stylingMode = 0;
  12331. function compilerIsNewStylingInUse() {
  12332. return _stylingMode > 0 /* UseOld */;
  12333. }
  12334. var IMPORTANT_FLAG = '!important';
  12335. /**
  12336. * Produces creation/update instructions for all styling bindings (class and style)
  12337. *
  12338. * It also produces the creation instruction to register all initial styling values
  12339. * (which are all the static class="..." and style="..." attribute values that exist
  12340. * on an element within a template).
  12341. *
  12342. * The builder class below handles producing instructions for the following cases:
  12343. *
  12344. * - Static style/class attributes (style="..." and class="...")
  12345. * - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
  12346. * - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
  12347. *
  12348. * Due to the complex relationship of all of these cases, the instructions generated
  12349. * for these attributes/properties/bindings must be done so in the correct order. The
  12350. * order which these must be generated is as follows:
  12351. *
  12352. * if (createMode) {
  12353. * styling(...)
  12354. * }
  12355. * if (updateMode) {
  12356. * styleMap(...)
  12357. * classMap(...)
  12358. * styleProp(...)
  12359. * classProp(...)
  12360. * stylingApp(...)
  12361. * }
  12362. *
  12363. * The creation/update methods within the builder class produce these instructions.
  12364. */
  12365. var StylingBuilder = /** @class */ (function () {
  12366. function StylingBuilder(_elementIndexExpr, _directiveExpr) {
  12367. this._elementIndexExpr = _elementIndexExpr;
  12368. this._directiveExpr = _directiveExpr;
  12369. /** Whether or not there are any static styling values present */
  12370. this._hasInitialValues = false;
  12371. /**
  12372. * Whether or not there are any styling bindings present
  12373. * (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
  12374. */
  12375. this.hasBindings = false;
  12376. /** the input for [class] (if it exists) */
  12377. this._classMapInput = null;
  12378. /** the input for [style] (if it exists) */
  12379. this._styleMapInput = null;
  12380. /** an array of each [style.prop] input */
  12381. this._singleStyleInputs = null;
  12382. /** an array of each [class.name] input */
  12383. this._singleClassInputs = null;
  12384. this._lastStylingInput = null;
  12385. this._firstStylingInput = null;
  12386. // maps are used instead of hash maps because a Map will
  12387. // retain the ordering of the keys
  12388. /**
  12389. * Represents the location of each style binding in the template
  12390. * (e.g. `<div [style.width]="w" [style.height]="h">` implies
  12391. * that `width=0` and `height=1`)
  12392. */
  12393. this._stylesIndex = new Map();
  12394. /**
  12395. * Represents the location of each class binding in the template
  12396. * (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
  12397. * that `big=0` and `hidden=1`)
  12398. */
  12399. this._classesIndex = new Map();
  12400. this._initialStyleValues = [];
  12401. this._initialClassValues = [];
  12402. // certain style properties ALWAYS need sanitization
  12403. // this is checked each time new styles are encountered
  12404. this._useDefaultSanitizer = false;
  12405. }
  12406. /**
  12407. * Registers a given input to the styling builder to be later used when producing AOT code.
  12408. *
  12409. * The code below will only accept the input if it is somehow tied to styling (whether it be
  12410. * style/class bindings or static style/class attributes).
  12411. */
  12412. StylingBuilder.prototype.registerBoundInput = function (input) {
  12413. // [attr.style] or [attr.class] are skipped in the code below,
  12414. // they should not be treated as styling-based bindings since
  12415. // they are intended to be written directly to the attr and
  12416. // will therefore skip all style/class resolution that is present
  12417. // with style="", [style]="" and [style.prop]="", class="",
  12418. // [class.prop]="". [class]="" assignments
  12419. var binding = null;
  12420. var name = input.name;
  12421. switch (input.type) {
  12422. case 0 /* Property */:
  12423. binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
  12424. break;
  12425. case 3 /* Style */:
  12426. binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
  12427. break;
  12428. case 2 /* Class */:
  12429. binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
  12430. break;
  12431. }
  12432. return binding ? true : false;
  12433. };
  12434. StylingBuilder.prototype.registerInputBasedOnName = function (name, expression, sourceSpan) {
  12435. var binding = null;
  12436. var nameToMatch = name.substring(0, 5); // class | style
  12437. var isStyle = nameToMatch === 'style';
  12438. var isClass = isStyle ? false : (nameToMatch === 'class');
  12439. if (isStyle || isClass) {
  12440. var isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
  12441. var property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
  12442. if (isStyle) {
  12443. binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
  12444. }
  12445. else {
  12446. binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
  12447. }
  12448. }
  12449. return binding;
  12450. };
  12451. StylingBuilder.prototype.registerStyleInput = function (name, isMapBased, value, sourceSpan, unit) {
  12452. if (isEmptyExpression(value)) {
  12453. return null;
  12454. }
  12455. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag, bindingUnit = _a.unit;
  12456. var entry = {
  12457. name: property,
  12458. unit: unit || bindingUnit, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag
  12459. };
  12460. if (isMapBased) {
  12461. this._useDefaultSanitizer = true;
  12462. this._styleMapInput = entry;
  12463. }
  12464. else {
  12465. (this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
  12466. this._useDefaultSanitizer = this._useDefaultSanitizer || isStyleSanitizable(name);
  12467. registerIntoMap(this._stylesIndex, property);
  12468. }
  12469. this._lastStylingInput = entry;
  12470. this._firstStylingInput = this._firstStylingInput || entry;
  12471. this.hasBindings = true;
  12472. return entry;
  12473. };
  12474. StylingBuilder.prototype.registerClassInput = function (name, isMapBased, value, sourceSpan) {
  12475. if (isEmptyExpression(value)) {
  12476. return null;
  12477. }
  12478. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag;
  12479. var entry = { name: property, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag, unit: null };
  12480. if (isMapBased) {
  12481. this._classMapInput = entry;
  12482. }
  12483. else {
  12484. (this._singleClassInputs = this._singleClassInputs || []).push(entry);
  12485. registerIntoMap(this._classesIndex, property);
  12486. }
  12487. this._lastStylingInput = entry;
  12488. this._firstStylingInput = this._firstStylingInput || entry;
  12489. this.hasBindings = true;
  12490. return entry;
  12491. };
  12492. /**
  12493. * Registers the element's static style string value to the builder.
  12494. *
  12495. * @param value the style string (e.g. `width:100px; height:200px;`)
  12496. */
  12497. StylingBuilder.prototype.registerStyleAttr = function (value) {
  12498. this._initialStyleValues = parse(value);
  12499. this._hasInitialValues = true;
  12500. };
  12501. /**
  12502. * Registers the element's static class string value to the builder.
  12503. *
  12504. * @param value the className string (e.g. `disabled gold zoom`)
  12505. */
  12506. StylingBuilder.prototype.registerClassAttr = function (value) {
  12507. this._initialClassValues = value.trim().split(/\s+/g);
  12508. this._hasInitialValues = true;
  12509. };
  12510. /**
  12511. * Appends all styling-related expressions to the provided attrs array.
  12512. *
  12513. * @param attrs an existing array where each of the styling expressions
  12514. * will be inserted into.
  12515. */
  12516. StylingBuilder.prototype.populateInitialStylingAttrs = function (attrs) {
  12517. // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
  12518. if (this._initialClassValues.length) {
  12519. attrs.push(literal(1 /* Classes */));
  12520. for (var i = 0; i < this._initialClassValues.length; i++) {
  12521. attrs.push(literal(this._initialClassValues[i]));
  12522. }
  12523. }
  12524. // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
  12525. if (this._initialStyleValues.length) {
  12526. attrs.push(literal(2 /* Styles */));
  12527. for (var i = 0; i < this._initialStyleValues.length; i += 2) {
  12528. attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
  12529. }
  12530. }
  12531. };
  12532. /**
  12533. * Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
  12534. *
  12535. * The instruction generation code below is used for producing the AOT statement code which is
  12536. * responsible for registering initial styles (within a directive hostBindings' creation block),
  12537. * as well as any of the provided attribute values, to the directive host element.
  12538. */
  12539. StylingBuilder.prototype.buildHostAttrsInstruction = function (sourceSpan, attrs, constantPool) {
  12540. var _this = this;
  12541. if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
  12542. return {
  12543. sourceSpan: sourceSpan,
  12544. reference: Identifiers$1.elementHostAttrs,
  12545. allocateBindingSlots: 0,
  12546. buildParams: function () {
  12547. // params => elementHostAttrs(attrs)
  12548. _this.populateInitialStylingAttrs(attrs);
  12549. var attrArray = !attrs.some(function (attr) { return attr instanceof WrappedNodeExpr; }) ?
  12550. getConstantLiteralFromArray(constantPool, attrs) :
  12551. literalArr(attrs);
  12552. return [attrArray];
  12553. }
  12554. };
  12555. }
  12556. return null;
  12557. };
  12558. /**
  12559. * Builds an instruction with all the expressions and parameters for `styling`.
  12560. *
  12561. * The instruction generation code below is used for producing the AOT statement code which is
  12562. * responsible for registering style/class bindings to an element.
  12563. */
  12564. StylingBuilder.prototype.buildStylingInstruction = function (sourceSpan, constantPool) {
  12565. var _this = this;
  12566. if (this.hasBindings) {
  12567. return {
  12568. sourceSpan: sourceSpan,
  12569. allocateBindingSlots: 0,
  12570. reference: Identifiers$1.styling,
  12571. buildParams: function () {
  12572. // a string array of every style-based binding
  12573. var styleBindingProps = _this._singleStyleInputs ? _this._singleStyleInputs.map(function (i) { return literal(i.name); }) : [];
  12574. // a string array of every class-based binding
  12575. var classBindingNames = _this._singleClassInputs ? _this._singleClassInputs.map(function (i) { return literal(i.name); }) : [];
  12576. // to salvage space in the AOT generated code, there is no point in passing
  12577. // in `null` into a param if any follow-up params are not used. Therefore,
  12578. // only when a trailing param is used then it will be filled with nulls in between
  12579. // (otherwise a shorter amount of params will be filled). The code below helps
  12580. // determine how many params are required in the expression code.
  12581. //
  12582. // min params => styling()
  12583. // max params => styling(classBindings, styleBindings, sanitizer)
  12584. //
  12585. var params = [];
  12586. var expectedNumberOfArgs = 0;
  12587. if (_this._useDefaultSanitizer) {
  12588. expectedNumberOfArgs = 3;
  12589. }
  12590. else if (styleBindingProps.length) {
  12591. expectedNumberOfArgs = 2;
  12592. }
  12593. else if (classBindingNames.length) {
  12594. expectedNumberOfArgs = 1;
  12595. }
  12596. addParam(params, classBindingNames.length > 0, getConstantLiteralFromArray(constantPool, classBindingNames), 1, expectedNumberOfArgs);
  12597. addParam(params, styleBindingProps.length > 0, getConstantLiteralFromArray(constantPool, styleBindingProps), 2, expectedNumberOfArgs);
  12598. addParam(params, _this._useDefaultSanitizer, importExpr(Identifiers$1.defaultStyleSanitizer), 3, expectedNumberOfArgs);
  12599. return params;
  12600. }
  12601. };
  12602. }
  12603. return null;
  12604. };
  12605. /**
  12606. * Builds an instruction with all the expressions and parameters for `classMap`.
  12607. *
  12608. * The instruction data will contain all expressions for `classMap` to function
  12609. * which includes the `[class]` expression params.
  12610. */
  12611. StylingBuilder.prototype.buildClassMapInstruction = function (valueConverter) {
  12612. if (this._classMapInput) {
  12613. return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
  12614. }
  12615. return null;
  12616. };
  12617. /**
  12618. * Builds an instruction with all the expressions and parameters for `styleMap`.
  12619. *
  12620. * The instruction data will contain all expressions for `styleMap` to function
  12621. * which includes the `[style]` expression params.
  12622. */
  12623. StylingBuilder.prototype.buildStyleMapInstruction = function (valueConverter) {
  12624. if (this._styleMapInput) {
  12625. return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
  12626. }
  12627. return null;
  12628. };
  12629. StylingBuilder.prototype._buildMapBasedInstruction = function (valueConverter, isClassBased, stylingInput) {
  12630. var totalBindingSlotsRequired = 0;
  12631. if (compilerIsNewStylingInUse()) {
  12632. // the old implementation does not reserve slot values for
  12633. // binding entries. The new one does.
  12634. totalBindingSlotsRequired++;
  12635. }
  12636. // these values must be outside of the update block so that they can
  12637. // be evaluated (the AST visit call) during creation time so that any
  12638. // pipes can be picked up in time before the template is built
  12639. var mapValue = stylingInput.value.visit(valueConverter);
  12640. if (mapValue instanceof Interpolation) {
  12641. totalBindingSlotsRequired += mapValue.expressions.length;
  12642. }
  12643. var reference = isClassBased ? Identifiers$1.classMap : Identifiers$1.styleMap;
  12644. return {
  12645. sourceSpan: stylingInput.sourceSpan,
  12646. reference: reference,
  12647. allocateBindingSlots: totalBindingSlotsRequired,
  12648. buildParams: function (convertFn) { return [convertFn(mapValue)]; }
  12649. };
  12650. };
  12651. StylingBuilder.prototype._buildSingleInputs = function (reference, inputs, mapIndex, allowUnits, valueConverter) {
  12652. var totalBindingSlotsRequired = 0;
  12653. return inputs.map(function (input) {
  12654. var bindingIndex = mapIndex.get(input.name);
  12655. var value = input.value.visit(valueConverter);
  12656. totalBindingSlotsRequired += (value instanceof Interpolation) ? value.expressions.length : 0;
  12657. if (compilerIsNewStylingInUse()) {
  12658. // the old implementation does not reserve slot values for
  12659. // binding entries. The new one does.
  12660. totalBindingSlotsRequired++;
  12661. }
  12662. return {
  12663. sourceSpan: input.sourceSpan,
  12664. allocateBindingSlots: totalBindingSlotsRequired, reference: reference,
  12665. buildParams: function (convertFn) {
  12666. // min params => stylingProp(elmIndex, bindingIndex, value)
  12667. // max params => stylingProp(elmIndex, bindingIndex, value, overrideFlag)
  12668. var params = [];
  12669. params.push(literal(bindingIndex));
  12670. params.push(convertFn(value));
  12671. if (allowUnits) {
  12672. if (input.unit) {
  12673. params.push(literal(input.unit));
  12674. }
  12675. else if (input.hasOverrideFlag) {
  12676. params.push(NULL_EXPR);
  12677. }
  12678. }
  12679. if (input.hasOverrideFlag) {
  12680. params.push(literal(true));
  12681. }
  12682. return params;
  12683. }
  12684. };
  12685. });
  12686. };
  12687. StylingBuilder.prototype._buildClassInputs = function (valueConverter) {
  12688. if (this._singleClassInputs) {
  12689. return this._buildSingleInputs(Identifiers$1.classProp, this._singleClassInputs, this._classesIndex, false, valueConverter);
  12690. }
  12691. return [];
  12692. };
  12693. StylingBuilder.prototype._buildStyleInputs = function (valueConverter) {
  12694. if (this._singleStyleInputs) {
  12695. return this._buildSingleInputs(Identifiers$1.styleProp, this._singleStyleInputs, this._stylesIndex, true, valueConverter);
  12696. }
  12697. return [];
  12698. };
  12699. StylingBuilder.prototype._buildApplyFn = function () {
  12700. return {
  12701. sourceSpan: this._lastStylingInput ? this._lastStylingInput.sourceSpan : null,
  12702. reference: Identifiers$1.stylingApply,
  12703. allocateBindingSlots: 0,
  12704. buildParams: function () { return []; }
  12705. };
  12706. };
  12707. StylingBuilder.prototype._buildSanitizerFn = function () {
  12708. return {
  12709. sourceSpan: this._firstStylingInput ? this._firstStylingInput.sourceSpan : null,
  12710. reference: Identifiers$1.styleSanitizer,
  12711. allocateBindingSlots: 0,
  12712. buildParams: function () { return [importExpr(Identifiers$1.defaultStyleSanitizer)]; }
  12713. };
  12714. };
  12715. /**
  12716. * Constructs all instructions which contain the expressions that will be placed
  12717. * into the update block of a template function or a directive hostBindings function.
  12718. */
  12719. StylingBuilder.prototype.buildUpdateLevelInstructions = function (valueConverter) {
  12720. var instructions = [];
  12721. if (this.hasBindings) {
  12722. if (compilerIsNewStylingInUse() && this._useDefaultSanitizer) {
  12723. instructions.push(this._buildSanitizerFn());
  12724. }
  12725. var styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
  12726. if (styleMapInstruction) {
  12727. instructions.push(styleMapInstruction);
  12728. }
  12729. var classMapInstruction = this.buildClassMapInstruction(valueConverter);
  12730. if (classMapInstruction) {
  12731. instructions.push(classMapInstruction);
  12732. }
  12733. instructions.push.apply(instructions, __spread(this._buildStyleInputs(valueConverter)));
  12734. instructions.push.apply(instructions, __spread(this._buildClassInputs(valueConverter)));
  12735. instructions.push(this._buildApplyFn());
  12736. }
  12737. return instructions;
  12738. };
  12739. return StylingBuilder;
  12740. }());
  12741. function registerIntoMap(map, key) {
  12742. if (!map.has(key)) {
  12743. map.set(key, map.size);
  12744. }
  12745. }
  12746. function isStyleSanitizable(prop) {
  12747. // Note that browsers support both the dash case and
  12748. // camel case property names when setting through JS.
  12749. return prop === 'background-image' || prop === 'backgroundImage' || prop === 'background' ||
  12750. prop === 'border-image' || prop === 'borderImage' || prop === 'filter' ||
  12751. prop === 'list-style' || prop === 'listStyle' || prop === 'list-style-image' ||
  12752. prop === 'listStyleImage' || prop === 'clip-path' || prop === 'clipPath';
  12753. }
  12754. /**
  12755. * Simple helper function to either provide the constant literal that will house the value
  12756. * here or a null value if the provided values are empty.
  12757. */
  12758. function getConstantLiteralFromArray(constantPool, values) {
  12759. return values.length ? constantPool.getConstLiteral(literalArr(values), true) : NULL_EXPR;
  12760. }
  12761. /**
  12762. * Simple helper function that adds a parameter or does nothing at all depending on the provided
  12763. * predicate and totalExpectedArgs values
  12764. */
  12765. function addParam(params, predicate, value, argNumber, totalExpectedArgs) {
  12766. if (predicate && value) {
  12767. params.push(value);
  12768. }
  12769. else if (argNumber < totalExpectedArgs) {
  12770. params.push(NULL_EXPR);
  12771. }
  12772. }
  12773. function parseProperty(name) {
  12774. var hasOverrideFlag = false;
  12775. var overrideIndex = name.indexOf(IMPORTANT_FLAG);
  12776. if (overrideIndex !== -1) {
  12777. name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
  12778. hasOverrideFlag = true;
  12779. }
  12780. var unit = '';
  12781. var property = name;
  12782. var unitIndex = name.lastIndexOf('.');
  12783. if (unitIndex > 0) {
  12784. unit = name.substr(unitIndex + 1);
  12785. property = name.substring(0, unitIndex);
  12786. }
  12787. return { property: property, unit: unit, hasOverrideFlag: hasOverrideFlag };
  12788. }
  12789. /**
  12790. * @license
  12791. * Copyright Google Inc. All Rights Reserved.
  12792. *
  12793. * Use of this source code is governed by an MIT-style license that can be
  12794. * found in the LICENSE file at https://angular.io/license
  12795. */
  12796. var TokenType$1;
  12797. (function (TokenType) {
  12798. TokenType[TokenType["Character"] = 0] = "Character";
  12799. TokenType[TokenType["Identifier"] = 1] = "Identifier";
  12800. TokenType[TokenType["Keyword"] = 2] = "Keyword";
  12801. TokenType[TokenType["String"] = 3] = "String";
  12802. TokenType[TokenType["Operator"] = 4] = "Operator";
  12803. TokenType[TokenType["Number"] = 5] = "Number";
  12804. TokenType[TokenType["Error"] = 6] = "Error";
  12805. })(TokenType$1 || (TokenType$1 = {}));
  12806. var KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
  12807. var Lexer = /** @class */ (function () {
  12808. function Lexer() {
  12809. }
  12810. Lexer.prototype.tokenize = function (text) {
  12811. var scanner = new _Scanner(text);
  12812. var tokens = [];
  12813. var token = scanner.scanToken();
  12814. while (token != null) {
  12815. tokens.push(token);
  12816. token = scanner.scanToken();
  12817. }
  12818. return tokens;
  12819. };
  12820. return Lexer;
  12821. }());
  12822. var Token$1 = /** @class */ (function () {
  12823. function Token(index, type, numValue, strValue) {
  12824. this.index = index;
  12825. this.type = type;
  12826. this.numValue = numValue;
  12827. this.strValue = strValue;
  12828. }
  12829. Token.prototype.isCharacter = function (code) {
  12830. return this.type == TokenType$1.Character && this.numValue == code;
  12831. };
  12832. Token.prototype.isNumber = function () { return this.type == TokenType$1.Number; };
  12833. Token.prototype.isString = function () { return this.type == TokenType$1.String; };
  12834. Token.prototype.isOperator = function (operator) {
  12835. return this.type == TokenType$1.Operator && this.strValue == operator;
  12836. };
  12837. Token.prototype.isIdentifier = function () { return this.type == TokenType$1.Identifier; };
  12838. Token.prototype.isKeyword = function () { return this.type == TokenType$1.Keyword; };
  12839. Token.prototype.isKeywordLet = function () { return this.type == TokenType$1.Keyword && this.strValue == 'let'; };
  12840. Token.prototype.isKeywordAs = function () { return this.type == TokenType$1.Keyword && this.strValue == 'as'; };
  12841. Token.prototype.isKeywordNull = function () { return this.type == TokenType$1.Keyword && this.strValue == 'null'; };
  12842. Token.prototype.isKeywordUndefined = function () {
  12843. return this.type == TokenType$1.Keyword && this.strValue == 'undefined';
  12844. };
  12845. Token.prototype.isKeywordTrue = function () { return this.type == TokenType$1.Keyword && this.strValue == 'true'; };
  12846. Token.prototype.isKeywordFalse = function () { return this.type == TokenType$1.Keyword && this.strValue == 'false'; };
  12847. Token.prototype.isKeywordThis = function () { return this.type == TokenType$1.Keyword && this.strValue == 'this'; };
  12848. Token.prototype.isError = function () { return this.type == TokenType$1.Error; };
  12849. Token.prototype.toNumber = function () { return this.type == TokenType$1.Number ? this.numValue : -1; };
  12850. Token.prototype.toString = function () {
  12851. switch (this.type) {
  12852. case TokenType$1.Character:
  12853. case TokenType$1.Identifier:
  12854. case TokenType$1.Keyword:
  12855. case TokenType$1.Operator:
  12856. case TokenType$1.String:
  12857. case TokenType$1.Error:
  12858. return this.strValue;
  12859. case TokenType$1.Number:
  12860. return this.numValue.toString();
  12861. default:
  12862. return null;
  12863. }
  12864. };
  12865. return Token;
  12866. }());
  12867. function newCharacterToken(index, code) {
  12868. return new Token$1(index, TokenType$1.Character, code, String.fromCharCode(code));
  12869. }
  12870. function newIdentifierToken(index, text) {
  12871. return new Token$1(index, TokenType$1.Identifier, 0, text);
  12872. }
  12873. function newKeywordToken(index, text) {
  12874. return new Token$1(index, TokenType$1.Keyword, 0, text);
  12875. }
  12876. function newOperatorToken(index, text) {
  12877. return new Token$1(index, TokenType$1.Operator, 0, text);
  12878. }
  12879. function newStringToken(index, text) {
  12880. return new Token$1(index, TokenType$1.String, 0, text);
  12881. }
  12882. function newNumberToken(index, n) {
  12883. return new Token$1(index, TokenType$1.Number, n, '');
  12884. }
  12885. function newErrorToken(index, message) {
  12886. return new Token$1(index, TokenType$1.Error, 0, message);
  12887. }
  12888. var EOF = new Token$1(-1, TokenType$1.Character, 0, '');
  12889. var _Scanner = /** @class */ (function () {
  12890. function _Scanner(input) {
  12891. this.input = input;
  12892. this.peek = 0;
  12893. this.index = -1;
  12894. this.length = input.length;
  12895. this.advance();
  12896. }
  12897. _Scanner.prototype.advance = function () {
  12898. this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
  12899. };
  12900. _Scanner.prototype.scanToken = function () {
  12901. var input = this.input, length = this.length;
  12902. var peek = this.peek, index = this.index;
  12903. // Skip whitespace.
  12904. while (peek <= $SPACE) {
  12905. if (++index >= length) {
  12906. peek = $EOF;
  12907. break;
  12908. }
  12909. else {
  12910. peek = input.charCodeAt(index);
  12911. }
  12912. }
  12913. this.peek = peek;
  12914. this.index = index;
  12915. if (index >= length) {
  12916. return null;
  12917. }
  12918. // Handle identifiers and numbers.
  12919. if (isIdentifierStart(peek))
  12920. return this.scanIdentifier();
  12921. if (isDigit(peek))
  12922. return this.scanNumber(index);
  12923. var start = index;
  12924. switch (peek) {
  12925. case $PERIOD:
  12926. this.advance();
  12927. return isDigit(this.peek) ? this.scanNumber(start) :
  12928. newCharacterToken(start, $PERIOD);
  12929. case $LPAREN:
  12930. case $RPAREN:
  12931. case $LBRACE:
  12932. case $RBRACE:
  12933. case $LBRACKET:
  12934. case $RBRACKET:
  12935. case $COMMA:
  12936. case $COLON:
  12937. case $SEMICOLON:
  12938. return this.scanCharacter(start, peek);
  12939. case $SQ:
  12940. case $DQ:
  12941. return this.scanString();
  12942. case $HASH:
  12943. case $PLUS:
  12944. case $MINUS:
  12945. case $STAR:
  12946. case $SLASH:
  12947. case $PERCENT:
  12948. case $CARET:
  12949. return this.scanOperator(start, String.fromCharCode(peek));
  12950. case $QUESTION:
  12951. return this.scanComplexOperator(start, '?', $PERIOD, '.');
  12952. case $LT:
  12953. case $GT:
  12954. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
  12955. case $BANG:
  12956. case $EQ:
  12957. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
  12958. case $AMPERSAND:
  12959. return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
  12960. case $BAR:
  12961. return this.scanComplexOperator(start, '|', $BAR, '|');
  12962. case $NBSP:
  12963. while (isWhitespace(this.peek))
  12964. this.advance();
  12965. return this.scanToken();
  12966. }
  12967. this.advance();
  12968. return this.error("Unexpected character [" + String.fromCharCode(peek) + "]", 0);
  12969. };
  12970. _Scanner.prototype.scanCharacter = function (start, code) {
  12971. this.advance();
  12972. return newCharacterToken(start, code);
  12973. };
  12974. _Scanner.prototype.scanOperator = function (start, str) {
  12975. this.advance();
  12976. return newOperatorToken(start, str);
  12977. };
  12978. /**
  12979. * Tokenize a 2/3 char long operator
  12980. *
  12981. * @param start start index in the expression
  12982. * @param one first symbol (always part of the operator)
  12983. * @param twoCode code point for the second symbol
  12984. * @param two second symbol (part of the operator when the second code point matches)
  12985. * @param threeCode code point for the third symbol
  12986. * @param three third symbol (part of the operator when provided and matches source expression)
  12987. */
  12988. _Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
  12989. this.advance();
  12990. var str = one;
  12991. if (this.peek == twoCode) {
  12992. this.advance();
  12993. str += two;
  12994. }
  12995. if (threeCode != null && this.peek == threeCode) {
  12996. this.advance();
  12997. str += three;
  12998. }
  12999. return newOperatorToken(start, str);
  13000. };
  13001. _Scanner.prototype.scanIdentifier = function () {
  13002. var start = this.index;
  13003. this.advance();
  13004. while (isIdentifierPart(this.peek))
  13005. this.advance();
  13006. var str = this.input.substring(start, this.index);
  13007. return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
  13008. newIdentifierToken(start, str);
  13009. };
  13010. _Scanner.prototype.scanNumber = function (start) {
  13011. var simple = (this.index === start);
  13012. this.advance(); // Skip initial digit.
  13013. while (true) {
  13014. if (isDigit(this.peek)) ;
  13015. else if (this.peek == $PERIOD) {
  13016. simple = false;
  13017. }
  13018. else if (isExponentStart(this.peek)) {
  13019. this.advance();
  13020. if (isExponentSign(this.peek))
  13021. this.advance();
  13022. if (!isDigit(this.peek))
  13023. return this.error('Invalid exponent', -1);
  13024. simple = false;
  13025. }
  13026. else {
  13027. break;
  13028. }
  13029. this.advance();
  13030. }
  13031. var str = this.input.substring(start, this.index);
  13032. var value = simple ? parseIntAutoRadix(str) : parseFloat(str);
  13033. return newNumberToken(start, value);
  13034. };
  13035. _Scanner.prototype.scanString = function () {
  13036. var start = this.index;
  13037. var quote = this.peek;
  13038. this.advance(); // Skip initial quote.
  13039. var buffer = '';
  13040. var marker = this.index;
  13041. var input = this.input;
  13042. while (this.peek != quote) {
  13043. if (this.peek == $BACKSLASH) {
  13044. buffer += input.substring(marker, this.index);
  13045. this.advance();
  13046. var unescapedCode = void 0;
  13047. // Workaround for TS2.1-introduced type strictness
  13048. this.peek = this.peek;
  13049. if (this.peek == $u) {
  13050. // 4 character hex code for unicode character.
  13051. var hex = input.substring(this.index + 1, this.index + 5);
  13052. if (/^[0-9a-f]+$/i.test(hex)) {
  13053. unescapedCode = parseInt(hex, 16);
  13054. }
  13055. else {
  13056. return this.error("Invalid unicode escape [\\u" + hex + "]", 0);
  13057. }
  13058. for (var i = 0; i < 5; i++) {
  13059. this.advance();
  13060. }
  13061. }
  13062. else {
  13063. unescapedCode = unescape(this.peek);
  13064. this.advance();
  13065. }
  13066. buffer += String.fromCharCode(unescapedCode);
  13067. marker = this.index;
  13068. }
  13069. else if (this.peek == $EOF) {
  13070. return this.error('Unterminated quote', 0);
  13071. }
  13072. else {
  13073. this.advance();
  13074. }
  13075. }
  13076. var last = input.substring(marker, this.index);
  13077. this.advance(); // Skip terminating quote.
  13078. return newStringToken(start, buffer + last);
  13079. };
  13080. _Scanner.prototype.error = function (message, offset) {
  13081. var position = this.index + offset;
  13082. return newErrorToken(position, "Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
  13083. };
  13084. return _Scanner;
  13085. }());
  13086. function isIdentifierStart(code) {
  13087. return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
  13088. (code == $_) || (code == $$);
  13089. }
  13090. function isIdentifier(input) {
  13091. if (input.length == 0)
  13092. return false;
  13093. var scanner = new _Scanner(input);
  13094. if (!isIdentifierStart(scanner.peek))
  13095. return false;
  13096. scanner.advance();
  13097. while (scanner.peek !== $EOF) {
  13098. if (!isIdentifierPart(scanner.peek))
  13099. return false;
  13100. scanner.advance();
  13101. }
  13102. return true;
  13103. }
  13104. function isIdentifierPart(code) {
  13105. return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
  13106. (code == $$);
  13107. }
  13108. function isExponentStart(code) {
  13109. return code == $e || code == $E;
  13110. }
  13111. function isExponentSign(code) {
  13112. return code == $MINUS || code == $PLUS;
  13113. }
  13114. function isQuote(code) {
  13115. return code === $SQ || code === $DQ || code === $BT;
  13116. }
  13117. function unescape(code) {
  13118. switch (code) {
  13119. case $n:
  13120. return $LF;
  13121. case $f:
  13122. return $FF;
  13123. case $r:
  13124. return $CR;
  13125. case $t:
  13126. return $TAB;
  13127. case $v:
  13128. return $VTAB;
  13129. default:
  13130. return code;
  13131. }
  13132. }
  13133. function parseIntAutoRadix(text) {
  13134. var result = parseInt(text);
  13135. if (isNaN(result)) {
  13136. throw new Error('Invalid integer literal when parsing ' + text);
  13137. }
  13138. return result;
  13139. }
  13140. /**
  13141. * @license
  13142. * Copyright Google Inc. All Rights Reserved.
  13143. *
  13144. * Use of this source code is governed by an MIT-style license that can be
  13145. * found in the LICENSE file at https://angular.io/license
  13146. */
  13147. var SplitInterpolation = /** @class */ (function () {
  13148. function SplitInterpolation(strings, expressions, offsets) {
  13149. this.strings = strings;
  13150. this.expressions = expressions;
  13151. this.offsets = offsets;
  13152. }
  13153. return SplitInterpolation;
  13154. }());
  13155. var TemplateBindingParseResult = /** @class */ (function () {
  13156. function TemplateBindingParseResult(templateBindings, warnings, errors) {
  13157. this.templateBindings = templateBindings;
  13158. this.warnings = warnings;
  13159. this.errors = errors;
  13160. }
  13161. return TemplateBindingParseResult;
  13162. }());
  13163. function _createInterpolateRegExp(config) {
  13164. var pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
  13165. return new RegExp(pattern, 'g');
  13166. }
  13167. var Parser$1 = /** @class */ (function () {
  13168. function Parser(_lexer) {
  13169. this._lexer = _lexer;
  13170. this.errors = [];
  13171. }
  13172. Parser.prototype.parseAction = function (input, location, interpolationConfig) {
  13173. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13174. this._checkNoInterpolation(input, location, interpolationConfig);
  13175. var sourceToLex = this._stripComments(input);
  13176. var tokens = this._lexer.tokenize(this._stripComments(input));
  13177. var ast = new _ParseAST(input, location, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
  13178. .parseChain();
  13179. return new ASTWithSource(ast, input, location, this.errors);
  13180. };
  13181. Parser.prototype.parseBinding = function (input, location, interpolationConfig) {
  13182. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13183. var ast = this._parseBindingAst(input, location, interpolationConfig);
  13184. return new ASTWithSource(ast, input, location, this.errors);
  13185. };
  13186. Parser.prototype.parseSimpleBinding = function (input, location, interpolationConfig) {
  13187. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13188. var ast = this._parseBindingAst(input, location, interpolationConfig);
  13189. var errors = SimpleExpressionChecker.check(ast);
  13190. if (errors.length > 0) {
  13191. this._reportError("Host binding expression cannot contain " + errors.join(' '), input, location);
  13192. }
  13193. return new ASTWithSource(ast, input, location, this.errors);
  13194. };
  13195. Parser.prototype._reportError = function (message, input, errLocation, ctxLocation) {
  13196. this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
  13197. };
  13198. Parser.prototype._parseBindingAst = function (input, location, interpolationConfig) {
  13199. // Quotes expressions use 3rd-party expression language. We don't want to use
  13200. // our lexer or parser for that, so we check for that ahead of time.
  13201. var quote = this._parseQuote(input, location);
  13202. if (quote != null) {
  13203. return quote;
  13204. }
  13205. this._checkNoInterpolation(input, location, interpolationConfig);
  13206. var sourceToLex = this._stripComments(input);
  13207. var tokens = this._lexer.tokenize(sourceToLex);
  13208. return new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
  13209. .parseChain();
  13210. };
  13211. Parser.prototype._parseQuote = function (input, location) {
  13212. if (input == null)
  13213. return null;
  13214. var prefixSeparatorIndex = input.indexOf(':');
  13215. if (prefixSeparatorIndex == -1)
  13216. return null;
  13217. var prefix = input.substring(0, prefixSeparatorIndex).trim();
  13218. if (!isIdentifier(prefix))
  13219. return null;
  13220. var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
  13221. return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
  13222. };
  13223. Parser.prototype.parseTemplateBindings = function (tplKey, tplValue, location) {
  13224. var tokens = this._lexer.tokenize(tplValue);
  13225. return new _ParseAST(tplValue, location, tokens, tplValue.length, false, this.errors, 0)
  13226. .parseTemplateBindings(tplKey);
  13227. };
  13228. Parser.prototype.parseInterpolation = function (input, location, interpolationConfig) {
  13229. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13230. var split = this.splitInterpolation(input, location, interpolationConfig);
  13231. if (split == null)
  13232. return null;
  13233. var expressions = [];
  13234. for (var i = 0; i < split.expressions.length; ++i) {
  13235. var expressionText = split.expressions[i];
  13236. var sourceToLex = this._stripComments(expressionText);
  13237. var tokens = this._lexer.tokenize(sourceToLex);
  13238. var ast = new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, split.offsets[i] + (expressionText.length - sourceToLex.length))
  13239. .parseChain();
  13240. expressions.push(ast);
  13241. }
  13242. return new ASTWithSource(new Interpolation(new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions), input, location, this.errors);
  13243. };
  13244. Parser.prototype.splitInterpolation = function (input, location, interpolationConfig) {
  13245. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13246. var regexp = _createInterpolateRegExp(interpolationConfig);
  13247. var parts = input.split(regexp);
  13248. if (parts.length <= 1) {
  13249. return null;
  13250. }
  13251. var strings = [];
  13252. var expressions = [];
  13253. var offsets = [];
  13254. var offset = 0;
  13255. for (var i = 0; i < parts.length; i++) {
  13256. var part = parts[i];
  13257. if (i % 2 === 0) {
  13258. // fixed string
  13259. strings.push(part);
  13260. offset += part.length;
  13261. }
  13262. else if (part.trim().length > 0) {
  13263. offset += interpolationConfig.start.length;
  13264. expressions.push(part);
  13265. offsets.push(offset);
  13266. offset += part.length + interpolationConfig.end.length;
  13267. }
  13268. else {
  13269. this._reportError('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i, interpolationConfig) + " in", location);
  13270. expressions.push('$implict');
  13271. offsets.push(offset);
  13272. }
  13273. }
  13274. return new SplitInterpolation(strings, expressions, offsets);
  13275. };
  13276. Parser.prototype.wrapLiteralPrimitive = function (input, location) {
  13277. return new ASTWithSource(new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input, location, this.errors);
  13278. };
  13279. Parser.prototype._stripComments = function (input) {
  13280. var i = this._commentStart(input);
  13281. return i != null ? input.substring(0, i).trim() : input;
  13282. };
  13283. Parser.prototype._commentStart = function (input) {
  13284. var outerQuote = null;
  13285. for (var i = 0; i < input.length - 1; i++) {
  13286. var char = input.charCodeAt(i);
  13287. var nextChar = input.charCodeAt(i + 1);
  13288. if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
  13289. return i;
  13290. if (outerQuote === char) {
  13291. outerQuote = null;
  13292. }
  13293. else if (outerQuote == null && isQuote(char)) {
  13294. outerQuote = char;
  13295. }
  13296. }
  13297. return null;
  13298. };
  13299. Parser.prototype._checkNoInterpolation = function (input, location, interpolationConfig) {
  13300. var regexp = _createInterpolateRegExp(interpolationConfig);
  13301. var parts = input.split(regexp);
  13302. if (parts.length > 1) {
  13303. this._reportError("Got interpolation (" + interpolationConfig.start + interpolationConfig.end + ") where expression was expected", input, "at column " + this._findInterpolationErrorColumn(parts, 1, interpolationConfig) + " in", location);
  13304. }
  13305. };
  13306. Parser.prototype._findInterpolationErrorColumn = function (parts, partInErrIdx, interpolationConfig) {
  13307. var errLocation = '';
  13308. for (var j = 0; j < partInErrIdx; j++) {
  13309. errLocation += j % 2 === 0 ?
  13310. parts[j] :
  13311. "" + interpolationConfig.start + parts[j] + interpolationConfig.end;
  13312. }
  13313. return errLocation.length;
  13314. };
  13315. return Parser;
  13316. }());
  13317. var _ParseAST = /** @class */ (function () {
  13318. function _ParseAST(input, location, tokens, inputLength, parseAction, errors, offset) {
  13319. this.input = input;
  13320. this.location = location;
  13321. this.tokens = tokens;
  13322. this.inputLength = inputLength;
  13323. this.parseAction = parseAction;
  13324. this.errors = errors;
  13325. this.offset = offset;
  13326. this.rparensExpected = 0;
  13327. this.rbracketsExpected = 0;
  13328. this.rbracesExpected = 0;
  13329. this.index = 0;
  13330. }
  13331. _ParseAST.prototype.peek = function (offset) {
  13332. var i = this.index + offset;
  13333. return i < this.tokens.length ? this.tokens[i] : EOF;
  13334. };
  13335. Object.defineProperty(_ParseAST.prototype, "next", {
  13336. get: function () { return this.peek(0); },
  13337. enumerable: true,
  13338. configurable: true
  13339. });
  13340. Object.defineProperty(_ParseAST.prototype, "inputIndex", {
  13341. get: function () {
  13342. return (this.index < this.tokens.length) ? this.next.index + this.offset :
  13343. this.inputLength + this.offset;
  13344. },
  13345. enumerable: true,
  13346. configurable: true
  13347. });
  13348. _ParseAST.prototype.span = function (start) { return new ParseSpan(start, this.inputIndex); };
  13349. _ParseAST.prototype.advance = function () { this.index++; };
  13350. _ParseAST.prototype.optionalCharacter = function (code) {
  13351. if (this.next.isCharacter(code)) {
  13352. this.advance();
  13353. return true;
  13354. }
  13355. else {
  13356. return false;
  13357. }
  13358. };
  13359. _ParseAST.prototype.peekKeywordLet = function () { return this.next.isKeywordLet(); };
  13360. _ParseAST.prototype.peekKeywordAs = function () { return this.next.isKeywordAs(); };
  13361. _ParseAST.prototype.expectCharacter = function (code) {
  13362. if (this.optionalCharacter(code))
  13363. return;
  13364. this.error("Missing expected " + String.fromCharCode(code));
  13365. };
  13366. _ParseAST.prototype.optionalOperator = function (op) {
  13367. if (this.next.isOperator(op)) {
  13368. this.advance();
  13369. return true;
  13370. }
  13371. else {
  13372. return false;
  13373. }
  13374. };
  13375. _ParseAST.prototype.expectOperator = function (operator) {
  13376. if (this.optionalOperator(operator))
  13377. return;
  13378. this.error("Missing expected operator " + operator);
  13379. };
  13380. _ParseAST.prototype.expectIdentifierOrKeyword = function () {
  13381. var n = this.next;
  13382. if (!n.isIdentifier() && !n.isKeyword()) {
  13383. this.error("Unexpected token " + n + ", expected identifier or keyword");
  13384. return '';
  13385. }
  13386. this.advance();
  13387. return n.toString();
  13388. };
  13389. _ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
  13390. var n = this.next;
  13391. if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
  13392. this.error("Unexpected token " + n + ", expected identifier, keyword, or string");
  13393. return '';
  13394. }
  13395. this.advance();
  13396. return n.toString();
  13397. };
  13398. _ParseAST.prototype.parseChain = function () {
  13399. var exprs = [];
  13400. var start = this.inputIndex;
  13401. while (this.index < this.tokens.length) {
  13402. var expr = this.parsePipe();
  13403. exprs.push(expr);
  13404. if (this.optionalCharacter($SEMICOLON)) {
  13405. if (!this.parseAction) {
  13406. this.error('Binding expression cannot contain chained expression');
  13407. }
  13408. while (this.optionalCharacter($SEMICOLON)) {
  13409. } // read all semicolons
  13410. }
  13411. else if (this.index < this.tokens.length) {
  13412. this.error("Unexpected token '" + this.next + "'");
  13413. }
  13414. }
  13415. if (exprs.length == 0)
  13416. return new EmptyExpr(this.span(start));
  13417. if (exprs.length == 1)
  13418. return exprs[0];
  13419. return new Chain(this.span(start), exprs);
  13420. };
  13421. _ParseAST.prototype.parsePipe = function () {
  13422. var result = this.parseExpression();
  13423. if (this.optionalOperator('|')) {
  13424. if (this.parseAction) {
  13425. this.error('Cannot have a pipe in an action expression');
  13426. }
  13427. do {
  13428. var name_1 = this.expectIdentifierOrKeyword();
  13429. var args = [];
  13430. while (this.optionalCharacter($COLON)) {
  13431. args.push(this.parseExpression());
  13432. }
  13433. result = new BindingPipe(this.span(result.span.start), result, name_1, args);
  13434. } while (this.optionalOperator('|'));
  13435. }
  13436. return result;
  13437. };
  13438. _ParseAST.prototype.parseExpression = function () { return this.parseConditional(); };
  13439. _ParseAST.prototype.parseConditional = function () {
  13440. var start = this.inputIndex;
  13441. var result = this.parseLogicalOr();
  13442. if (this.optionalOperator('?')) {
  13443. var yes = this.parsePipe();
  13444. var no = void 0;
  13445. if (!this.optionalCharacter($COLON)) {
  13446. var end = this.inputIndex;
  13447. var expression = this.input.substring(start, end);
  13448. this.error("Conditional expression " + expression + " requires all 3 expressions");
  13449. no = new EmptyExpr(this.span(start));
  13450. }
  13451. else {
  13452. no = this.parsePipe();
  13453. }
  13454. return new Conditional(this.span(start), result, yes, no);
  13455. }
  13456. else {
  13457. return result;
  13458. }
  13459. };
  13460. _ParseAST.prototype.parseLogicalOr = function () {
  13461. // '||'
  13462. var result = this.parseLogicalAnd();
  13463. while (this.optionalOperator('||')) {
  13464. var right = this.parseLogicalAnd();
  13465. result = new Binary(this.span(result.span.start), '||', result, right);
  13466. }
  13467. return result;
  13468. };
  13469. _ParseAST.prototype.parseLogicalAnd = function () {
  13470. // '&&'
  13471. var result = this.parseEquality();
  13472. while (this.optionalOperator('&&')) {
  13473. var right = this.parseEquality();
  13474. result = new Binary(this.span(result.span.start), '&&', result, right);
  13475. }
  13476. return result;
  13477. };
  13478. _ParseAST.prototype.parseEquality = function () {
  13479. // '==','!=','===','!=='
  13480. var result = this.parseRelational();
  13481. while (this.next.type == TokenType$1.Operator) {
  13482. var operator = this.next.strValue;
  13483. switch (operator) {
  13484. case '==':
  13485. case '===':
  13486. case '!=':
  13487. case '!==':
  13488. this.advance();
  13489. var right = this.parseRelational();
  13490. result = new Binary(this.span(result.span.start), operator, result, right);
  13491. continue;
  13492. }
  13493. break;
  13494. }
  13495. return result;
  13496. };
  13497. _ParseAST.prototype.parseRelational = function () {
  13498. // '<', '>', '<=', '>='
  13499. var result = this.parseAdditive();
  13500. while (this.next.type == TokenType$1.Operator) {
  13501. var operator = this.next.strValue;
  13502. switch (operator) {
  13503. case '<':
  13504. case '>':
  13505. case '<=':
  13506. case '>=':
  13507. this.advance();
  13508. var right = this.parseAdditive();
  13509. result = new Binary(this.span(result.span.start), operator, result, right);
  13510. continue;
  13511. }
  13512. break;
  13513. }
  13514. return result;
  13515. };
  13516. _ParseAST.prototype.parseAdditive = function () {
  13517. // '+', '-'
  13518. var result = this.parseMultiplicative();
  13519. while (this.next.type == TokenType$1.Operator) {
  13520. var operator = this.next.strValue;
  13521. switch (operator) {
  13522. case '+':
  13523. case '-':
  13524. this.advance();
  13525. var right = this.parseMultiplicative();
  13526. result = new Binary(this.span(result.span.start), operator, result, right);
  13527. continue;
  13528. }
  13529. break;
  13530. }
  13531. return result;
  13532. };
  13533. _ParseAST.prototype.parseMultiplicative = function () {
  13534. // '*', '%', '/'
  13535. var result = this.parsePrefix();
  13536. while (this.next.type == TokenType$1.Operator) {
  13537. var operator = this.next.strValue;
  13538. switch (operator) {
  13539. case '*':
  13540. case '%':
  13541. case '/':
  13542. this.advance();
  13543. var right = this.parsePrefix();
  13544. result = new Binary(this.span(result.span.start), operator, result, right);
  13545. continue;
  13546. }
  13547. break;
  13548. }
  13549. return result;
  13550. };
  13551. _ParseAST.prototype.parsePrefix = function () {
  13552. if (this.next.type == TokenType$1.Operator) {
  13553. var start = this.inputIndex;
  13554. var operator = this.next.strValue;
  13555. var result = void 0;
  13556. switch (operator) {
  13557. case '+':
  13558. this.advance();
  13559. result = this.parsePrefix();
  13560. return new Binary(this.span(start), '-', result, new LiteralPrimitive(new ParseSpan(start, start), 0));
  13561. case '-':
  13562. this.advance();
  13563. result = this.parsePrefix();
  13564. return new Binary(this.span(start), operator, new LiteralPrimitive(new ParseSpan(start, start), 0), result);
  13565. case '!':
  13566. this.advance();
  13567. result = this.parsePrefix();
  13568. return new PrefixNot(this.span(start), result);
  13569. }
  13570. }
  13571. return this.parseCallChain();
  13572. };
  13573. _ParseAST.prototype.parseCallChain = function () {
  13574. var result = this.parsePrimary();
  13575. while (true) {
  13576. if (this.optionalCharacter($PERIOD)) {
  13577. result = this.parseAccessMemberOrMethodCall(result, false);
  13578. }
  13579. else if (this.optionalOperator('?.')) {
  13580. result = this.parseAccessMemberOrMethodCall(result, true);
  13581. }
  13582. else if (this.optionalCharacter($LBRACKET)) {
  13583. this.rbracketsExpected++;
  13584. var key = this.parsePipe();
  13585. this.rbracketsExpected--;
  13586. this.expectCharacter($RBRACKET);
  13587. if (this.optionalOperator('=')) {
  13588. var value = this.parseConditional();
  13589. result = new KeyedWrite(this.span(result.span.start), result, key, value);
  13590. }
  13591. else {
  13592. result = new KeyedRead(this.span(result.span.start), result, key);
  13593. }
  13594. }
  13595. else if (this.optionalCharacter($LPAREN)) {
  13596. this.rparensExpected++;
  13597. var args = this.parseCallArguments();
  13598. this.rparensExpected--;
  13599. this.expectCharacter($RPAREN);
  13600. result = new FunctionCall(this.span(result.span.start), result, args);
  13601. }
  13602. else if (this.optionalOperator('!')) {
  13603. result = new NonNullAssert(this.span(result.span.start), result);
  13604. }
  13605. else {
  13606. return result;
  13607. }
  13608. }
  13609. };
  13610. _ParseAST.prototype.parsePrimary = function () {
  13611. var start = this.inputIndex;
  13612. if (this.optionalCharacter($LPAREN)) {
  13613. this.rparensExpected++;
  13614. var result = this.parsePipe();
  13615. this.rparensExpected--;
  13616. this.expectCharacter($RPAREN);
  13617. return result;
  13618. }
  13619. else if (this.next.isKeywordNull()) {
  13620. this.advance();
  13621. return new LiteralPrimitive(this.span(start), null);
  13622. }
  13623. else if (this.next.isKeywordUndefined()) {
  13624. this.advance();
  13625. return new LiteralPrimitive(this.span(start), void 0);
  13626. }
  13627. else if (this.next.isKeywordTrue()) {
  13628. this.advance();
  13629. return new LiteralPrimitive(this.span(start), true);
  13630. }
  13631. else if (this.next.isKeywordFalse()) {
  13632. this.advance();
  13633. return new LiteralPrimitive(this.span(start), false);
  13634. }
  13635. else if (this.next.isKeywordThis()) {
  13636. this.advance();
  13637. return new ImplicitReceiver(this.span(start));
  13638. }
  13639. else if (this.optionalCharacter($LBRACKET)) {
  13640. this.rbracketsExpected++;
  13641. var elements = this.parseExpressionList($RBRACKET);
  13642. this.rbracketsExpected--;
  13643. this.expectCharacter($RBRACKET);
  13644. return new LiteralArray(this.span(start), elements);
  13645. }
  13646. else if (this.next.isCharacter($LBRACE)) {
  13647. return this.parseLiteralMap();
  13648. }
  13649. else if (this.next.isIdentifier()) {
  13650. return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start)), false);
  13651. }
  13652. else if (this.next.isNumber()) {
  13653. var value = this.next.toNumber();
  13654. this.advance();
  13655. return new LiteralPrimitive(this.span(start), value);
  13656. }
  13657. else if (this.next.isString()) {
  13658. var literalValue = this.next.toString();
  13659. this.advance();
  13660. return new LiteralPrimitive(this.span(start), literalValue);
  13661. }
  13662. else if (this.index >= this.tokens.length) {
  13663. this.error("Unexpected end of expression: " + this.input);
  13664. return new EmptyExpr(this.span(start));
  13665. }
  13666. else {
  13667. this.error("Unexpected token " + this.next);
  13668. return new EmptyExpr(this.span(start));
  13669. }
  13670. };
  13671. _ParseAST.prototype.parseExpressionList = function (terminator) {
  13672. var result = [];
  13673. if (!this.next.isCharacter(terminator)) {
  13674. do {
  13675. result.push(this.parsePipe());
  13676. } while (this.optionalCharacter($COMMA));
  13677. }
  13678. return result;
  13679. };
  13680. _ParseAST.prototype.parseLiteralMap = function () {
  13681. var keys = [];
  13682. var values = [];
  13683. var start = this.inputIndex;
  13684. this.expectCharacter($LBRACE);
  13685. if (!this.optionalCharacter($RBRACE)) {
  13686. this.rbracesExpected++;
  13687. do {
  13688. var quoted = this.next.isString();
  13689. var key = this.expectIdentifierOrKeywordOrString();
  13690. keys.push({ key: key, quoted: quoted });
  13691. this.expectCharacter($COLON);
  13692. values.push(this.parsePipe());
  13693. } while (this.optionalCharacter($COMMA));
  13694. this.rbracesExpected--;
  13695. this.expectCharacter($RBRACE);
  13696. }
  13697. return new LiteralMap(this.span(start), keys, values);
  13698. };
  13699. _ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, isSafe) {
  13700. if (isSafe === void 0) { isSafe = false; }
  13701. var start = receiver.span.start;
  13702. var id = this.expectIdentifierOrKeyword();
  13703. if (this.optionalCharacter($LPAREN)) {
  13704. this.rparensExpected++;
  13705. var args = this.parseCallArguments();
  13706. this.expectCharacter($RPAREN);
  13707. this.rparensExpected--;
  13708. var span = this.span(start);
  13709. return isSafe ? new SafeMethodCall(span, receiver, id, args) :
  13710. new MethodCall(span, receiver, id, args);
  13711. }
  13712. else {
  13713. if (isSafe) {
  13714. if (this.optionalOperator('=')) {
  13715. this.error('The \'?.\' operator cannot be used in the assignment');
  13716. return new EmptyExpr(this.span(start));
  13717. }
  13718. else {
  13719. return new SafePropertyRead(this.span(start), receiver, id);
  13720. }
  13721. }
  13722. else {
  13723. if (this.optionalOperator('=')) {
  13724. if (!this.parseAction) {
  13725. this.error('Bindings cannot contain assignments');
  13726. return new EmptyExpr(this.span(start));
  13727. }
  13728. var value = this.parseConditional();
  13729. return new PropertyWrite(this.span(start), receiver, id, value);
  13730. }
  13731. else {
  13732. return new PropertyRead(this.span(start), receiver, id);
  13733. }
  13734. }
  13735. }
  13736. };
  13737. _ParseAST.prototype.parseCallArguments = function () {
  13738. if (this.next.isCharacter($RPAREN))
  13739. return [];
  13740. var positionals = [];
  13741. do {
  13742. positionals.push(this.parsePipe());
  13743. } while (this.optionalCharacter($COMMA));
  13744. return positionals;
  13745. };
  13746. /**
  13747. * An identifier, a keyword, a string with an optional `-` in between.
  13748. */
  13749. _ParseAST.prototype.expectTemplateBindingKey = function () {
  13750. var result = '';
  13751. var operatorFound = false;
  13752. do {
  13753. result += this.expectIdentifierOrKeywordOrString();
  13754. operatorFound = this.optionalOperator('-');
  13755. if (operatorFound) {
  13756. result += '-';
  13757. }
  13758. } while (operatorFound);
  13759. return result.toString();
  13760. };
  13761. // Parses the AST for `<some-tag *tplKey=AST>`
  13762. _ParseAST.prototype.parseTemplateBindings = function (tplKey) {
  13763. var firstBinding = true;
  13764. var bindings = [];
  13765. var warnings = [];
  13766. do {
  13767. var start = this.inputIndex;
  13768. var rawKey = void 0;
  13769. var key = void 0;
  13770. var isVar = false;
  13771. if (firstBinding) {
  13772. rawKey = key = tplKey;
  13773. firstBinding = false;
  13774. }
  13775. else {
  13776. isVar = this.peekKeywordLet();
  13777. if (isVar)
  13778. this.advance();
  13779. rawKey = this.expectTemplateBindingKey();
  13780. key = isVar ? rawKey : tplKey + rawKey[0].toUpperCase() + rawKey.substring(1);
  13781. this.optionalCharacter($COLON);
  13782. }
  13783. var name_2 = null;
  13784. var expression = null;
  13785. if (isVar) {
  13786. if (this.optionalOperator('=')) {
  13787. name_2 = this.expectTemplateBindingKey();
  13788. }
  13789. else {
  13790. name_2 = '\$implicit';
  13791. }
  13792. }
  13793. else if (this.peekKeywordAs()) {
  13794. this.advance(); // consume `as`
  13795. name_2 = rawKey;
  13796. key = this.expectTemplateBindingKey(); // read local var name
  13797. isVar = true;
  13798. }
  13799. else if (this.next !== EOF && !this.peekKeywordLet()) {
  13800. var start_1 = this.inputIndex;
  13801. var ast = this.parsePipe();
  13802. var source = this.input.substring(start_1 - this.offset, this.inputIndex - this.offset);
  13803. expression = new ASTWithSource(ast, source, this.location, this.errors);
  13804. }
  13805. bindings.push(new TemplateBinding(this.span(start), key, isVar, name_2, expression));
  13806. if (this.peekKeywordAs() && !isVar) {
  13807. var letStart = this.inputIndex;
  13808. this.advance(); // consume `as`
  13809. var letName = this.expectTemplateBindingKey(); // read local var name
  13810. bindings.push(new TemplateBinding(this.span(letStart), letName, true, key, null));
  13811. }
  13812. if (!this.optionalCharacter($SEMICOLON)) {
  13813. this.optionalCharacter($COMMA);
  13814. }
  13815. } while (this.index < this.tokens.length);
  13816. return new TemplateBindingParseResult(bindings, warnings, this.errors);
  13817. };
  13818. _ParseAST.prototype.error = function (message, index) {
  13819. if (index === void 0) { index = null; }
  13820. this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
  13821. this.skip();
  13822. };
  13823. _ParseAST.prototype.locationText = function (index) {
  13824. if (index === void 0) { index = null; }
  13825. if (index == null)
  13826. index = this.index;
  13827. return (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
  13828. "at the end of the expression";
  13829. };
  13830. // Error recovery should skip tokens until it encounters a recovery point. skip() treats
  13831. // the end of input and a ';' as unconditionally a recovery point. It also treats ')',
  13832. // '}' and ']' as conditional recovery points if one of calling productions is expecting
  13833. // one of these symbols. This allows skip() to recover from errors such as '(a.) + 1' allowing
  13834. // more of the AST to be retained (it doesn't skip any tokens as the ')' is retained because
  13835. // of the '(' begins an '(' <expr> ')' production). The recovery points of grouping symbols
  13836. // must be conditional as they must be skipped if none of the calling productions are not
  13837. // expecting the closing token else we will never make progress in the case of an
  13838. // extraneous group closing symbol (such as a stray ')'). This is not the case for ';' because
  13839. // parseChain() is always the root production and it expects a ';'.
  13840. // If a production expects one of these token it increments the corresponding nesting count,
  13841. // and then decrements it just prior to checking if the token is in the input.
  13842. _ParseAST.prototype.skip = function () {
  13843. var n = this.next;
  13844. while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
  13845. (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
  13846. (this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
  13847. (this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET))) {
  13848. if (this.next.isError()) {
  13849. this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
  13850. }
  13851. this.advance();
  13852. n = this.next;
  13853. }
  13854. };
  13855. return _ParseAST;
  13856. }());
  13857. var SimpleExpressionChecker = /** @class */ (function () {
  13858. function SimpleExpressionChecker() {
  13859. this.errors = [];
  13860. }
  13861. SimpleExpressionChecker.check = function (ast) {
  13862. var s = new SimpleExpressionChecker();
  13863. ast.visit(s);
  13864. return s.errors;
  13865. };
  13866. SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast, context) { };
  13867. SimpleExpressionChecker.prototype.visitInterpolation = function (ast, context) { };
  13868. SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast, context) { };
  13869. SimpleExpressionChecker.prototype.visitPropertyRead = function (ast, context) { };
  13870. SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast, context) { };
  13871. SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast, context) { };
  13872. SimpleExpressionChecker.prototype.visitMethodCall = function (ast, context) { };
  13873. SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast, context) { };
  13874. SimpleExpressionChecker.prototype.visitFunctionCall = function (ast, context) { };
  13875. SimpleExpressionChecker.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions); };
  13876. SimpleExpressionChecker.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values); };
  13877. SimpleExpressionChecker.prototype.visitBinary = function (ast, context) { };
  13878. SimpleExpressionChecker.prototype.visitPrefixNot = function (ast, context) { };
  13879. SimpleExpressionChecker.prototype.visitNonNullAssert = function (ast, context) { };
  13880. SimpleExpressionChecker.prototype.visitConditional = function (ast, context) { };
  13881. SimpleExpressionChecker.prototype.visitPipe = function (ast, context) { this.errors.push('pipes'); };
  13882. SimpleExpressionChecker.prototype.visitKeyedRead = function (ast, context) { };
  13883. SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast, context) { };
  13884. SimpleExpressionChecker.prototype.visitAll = function (asts) {
  13885. var _this = this;
  13886. return asts.map(function (node) { return node.visit(_this); });
  13887. };
  13888. SimpleExpressionChecker.prototype.visitChain = function (ast, context) { };
  13889. SimpleExpressionChecker.prototype.visitQuote = function (ast, context) { };
  13890. return SimpleExpressionChecker;
  13891. }());
  13892. /**
  13893. * @license
  13894. * Copyright Google Inc. All Rights Reserved.
  13895. *
  13896. * Use of this source code is governed by an MIT-style license that can be
  13897. * found in the LICENSE file at https://angular.io/license
  13898. */
  13899. // =================================================================================================
  13900. // =================================================================================================
  13901. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  13902. // =================================================================================================
  13903. // =================================================================================================
  13904. //
  13905. // DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
  13906. // Reach out to mprobst for details.
  13907. //
  13908. // =================================================================================================
  13909. /** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
  13910. var _SECURITY_SCHEMA;
  13911. function SECURITY_SCHEMA() {
  13912. if (!_SECURITY_SCHEMA) {
  13913. _SECURITY_SCHEMA = {};
  13914. // Case is insignificant below, all element and attribute names are lower-cased for lookup.
  13915. registerContext(SecurityContext.HTML, [
  13916. 'iframe|srcdoc',
  13917. '*|innerHTML',
  13918. '*|outerHTML',
  13919. ]);
  13920. registerContext(SecurityContext.STYLE, ['*|style']);
  13921. // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
  13922. registerContext(SecurityContext.URL, [
  13923. '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
  13924. 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
  13925. 'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
  13926. 'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
  13927. ]);
  13928. registerContext(SecurityContext.RESOURCE_URL, [
  13929. 'applet|code',
  13930. 'applet|codebase',
  13931. 'base|href',
  13932. 'embed|src',
  13933. 'frame|src',
  13934. 'head|profile',
  13935. 'html|manifest',
  13936. 'iframe|src',
  13937. 'link|href',
  13938. 'media|src',
  13939. 'object|codebase',
  13940. 'object|data',
  13941. 'script|src',
  13942. ]);
  13943. }
  13944. return _SECURITY_SCHEMA;
  13945. }
  13946. function registerContext(ctx, specs) {
  13947. var e_1, _a;
  13948. try {
  13949. for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
  13950. var spec = specs_1_1.value;
  13951. _SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
  13952. }
  13953. }
  13954. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13955. finally {
  13956. try {
  13957. if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
  13958. }
  13959. finally { if (e_1) throw e_1.error; }
  13960. }
  13961. }
  13962. /**
  13963. * @license
  13964. * Copyright Google Inc. All Rights Reserved.
  13965. *
  13966. * Use of this source code is governed by an MIT-style license that can be
  13967. * found in the LICENSE file at https://angular.io/license
  13968. */
  13969. var ElementSchemaRegistry = /** @class */ (function () {
  13970. function ElementSchemaRegistry() {
  13971. }
  13972. return ElementSchemaRegistry;
  13973. }());
  13974. /**
  13975. * @license
  13976. * Copyright Google Inc. All Rights Reserved.
  13977. *
  13978. * Use of this source code is governed by an MIT-style license that can be
  13979. * found in the LICENSE file at https://angular.io/license
  13980. */
  13981. var BOOLEAN = 'boolean';
  13982. var NUMBER = 'number';
  13983. var STRING = 'string';
  13984. var OBJECT = 'object';
  13985. /**
  13986. * This array represents the DOM schema. It encodes inheritance, properties, and events.
  13987. *
  13988. * ## Overview
  13989. *
  13990. * Each line represents one kind of element. The `element_inheritance` and properties are joined
  13991. * using `element_inheritance|properties` syntax.
  13992. *
  13993. * ## Element Inheritance
  13994. *
  13995. * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
  13996. * Here the individual elements are separated by `,` (commas). Every element in the list
  13997. * has identical properties.
  13998. *
  13999. * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
  14000. * specified then `""` (blank) element is assumed.
  14001. *
  14002. * NOTE: The blank element inherits from root `[Element]` element, the super element of all
  14003. * elements.
  14004. *
  14005. * NOTE an element prefix such as `:svg:` has no special meaning to the schema.
  14006. *
  14007. * ## Properties
  14008. *
  14009. * Each element has a set of properties separated by `,` (commas). Each property can be prefixed
  14010. * by a special character designating its type:
  14011. *
  14012. * - (no prefix): property is a string.
  14013. * - `*`: property represents an event.
  14014. * - `!`: property is a boolean.
  14015. * - `#`: property is a number.
  14016. * - `%`: property is an object.
  14017. *
  14018. * ## Query
  14019. *
  14020. * The class creates an internal squas representation which allows to easily answer the query of
  14021. * if a given property exist on a given element.
  14022. *
  14023. * NOTE: We don't yet support querying for types or events.
  14024. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
  14025. * see dom_element_schema_registry_spec.ts
  14026. */
  14027. // =================================================================================================
  14028. // =================================================================================================
  14029. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  14030. // =================================================================================================
  14031. // =================================================================================================
  14032. //
  14033. // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
  14034. //
  14035. // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
  14036. // dom_security_schema.ts. Reach out to mprobst & rjamet for details.
  14037. //
  14038. // =================================================================================================
  14039. var SCHEMA = [
  14040. '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
  14041. /* added manually to avoid breaking changes */
  14042. ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
  14043. '[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
  14044. 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
  14045. 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
  14046. ':svg:^[HTMLElement]|*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex',
  14047. ':svg:graphics^:svg:|',
  14048. ':svg:animation^:svg:|*begin,*end,*repeat',
  14049. ':svg:geometry^:svg:|',
  14050. ':svg:componentTransferFunction^:svg:|',
  14051. ':svg:gradient^:svg:|',
  14052. ':svg:textContent^:svg:graphics|',
  14053. ':svg:textPositioning^:svg:textContent|',
  14054. 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username',
  14055. 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
  14056. 'audio^media|',
  14057. 'br^[HTMLElement]|clear',
  14058. 'base^[HTMLElement]|href,target',
  14059. 'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink',
  14060. 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
  14061. 'canvas^[HTMLElement]|#height,#width',
  14062. 'content^[HTMLElement]|select',
  14063. 'dl^[HTMLElement]|!compact',
  14064. 'datalist^[HTMLElement]|',
  14065. 'details^[HTMLElement]|!open',
  14066. 'dialog^[HTMLElement]|!open,returnValue',
  14067. 'dir^[HTMLElement]|!compact',
  14068. 'div^[HTMLElement]|align',
  14069. 'embed^[HTMLElement]|align,height,name,src,type,width',
  14070. 'fieldset^[HTMLElement]|!disabled,name',
  14071. 'font^[HTMLElement]|color,face,size',
  14072. 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
  14073. 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
  14074. 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
  14075. 'hr^[HTMLElement]|align,color,!noShade,size,width',
  14076. 'head^[HTMLElement]|',
  14077. 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
  14078. 'html^[HTMLElement]|version',
  14079. 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
  14080. 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
  14081. 'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width',
  14082. 'li^[HTMLElement]|type,#value',
  14083. 'label^[HTMLElement]|htmlFor',
  14084. 'legend^[HTMLElement]|align',
  14085. 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
  14086. 'map^[HTMLElement]|name',
  14087. 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
  14088. 'menu^[HTMLElement]|!compact',
  14089. 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
  14090. 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
  14091. 'ins,del^[HTMLElement]|cite,dateTime',
  14092. 'ol^[HTMLElement]|!compact,!reversed,#start,type',
  14093. 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
  14094. 'optgroup^[HTMLElement]|!disabled,label',
  14095. 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
  14096. 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
  14097. 'p^[HTMLElement]|align',
  14098. 'param^[HTMLElement]|name,type,value,valueType',
  14099. 'picture^[HTMLElement]|',
  14100. 'pre^[HTMLElement]|#width',
  14101. 'progress^[HTMLElement]|#max,#value',
  14102. 'q,blockquote,cite^[HTMLElement]|',
  14103. 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
  14104. 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
  14105. 'shadow^[HTMLElement]|',
  14106. 'slot^[HTMLElement]|name',
  14107. 'source^[HTMLElement]|media,sizes,src,srcset,type',
  14108. 'span^[HTMLElement]|',
  14109. 'style^[HTMLElement]|!disabled,media,type',
  14110. 'caption^[HTMLElement]|align',
  14111. 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
  14112. 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
  14113. 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
  14114. 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
  14115. 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
  14116. 'template^[HTMLElement]|',
  14117. 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
  14118. 'title^[HTMLElement]|text',
  14119. 'track^[HTMLElement]|!default,kind,label,src,srclang',
  14120. 'ul^[HTMLElement]|!compact,type',
  14121. 'unknown^[HTMLElement]|',
  14122. 'video^media|#height,poster,#width',
  14123. ':svg:a^:svg:graphics|',
  14124. ':svg:animate^:svg:animation|',
  14125. ':svg:animateMotion^:svg:animation|',
  14126. ':svg:animateTransform^:svg:animation|',
  14127. ':svg:circle^:svg:geometry|',
  14128. ':svg:clipPath^:svg:graphics|',
  14129. ':svg:defs^:svg:graphics|',
  14130. ':svg:desc^:svg:|',
  14131. ':svg:discard^:svg:|',
  14132. ':svg:ellipse^:svg:geometry|',
  14133. ':svg:feBlend^:svg:|',
  14134. ':svg:feColorMatrix^:svg:|',
  14135. ':svg:feComponentTransfer^:svg:|',
  14136. ':svg:feComposite^:svg:|',
  14137. ':svg:feConvolveMatrix^:svg:|',
  14138. ':svg:feDiffuseLighting^:svg:|',
  14139. ':svg:feDisplacementMap^:svg:|',
  14140. ':svg:feDistantLight^:svg:|',
  14141. ':svg:feDropShadow^:svg:|',
  14142. ':svg:feFlood^:svg:|',
  14143. ':svg:feFuncA^:svg:componentTransferFunction|',
  14144. ':svg:feFuncB^:svg:componentTransferFunction|',
  14145. ':svg:feFuncG^:svg:componentTransferFunction|',
  14146. ':svg:feFuncR^:svg:componentTransferFunction|',
  14147. ':svg:feGaussianBlur^:svg:|',
  14148. ':svg:feImage^:svg:|',
  14149. ':svg:feMerge^:svg:|',
  14150. ':svg:feMergeNode^:svg:|',
  14151. ':svg:feMorphology^:svg:|',
  14152. ':svg:feOffset^:svg:|',
  14153. ':svg:fePointLight^:svg:|',
  14154. ':svg:feSpecularLighting^:svg:|',
  14155. ':svg:feSpotLight^:svg:|',
  14156. ':svg:feTile^:svg:|',
  14157. ':svg:feTurbulence^:svg:|',
  14158. ':svg:filter^:svg:|',
  14159. ':svg:foreignObject^:svg:graphics|',
  14160. ':svg:g^:svg:graphics|',
  14161. ':svg:image^:svg:graphics|',
  14162. ':svg:line^:svg:geometry|',
  14163. ':svg:linearGradient^:svg:gradient|',
  14164. ':svg:mpath^:svg:|',
  14165. ':svg:marker^:svg:|',
  14166. ':svg:mask^:svg:|',
  14167. ':svg:metadata^:svg:|',
  14168. ':svg:path^:svg:geometry|',
  14169. ':svg:pattern^:svg:|',
  14170. ':svg:polygon^:svg:geometry|',
  14171. ':svg:polyline^:svg:geometry|',
  14172. ':svg:radialGradient^:svg:gradient|',
  14173. ':svg:rect^:svg:geometry|',
  14174. ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
  14175. ':svg:script^:svg:|type',
  14176. ':svg:set^:svg:animation|',
  14177. ':svg:stop^:svg:|',
  14178. ':svg:style^:svg:|!disabled,media,title,type',
  14179. ':svg:switch^:svg:graphics|',
  14180. ':svg:symbol^:svg:|',
  14181. ':svg:tspan^:svg:textPositioning|',
  14182. ':svg:text^:svg:textPositioning|',
  14183. ':svg:textPath^:svg:textContent|',
  14184. ':svg:title^:svg:|',
  14185. ':svg:use^:svg:graphics|',
  14186. ':svg:view^:svg:|#zoomAndPan',
  14187. 'data^[HTMLElement]|value',
  14188. 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
  14189. 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
  14190. 'summary^[HTMLElement]|',
  14191. 'time^[HTMLElement]|dateTime',
  14192. ':svg:cursor^:svg:|',
  14193. ];
  14194. var _ATTR_TO_PROP = {
  14195. 'class': 'className',
  14196. 'for': 'htmlFor',
  14197. 'formaction': 'formAction',
  14198. 'innerHtml': 'innerHTML',
  14199. 'readonly': 'readOnly',
  14200. 'tabindex': 'tabIndex',
  14201. };
  14202. var DomElementSchemaRegistry = /** @class */ (function (_super) {
  14203. __extends(DomElementSchemaRegistry, _super);
  14204. function DomElementSchemaRegistry() {
  14205. var _this = _super.call(this) || this;
  14206. _this._schema = {};
  14207. SCHEMA.forEach(function (encodedType) {
  14208. var type = {};
  14209. var _a = __read(encodedType.split('|'), 2), strType = _a[0], strProperties = _a[1];
  14210. var properties = strProperties.split(',');
  14211. var _b = __read(strType.split('^'), 2), typeNames = _b[0], superName = _b[1];
  14212. typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
  14213. var superType = superName && _this._schema[superName.toLowerCase()];
  14214. if (superType) {
  14215. Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; });
  14216. }
  14217. properties.forEach(function (property) {
  14218. if (property.length > 0) {
  14219. switch (property[0]) {
  14220. case '*':
  14221. // We don't yet support events.
  14222. // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
  14223. // will
  14224. // almost certainly introduce bad XSS vulnerabilities.
  14225. // type[property.substring(1)] = EVENT;
  14226. break;
  14227. case '!':
  14228. type[property.substring(1)] = BOOLEAN;
  14229. break;
  14230. case '#':
  14231. type[property.substring(1)] = NUMBER;
  14232. break;
  14233. case '%':
  14234. type[property.substring(1)] = OBJECT;
  14235. break;
  14236. default:
  14237. type[property] = STRING;
  14238. }
  14239. }
  14240. });
  14241. });
  14242. return _this;
  14243. }
  14244. DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
  14245. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  14246. return true;
  14247. }
  14248. if (tagName.indexOf('-') > -1) {
  14249. if (isNgContainer(tagName) || isNgContent(tagName)) {
  14250. return false;
  14251. }
  14252. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  14253. // Can't tell now as we don't know which properties a custom element will get
  14254. // once it is instantiated
  14255. return true;
  14256. }
  14257. }
  14258. var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
  14259. return !!elementProperties[propName];
  14260. };
  14261. DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
  14262. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  14263. return true;
  14264. }
  14265. if (tagName.indexOf('-') > -1) {
  14266. if (isNgContainer(tagName) || isNgContent(tagName)) {
  14267. return true;
  14268. }
  14269. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  14270. // Allow any custom elements
  14271. return true;
  14272. }
  14273. }
  14274. return !!this._schema[tagName.toLowerCase()];
  14275. };
  14276. /**
  14277. * securityContext returns the security context for the given property on the given DOM tag.
  14278. *
  14279. * Tag and property name are statically known and cannot change at runtime, i.e. it is not
  14280. * possible to bind a value into a changing attribute or tag name.
  14281. *
  14282. * The filtering is based on a list of allowed tags|attributes. All attributes in the schema
  14283. * above are assumed to have the 'NONE' security context, i.e. that they are safe inert
  14284. * string values. Only specific well known attack vectors are assigned their appropriate context.
  14285. */
  14286. DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
  14287. if (isAttribute) {
  14288. // NB: For security purposes, use the mapped property name, not the attribute name.
  14289. propName = this.getMappedPropName(propName);
  14290. }
  14291. // Make sure comparisons are case insensitive, so that case differences between attribute and
  14292. // property names do not have a security impact.
  14293. tagName = tagName.toLowerCase();
  14294. propName = propName.toLowerCase();
  14295. var ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
  14296. if (ctx) {
  14297. return ctx;
  14298. }
  14299. ctx = SECURITY_SCHEMA()['*|' + propName];
  14300. return ctx ? ctx : SecurityContext.NONE;
  14301. };
  14302. DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; };
  14303. DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; };
  14304. DomElementSchemaRegistry.prototype.validateProperty = function (name) {
  14305. if (name.toLowerCase().startsWith('on')) {
  14306. var msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
  14307. ("please use (" + name.slice(2) + ")=...") +
  14308. ("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
  14309. " current module.";
  14310. return { error: true, msg: msg };
  14311. }
  14312. else {
  14313. return { error: false };
  14314. }
  14315. };
  14316. DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
  14317. if (name.toLowerCase().startsWith('on')) {
  14318. var msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
  14319. ("please use (" + name.slice(2) + ")=...");
  14320. return { error: true, msg: msg };
  14321. }
  14322. else {
  14323. return { error: false };
  14324. }
  14325. };
  14326. DomElementSchemaRegistry.prototype.allKnownElementNames = function () { return Object.keys(this._schema); };
  14327. DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
  14328. return dashCaseToCamelCase(propName);
  14329. };
  14330. DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
  14331. var unit = '';
  14332. var strVal = val.toString().trim();
  14333. var errorMsg = null;
  14334. if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
  14335. if (typeof val === 'number') {
  14336. unit = 'px';
  14337. }
  14338. else {
  14339. var valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
  14340. if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
  14341. errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
  14342. }
  14343. }
  14344. }
  14345. return { error: errorMsg, value: strVal + unit };
  14346. };
  14347. return DomElementSchemaRegistry;
  14348. }(ElementSchemaRegistry));
  14349. function _isPixelDimensionStyle(prop) {
  14350. switch (prop) {
  14351. case 'width':
  14352. case 'height':
  14353. case 'minWidth':
  14354. case 'minHeight':
  14355. case 'maxWidth':
  14356. case 'maxHeight':
  14357. case 'left':
  14358. case 'top':
  14359. case 'bottom':
  14360. case 'right':
  14361. case 'fontSize':
  14362. case 'outlineWidth':
  14363. case 'outlineOffset':
  14364. case 'paddingTop':
  14365. case 'paddingLeft':
  14366. case 'paddingBottom':
  14367. case 'paddingRight':
  14368. case 'marginTop':
  14369. case 'marginLeft':
  14370. case 'marginBottom':
  14371. case 'marginRight':
  14372. case 'borderRadius':
  14373. case 'borderWidth':
  14374. case 'borderTopWidth':
  14375. case 'borderLeftWidth':
  14376. case 'borderRightWidth':
  14377. case 'borderBottomWidth':
  14378. case 'textIndent':
  14379. return true;
  14380. default:
  14381. return false;
  14382. }
  14383. }
  14384. /**
  14385. * @license
  14386. * Copyright Google Inc. All Rights Reserved.
  14387. *
  14388. * Use of this source code is governed by an MIT-style license that can be
  14389. * found in the LICENSE file at https://angular.io/license
  14390. */
  14391. var BIND_NAME_REGEXP$1 = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  14392. // Group 1 = "bind-"
  14393. var KW_BIND_IDX$1 = 1;
  14394. // Group 2 = "let-"
  14395. var KW_LET_IDX$1 = 2;
  14396. // Group 3 = "ref-/#"
  14397. var KW_REF_IDX$1 = 3;
  14398. // Group 4 = "on-"
  14399. var KW_ON_IDX$1 = 4;
  14400. // Group 5 = "bindon-"
  14401. var KW_BINDON_IDX$1 = 5;
  14402. // Group 6 = "@"
  14403. var KW_AT_IDX$1 = 6;
  14404. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  14405. var IDENT_KW_IDX$1 = 7;
  14406. // Group 8 = identifier inside [()]
  14407. var IDENT_BANANA_BOX_IDX$1 = 8;
  14408. // Group 9 = identifier inside []
  14409. var IDENT_PROPERTY_IDX$1 = 9;
  14410. // Group 10 = identifier inside ()
  14411. var IDENT_EVENT_IDX$1 = 10;
  14412. var TEMPLATE_ATTR_PREFIX$1 = '*';
  14413. function htmlAstToRender3Ast(htmlNodes, bindingParser) {
  14414. var transformer = new HtmlAstToIvyAst(bindingParser);
  14415. var ivyNodes = visitAll$1(transformer, htmlNodes);
  14416. // Errors might originate in either the binding parser or the html to ivy transformer
  14417. var allErrors = bindingParser.errors.concat(transformer.errors);
  14418. var errors = allErrors.filter(function (e) { return e.level === ParseErrorLevel.ERROR; });
  14419. if (errors.length > 0) {
  14420. var errorString = errors.join('\n');
  14421. throw syntaxError("Template parse errors:\n" + errorString, errors);
  14422. }
  14423. return {
  14424. nodes: ivyNodes,
  14425. errors: allErrors,
  14426. styleUrls: transformer.styleUrls,
  14427. styles: transformer.styles,
  14428. };
  14429. }
  14430. var HtmlAstToIvyAst = /** @class */ (function () {
  14431. function HtmlAstToIvyAst(bindingParser) {
  14432. this.bindingParser = bindingParser;
  14433. this.errors = [];
  14434. this.styles = [];
  14435. this.styleUrls = [];
  14436. }
  14437. // HTML visitor
  14438. HtmlAstToIvyAst.prototype.visitElement = function (element) {
  14439. var _this = this;
  14440. var e_1, _a;
  14441. var preparsedElement = preparseElement(element);
  14442. if (preparsedElement.type === PreparsedElementType.SCRIPT) {
  14443. return null;
  14444. }
  14445. else if (preparsedElement.type === PreparsedElementType.STYLE) {
  14446. var contents = textContents(element);
  14447. if (contents !== null) {
  14448. this.styles.push(contents);
  14449. }
  14450. return null;
  14451. }
  14452. else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  14453. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  14454. this.styleUrls.push(preparsedElement.hrefAttr);
  14455. return null;
  14456. }
  14457. // Whether the element is a `<ng-template>`
  14458. var isTemplateElement = isNgTemplate(element.name);
  14459. var parsedProperties = [];
  14460. var boundEvents = [];
  14461. var variables = [];
  14462. var references = [];
  14463. var attributes = [];
  14464. var i18nAttrsMeta = {};
  14465. var templateParsedProperties = [];
  14466. var templateVariables = [];
  14467. // Whether the element has any *-attribute
  14468. var elementHasInlineTemplate = false;
  14469. try {
  14470. for (var _b = __values(element.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
  14471. var attribute = _c.value;
  14472. var hasBinding = false;
  14473. var normalizedName = normalizeAttributeName(attribute.name);
  14474. // `*attr` defines template bindings
  14475. var isTemplateBinding = false;
  14476. if (attribute.i18n) {
  14477. i18nAttrsMeta[attribute.name] = attribute.i18n;
  14478. }
  14479. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
  14480. // *-attributes
  14481. if (elementHasInlineTemplate) {
  14482. this.reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attribute.sourceSpan);
  14483. }
  14484. isTemplateBinding = true;
  14485. elementHasInlineTemplate = true;
  14486. var templateValue = attribute.value;
  14487. var templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
  14488. var parsedVariables = [];
  14489. this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, [], templateParsedProperties, parsedVariables);
  14490. templateVariables.push.apply(templateVariables, __spread(parsedVariables.map(function (v) { return new Variable(v.name, v.value, v.sourceSpan); })));
  14491. }
  14492. else {
  14493. // Check for variables, events, property bindings, interpolation
  14494. hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
  14495. }
  14496. if (!hasBinding && !isTemplateBinding) {
  14497. // don't include the bindings as attributes as well in the AST
  14498. attributes.push(this.visitAttribute(attribute));
  14499. }
  14500. }
  14501. }
  14502. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  14503. finally {
  14504. try {
  14505. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  14506. }
  14507. finally { if (e_1) throw e_1.error; }
  14508. }
  14509. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
  14510. var parsedElement;
  14511. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  14512. // `<ng-content>`
  14513. if (element.children &&
  14514. !element.children.every(function (node) { return isEmptyTextNode(node) || isCommentNode(node); })) {
  14515. this.reportError("<ng-content> element cannot have content.", element.sourceSpan);
  14516. }
  14517. var selector = preparsedElement.selectAttr;
  14518. var attrs = element.attrs.map(function (attr) { return _this.visitAttribute(attr); });
  14519. parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
  14520. }
  14521. else if (isTemplateElement) {
  14522. // `<ng-template>`
  14523. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  14524. parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14525. }
  14526. else {
  14527. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  14528. parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14529. }
  14530. if (elementHasInlineTemplate) {
  14531. // If this node is an inline-template (e.g. has *ngFor) then we need to create a template
  14532. // node that contains this node.
  14533. // Moreover, if the node is an element, then we need to hoist its attributes to the template
  14534. // node for matching against content projection selectors.
  14535. var attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
  14536. var templateAttrs_1 = [];
  14537. attrs.literal.forEach(function (attr) { return templateAttrs_1.push(attr); });
  14538. attrs.bound.forEach(function (attr) { return templateAttrs_1.push(attr); });
  14539. var hoistedAttrs = parsedElement instanceof Element ?
  14540. {
  14541. attributes: parsedElement.attributes,
  14542. inputs: parsedElement.inputs,
  14543. outputs: parsedElement.outputs,
  14544. } :
  14545. { attributes: [], inputs: [], outputs: [] };
  14546. // TODO(pk): test for this case
  14547. parsedElement = new Template(parsedElement.name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs_1, [parsedElement], [ /* no references */], templateVariables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14548. }
  14549. return parsedElement;
  14550. };
  14551. HtmlAstToIvyAst.prototype.visitAttribute = function (attribute) {
  14552. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.valueSpan, attribute.i18n);
  14553. };
  14554. HtmlAstToIvyAst.prototype.visitText = function (text) {
  14555. return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
  14556. };
  14557. HtmlAstToIvyAst.prototype.visitExpansion = function (expansion) {
  14558. var _this = this;
  14559. var meta = expansion.i18n;
  14560. // do not generate Icu in case it was created
  14561. // outside of i18n block in a template
  14562. if (!meta) {
  14563. return null;
  14564. }
  14565. var vars = {};
  14566. var placeholders = {};
  14567. // extract VARs from ICUs - we process them separately while
  14568. // assembling resulting message via goog.getMsg function, since
  14569. // we need to pass them to top-level goog.getMsg call
  14570. Object.keys(meta.placeholders).forEach(function (key) {
  14571. var value = meta.placeholders[key];
  14572. if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
  14573. var config = _this.bindingParser.interpolationConfig;
  14574. // ICU expression is a plain string, not wrapped into start
  14575. // and end tags, so we wrap it before passing to binding parser
  14576. var wrapped = "" + config.start + value + config.end;
  14577. vars[key] = _this._visitTextWithInterpolation(wrapped, expansion.sourceSpan);
  14578. }
  14579. else {
  14580. placeholders[key] = _this._visitTextWithInterpolation(value, expansion.sourceSpan);
  14581. }
  14582. });
  14583. return new Icu(vars, placeholders, expansion.sourceSpan, meta);
  14584. };
  14585. HtmlAstToIvyAst.prototype.visitExpansionCase = function (expansionCase) { return null; };
  14586. HtmlAstToIvyAst.prototype.visitComment = function (comment) { return null; };
  14587. // convert view engine `ParsedProperty` to a format suitable for IVY
  14588. HtmlAstToIvyAst.prototype.extractAttributes = function (elementName, properties, i18nPropsMeta) {
  14589. var _this = this;
  14590. var bound = [];
  14591. var literal = [];
  14592. properties.forEach(function (prop) {
  14593. var i18n = i18nPropsMeta[prop.name];
  14594. if (prop.isLiteral) {
  14595. literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, undefined, i18n));
  14596. }
  14597. else {
  14598. // Note that validation is skipped and property mapping is disabled
  14599. // due to the fact that we need to make sure a given prop is not an
  14600. // input of a directive and directive matching happens at runtime.
  14601. var bep = _this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
  14602. bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
  14603. }
  14604. });
  14605. return { bound: bound, literal: literal };
  14606. };
  14607. HtmlAstToIvyAst.prototype.parseAttribute = function (isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
  14608. var name = normalizeAttributeName(attribute.name);
  14609. var value = attribute.value;
  14610. var srcSpan = attribute.sourceSpan;
  14611. var bindParts = name.match(BIND_NAME_REGEXP$1);
  14612. var hasBinding = false;
  14613. if (bindParts) {
  14614. hasBinding = true;
  14615. if (bindParts[KW_BIND_IDX$1] != null) {
  14616. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14617. }
  14618. else if (bindParts[KW_LET_IDX$1]) {
  14619. if (isTemplateElement) {
  14620. var identifier = bindParts[IDENT_KW_IDX$1];
  14621. this.parseVariable(identifier, value, srcSpan, variables);
  14622. }
  14623. else {
  14624. this.reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  14625. }
  14626. }
  14627. else if (bindParts[KW_REF_IDX$1]) {
  14628. var identifier = bindParts[IDENT_KW_IDX$1];
  14629. this.parseReference(identifier, value, srcSpan, references);
  14630. }
  14631. else if (bindParts[KW_ON_IDX$1]) {
  14632. var events = [];
  14633. this.bindingParser.parseEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14634. addEvents(events, boundEvents);
  14635. }
  14636. else if (bindParts[KW_BINDON_IDX$1]) {
  14637. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14638. this.parseAssignmentEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14639. }
  14640. else if (bindParts[KW_AT_IDX$1]) {
  14641. this.bindingParser.parseLiteralAttr(name, value, srcSpan, matchableAttributes, parsedProperties);
  14642. }
  14643. else if (bindParts[IDENT_BANANA_BOX_IDX$1]) {
  14644. this.bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14645. this.parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14646. }
  14647. else if (bindParts[IDENT_PROPERTY_IDX$1]) {
  14648. this.bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14649. }
  14650. else if (bindParts[IDENT_EVENT_IDX$1]) {
  14651. var events = [];
  14652. this.bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14653. addEvents(events, boundEvents);
  14654. }
  14655. }
  14656. else {
  14657. hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, matchableAttributes, parsedProperties);
  14658. }
  14659. return hasBinding;
  14660. };
  14661. HtmlAstToIvyAst.prototype._visitTextWithInterpolation = function (value, sourceSpan, i18n) {
  14662. var valueNoNgsp = replaceNgsp(value);
  14663. var expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
  14664. return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
  14665. };
  14666. HtmlAstToIvyAst.prototype.parseVariable = function (identifier, value, sourceSpan, variables) {
  14667. if (identifier.indexOf('-') > -1) {
  14668. this.reportError("\"-\" is not allowed in variable names", sourceSpan);
  14669. }
  14670. variables.push(new Variable(identifier, value, sourceSpan));
  14671. };
  14672. HtmlAstToIvyAst.prototype.parseReference = function (identifier, value, sourceSpan, references) {
  14673. if (identifier.indexOf('-') > -1) {
  14674. this.reportError("\"-\" is not allowed in reference names", sourceSpan);
  14675. }
  14676. references.push(new Reference(identifier, value, sourceSpan));
  14677. };
  14678. HtmlAstToIvyAst.prototype.parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents) {
  14679. var events = [];
  14680. this.bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events);
  14681. addEvents(events, boundEvents);
  14682. };
  14683. HtmlAstToIvyAst.prototype.reportError = function (message, sourceSpan, level) {
  14684. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  14685. this.errors.push(new ParseError(sourceSpan, message, level));
  14686. };
  14687. return HtmlAstToIvyAst;
  14688. }());
  14689. var NonBindableVisitor$1 = /** @class */ (function () {
  14690. function NonBindableVisitor() {
  14691. }
  14692. NonBindableVisitor.prototype.visitElement = function (ast) {
  14693. var preparsedElement = preparseElement(ast);
  14694. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  14695. preparsedElement.type === PreparsedElementType.STYLE ||
  14696. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  14697. // Skipping <script> for security reasons
  14698. // Skipping <style> and stylesheets as we already processed them
  14699. // in the StyleCompiler
  14700. return null;
  14701. }
  14702. var children = visitAll$1(this, ast.children, null);
  14703. return new Element(ast.name, visitAll$1(this, ast.attrs),
  14704. /* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
  14705. };
  14706. NonBindableVisitor.prototype.visitComment = function (comment) { return null; };
  14707. NonBindableVisitor.prototype.visitAttribute = function (attribute) {
  14708. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, undefined, attribute.i18n);
  14709. };
  14710. NonBindableVisitor.prototype.visitText = function (text) { return new Text(text.value, text.sourceSpan); };
  14711. NonBindableVisitor.prototype.visitExpansion = function (expansion) { return null; };
  14712. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase) { return null; };
  14713. return NonBindableVisitor;
  14714. }());
  14715. var NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
  14716. function normalizeAttributeName(attrName) {
  14717. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  14718. }
  14719. function addEvents(events, boundEvents) {
  14720. boundEvents.push.apply(boundEvents, __spread(events.map(function (e) { return BoundEvent.fromParsedEvent(e); })));
  14721. }
  14722. function isEmptyTextNode(node) {
  14723. return node instanceof Text$3 && node.value.trim().length == 0;
  14724. }
  14725. function isCommentNode(node) {
  14726. return node instanceof Comment;
  14727. }
  14728. function textContents(node) {
  14729. if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
  14730. return null;
  14731. }
  14732. else {
  14733. return node.children[0].value;
  14734. }
  14735. }
  14736. /**
  14737. * @license
  14738. * Copyright Google Inc. All Rights Reserved.
  14739. *
  14740. * Use of this source code is governed by an MIT-style license that can be
  14741. * found in the LICENSE file at https://angular.io/license
  14742. */
  14743. var TagType;
  14744. (function (TagType) {
  14745. TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
  14746. TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
  14747. TagType[TagType["PROJECTION"] = 2] = "PROJECTION";
  14748. })(TagType || (TagType = {}));
  14749. /**
  14750. * Generates an object that is used as a shared state between parent and all child contexts.
  14751. */
  14752. function setupRegistry() {
  14753. return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
  14754. }
  14755. /**
  14756. * I18nContext is a helper class which keeps track of all i18n-related aspects
  14757. * (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
  14758. *
  14759. * When we enter a nested template, the top-level context is being passed down
  14760. * to the nested component, which uses this context to generate a child instance
  14761. * of I18nContext class (to handle nested template) and at the end, reconciles it back
  14762. * with the parent context.
  14763. *
  14764. * @param index Instruction index of i18nStart, which initiates this context
  14765. * @param ref Reference to a translation const that represents the content if thus context
  14766. * @param level Nestng level defined for child contexts
  14767. * @param templateIndex Instruction index of a template which this context belongs to
  14768. * @param meta Meta information (id, meaning, description, etc) associated with this context
  14769. */
  14770. var I18nContext = /** @class */ (function () {
  14771. function I18nContext(index, ref, level, templateIndex, meta, registry) {
  14772. if (level === void 0) { level = 0; }
  14773. if (templateIndex === void 0) { templateIndex = null; }
  14774. this.index = index;
  14775. this.ref = ref;
  14776. this.level = level;
  14777. this.templateIndex = templateIndex;
  14778. this.meta = meta;
  14779. this.registry = registry;
  14780. this.bindings = new Set();
  14781. this.placeholders = new Map();
  14782. this.isEmitted = false;
  14783. this._unresolvedCtxCount = 0;
  14784. this._registry = registry || setupRegistry();
  14785. this.id = this._registry.getUniqueId();
  14786. }
  14787. I18nContext.prototype.appendTag = function (type, node, index, closed) {
  14788. if (node.isVoid && closed) {
  14789. return; // ignore "close" for void tags
  14790. }
  14791. var ph = node.isVoid || !closed ? node.startName : node.closeName;
  14792. var content = { type: type, index: index, ctx: this.id, isVoid: node.isVoid, closed: closed };
  14793. updatePlaceholderMap(this.placeholders, ph, content);
  14794. };
  14795. Object.defineProperty(I18nContext.prototype, "icus", {
  14796. get: function () { return this._registry.icus; },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. Object.defineProperty(I18nContext.prototype, "isRoot", {
  14801. get: function () { return this.level === 0; },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(I18nContext.prototype, "isResolved", {
  14806. get: function () { return this._unresolvedCtxCount === 0; },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. I18nContext.prototype.getSerializedPlaceholders = function () {
  14811. var result = new Map();
  14812. this.placeholders.forEach(function (values, key) { return result.set(key, values.map(serializePlaceholderValue)); });
  14813. return result;
  14814. };
  14815. // public API to accumulate i18n-related content
  14816. I18nContext.prototype.appendBinding = function (binding) { this.bindings.add(binding); };
  14817. I18nContext.prototype.appendIcu = function (name, ref) {
  14818. updatePlaceholderMap(this._registry.icus, name, ref);
  14819. };
  14820. I18nContext.prototype.appendBoundText = function (node) {
  14821. var _this = this;
  14822. var phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
  14823. phs.forEach(function (values, key) { return updatePlaceholderMap.apply(void 0, __spread([_this.placeholders, key], values)); });
  14824. };
  14825. I18nContext.prototype.appendTemplate = function (node, index) {
  14826. // add open and close tags at the same time,
  14827. // since we process nested templates separately
  14828. this.appendTag(TagType.TEMPLATE, node, index, false);
  14829. this.appendTag(TagType.TEMPLATE, node, index, true);
  14830. this._unresolvedCtxCount++;
  14831. };
  14832. I18nContext.prototype.appendElement = function (node, index, closed) {
  14833. this.appendTag(TagType.ELEMENT, node, index, closed);
  14834. };
  14835. I18nContext.prototype.appendProjection = function (node, index) {
  14836. // add open and close tags at the same time,
  14837. // since we process projected content separately
  14838. this.appendTag(TagType.PROJECTION, node, index, false);
  14839. this.appendTag(TagType.PROJECTION, node, index, true);
  14840. };
  14841. /**
  14842. * Generates an instance of a child context based on the root one,
  14843. * when we enter a nested template within I18n section.
  14844. *
  14845. * @param index Instruction index of corresponding i18nStart, which initiates this context
  14846. * @param templateIndex Instruction index of a template which this context belongs to
  14847. * @param meta Meta information (id, meaning, description, etc) associated with this context
  14848. *
  14849. * @returns I18nContext instance
  14850. */
  14851. I18nContext.prototype.forkChildContext = function (index, templateIndex, meta) {
  14852. return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
  14853. };
  14854. /**
  14855. * Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
  14856. *
  14857. * @param context Child I18nContext instance to be reconciled with parent context.
  14858. */
  14859. I18nContext.prototype.reconcileChildContext = function (context) {
  14860. var _this = this;
  14861. // set the right context id for open and close
  14862. // template tags, so we can use it as sub-block ids
  14863. ['start', 'close'].forEach(function (op) {
  14864. var key = context.meta[op + "Name"];
  14865. var phs = _this.placeholders.get(key) || [];
  14866. var tag = phs.find(findTemplateFn(_this.id, context.templateIndex));
  14867. if (tag) {
  14868. tag.ctx = context.id;
  14869. }
  14870. });
  14871. // reconcile placeholders
  14872. var childPhs = context.placeholders;
  14873. childPhs.forEach(function (values, key) {
  14874. var phs = _this.placeholders.get(key);
  14875. if (!phs) {
  14876. _this.placeholders.set(key, values);
  14877. return;
  14878. }
  14879. // try to find matching template...
  14880. var tmplIdx = findIndex(phs, findTemplateFn(context.id, context.templateIndex));
  14881. if (tmplIdx >= 0) {
  14882. // ... if found - replace it with nested template content
  14883. var isCloseTag = key.startsWith('CLOSE');
  14884. var isTemplateTag = key.endsWith('NG-TEMPLATE');
  14885. if (isTemplateTag) {
  14886. // current template's content is placed before or after
  14887. // parent template tag, depending on the open/close atrribute
  14888. phs.splice.apply(phs, __spread([tmplIdx + (isCloseTag ? 0 : 1), 0], values));
  14889. }
  14890. else {
  14891. var idx = isCloseTag ? values.length - 1 : 0;
  14892. values[idx].tmpl = phs[tmplIdx];
  14893. phs.splice.apply(phs, __spread([tmplIdx, 1], values));
  14894. }
  14895. }
  14896. else {
  14897. // ... otherwise just append content to placeholder value
  14898. phs.push.apply(phs, __spread(values));
  14899. }
  14900. _this.placeholders.set(key, phs);
  14901. });
  14902. this._unresolvedCtxCount--;
  14903. };
  14904. return I18nContext;
  14905. }());
  14906. //
  14907. // Helper methods
  14908. //
  14909. function wrap(symbol, index, contextId, closed) {
  14910. var state = closed ? '/' : '';
  14911. return wrapI18nPlaceholder("" + state + symbol + index, contextId);
  14912. }
  14913. function wrapTag(symbol, _a, closed) {
  14914. var index = _a.index, ctx = _a.ctx, isVoid = _a.isVoid;
  14915. return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
  14916. wrap(symbol, index, ctx, closed);
  14917. }
  14918. function findTemplateFn(ctx, templateIndex) {
  14919. return function (token) { return typeof token === 'object' && token.type === TagType.TEMPLATE &&
  14920. token.index === templateIndex && token.ctx === ctx; };
  14921. }
  14922. function serializePlaceholderValue(value) {
  14923. var element = function (data, closed) { return wrapTag('#', data, closed); };
  14924. var template = function (data, closed) { return wrapTag('*', data, closed); };
  14925. var projection = function (data, closed) { return wrapTag('!', data, closed); };
  14926. switch (value.type) {
  14927. case TagType.ELEMENT:
  14928. // close element tag
  14929. if (value.closed) {
  14930. return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
  14931. }
  14932. // open element tag that also initiates a template
  14933. if (value.tmpl) {
  14934. return template(value.tmpl) + element(value) +
  14935. (value.isVoid ? template(value.tmpl, true) : '');
  14936. }
  14937. return element(value);
  14938. case TagType.TEMPLATE:
  14939. return template(value, value.closed);
  14940. case TagType.PROJECTION:
  14941. return projection(value, value.closed);
  14942. default:
  14943. return value;
  14944. }
  14945. }
  14946. /**
  14947. * @license
  14948. * Copyright Google Inc. All Rights Reserved.
  14949. *
  14950. * Use of this source code is governed by an MIT-style license that can be
  14951. * found in the LICENSE file at https://angular.io/license
  14952. */
  14953. var TAG_TO_PLACEHOLDER_NAMES = {
  14954. 'A': 'LINK',
  14955. 'B': 'BOLD_TEXT',
  14956. 'BR': 'LINE_BREAK',
  14957. 'EM': 'EMPHASISED_TEXT',
  14958. 'H1': 'HEADING_LEVEL1',
  14959. 'H2': 'HEADING_LEVEL2',
  14960. 'H3': 'HEADING_LEVEL3',
  14961. 'H4': 'HEADING_LEVEL4',
  14962. 'H5': 'HEADING_LEVEL5',
  14963. 'H6': 'HEADING_LEVEL6',
  14964. 'HR': 'HORIZONTAL_RULE',
  14965. 'I': 'ITALIC_TEXT',
  14966. 'LI': 'LIST_ITEM',
  14967. 'LINK': 'MEDIA_LINK',
  14968. 'OL': 'ORDERED_LIST',
  14969. 'P': 'PARAGRAPH',
  14970. 'Q': 'QUOTATION',
  14971. 'S': 'STRIKETHROUGH_TEXT',
  14972. 'SMALL': 'SMALL_TEXT',
  14973. 'SUB': 'SUBSTRIPT',
  14974. 'SUP': 'SUPERSCRIPT',
  14975. 'TBODY': 'TABLE_BODY',
  14976. 'TD': 'TABLE_CELL',
  14977. 'TFOOT': 'TABLE_FOOTER',
  14978. 'TH': 'TABLE_HEADER_CELL',
  14979. 'THEAD': 'TABLE_HEADER',
  14980. 'TR': 'TABLE_ROW',
  14981. 'TT': 'MONOSPACED_TEXT',
  14982. 'U': 'UNDERLINED_TEXT',
  14983. 'UL': 'UNORDERED_LIST',
  14984. };
  14985. /**
  14986. * Creates unique names for placeholder with different content.
  14987. *
  14988. * Returns the same placeholder name when the content is identical.
  14989. */
  14990. var PlaceholderRegistry = /** @class */ (function () {
  14991. function PlaceholderRegistry() {
  14992. // Count the occurrence of the base name top generate a unique name
  14993. this._placeHolderNameCounts = {};
  14994. // Maps signature to placeholder names
  14995. this._signatureToName = {};
  14996. }
  14997. PlaceholderRegistry.prototype.getStartTagPlaceholderName = function (tag, attrs, isVoid) {
  14998. var signature = this._hashTag(tag, attrs, isVoid);
  14999. if (this._signatureToName[signature]) {
  15000. return this._signatureToName[signature];
  15001. }
  15002. var upperTag = tag.toUpperCase();
  15003. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  15004. var name = this._generateUniqueName(isVoid ? baseName : "START_" + baseName);
  15005. this._signatureToName[signature] = name;
  15006. return name;
  15007. };
  15008. PlaceholderRegistry.prototype.getCloseTagPlaceholderName = function (tag) {
  15009. var signature = this._hashClosingTag(tag);
  15010. if (this._signatureToName[signature]) {
  15011. return this._signatureToName[signature];
  15012. }
  15013. var upperTag = tag.toUpperCase();
  15014. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  15015. var name = this._generateUniqueName("CLOSE_" + baseName);
  15016. this._signatureToName[signature] = name;
  15017. return name;
  15018. };
  15019. PlaceholderRegistry.prototype.getPlaceholderName = function (name, content) {
  15020. var upperName = name.toUpperCase();
  15021. var signature = "PH: " + upperName + "=" + content;
  15022. if (this._signatureToName[signature]) {
  15023. return this._signatureToName[signature];
  15024. }
  15025. var uniqueName = this._generateUniqueName(upperName);
  15026. this._signatureToName[signature] = uniqueName;
  15027. return uniqueName;
  15028. };
  15029. PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
  15030. return this._generateUniqueName(name.toUpperCase());
  15031. };
  15032. // Generate a hash for a tag - does not take attribute order into account
  15033. PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {
  15034. var start = "<" + tag;
  15035. var strAttrs = Object.keys(attrs).sort().map(function (name) { return " " + name + "=" + attrs[name]; }).join('');
  15036. var end = isVoid ? '/>' : "></" + tag + ">";
  15037. return start + strAttrs + end;
  15038. };
  15039. PlaceholderRegistry.prototype._hashClosingTag = function (tag) { return this._hashTag("/" + tag, {}, false); };
  15040. PlaceholderRegistry.prototype._generateUniqueName = function (base) {
  15041. var seen = this._placeHolderNameCounts.hasOwnProperty(base);
  15042. if (!seen) {
  15043. this._placeHolderNameCounts[base] = 1;
  15044. return base;
  15045. }
  15046. var id = this._placeHolderNameCounts[base];
  15047. this._placeHolderNameCounts[base] = id + 1;
  15048. return base + "_" + id;
  15049. };
  15050. return PlaceholderRegistry;
  15051. }());
  15052. /**
  15053. * @license
  15054. * Copyright Google Inc. All Rights Reserved.
  15055. *
  15056. * Use of this source code is governed by an MIT-style license that can be
  15057. * found in the LICENSE file at https://angular.io/license
  15058. */
  15059. var _expParser = new Parser$1(new Lexer());
  15060. /**
  15061. * Returns a function converting html nodes to an i18n Message given an interpolationConfig
  15062. */
  15063. function createI18nMessageFactory(interpolationConfig) {
  15064. var visitor = new _I18nVisitor(_expParser, interpolationConfig);
  15065. return function (nodes, meaning, description, id, visitNodeFn) {
  15066. return visitor.toI18nMessage(nodes, meaning, description, id, visitNodeFn);
  15067. };
  15068. }
  15069. var _I18nVisitor = /** @class */ (function () {
  15070. function _I18nVisitor(_expressionParser, _interpolationConfig) {
  15071. this._expressionParser = _expressionParser;
  15072. this._interpolationConfig = _interpolationConfig;
  15073. }
  15074. _I18nVisitor.prototype.toI18nMessage = function (nodes, meaning, description, id, visitNodeFn) {
  15075. this._isIcu = nodes.length == 1 && nodes[0] instanceof Expansion;
  15076. this._icuDepth = 0;
  15077. this._placeholderRegistry = new PlaceholderRegistry();
  15078. this._placeholderToContent = {};
  15079. this._placeholderToMessage = {};
  15080. this._visitNodeFn = visitNodeFn;
  15081. var i18nodes = visitAll$1(this, nodes, {});
  15082. return new Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description, id);
  15083. };
  15084. _I18nVisitor.prototype._visitNode = function (html, i18n) {
  15085. if (this._visitNodeFn) {
  15086. this._visitNodeFn(html, i18n);
  15087. }
  15088. return i18n;
  15089. };
  15090. _I18nVisitor.prototype.visitElement = function (el, context) {
  15091. var children = visitAll$1(this, el.children);
  15092. var attrs = {};
  15093. el.attrs.forEach(function (attr) {
  15094. // Do not visit the attributes, translatable ones are top-level ASTs
  15095. attrs[attr.name] = attr.value;
  15096. });
  15097. var isVoid = getHtmlTagDefinition(el.name).isVoid;
  15098. var startPhName = this._placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
  15099. this._placeholderToContent[startPhName] = el.sourceSpan.toString();
  15100. var closePhName = '';
  15101. if (!isVoid) {
  15102. closePhName = this._placeholderRegistry.getCloseTagPlaceholderName(el.name);
  15103. this._placeholderToContent[closePhName] = "</" + el.name + ">";
  15104. }
  15105. var node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan);
  15106. return this._visitNode(el, node);
  15107. };
  15108. _I18nVisitor.prototype.visitAttribute = function (attribute, context) {
  15109. var node = this._visitTextWithInterpolation(attribute.value, attribute.sourceSpan);
  15110. return this._visitNode(attribute, node);
  15111. };
  15112. _I18nVisitor.prototype.visitText = function (text, context) {
  15113. var node = this._visitTextWithInterpolation(text.value, text.sourceSpan);
  15114. return this._visitNode(text, node);
  15115. };
  15116. _I18nVisitor.prototype.visitComment = function (comment, context) { return null; };
  15117. _I18nVisitor.prototype.visitExpansion = function (icu, context) {
  15118. var _this = this;
  15119. this._icuDepth++;
  15120. var i18nIcuCases = {};
  15121. var i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
  15122. icu.cases.forEach(function (caze) {
  15123. i18nIcuCases[caze.value] = new Container(caze.expression.map(function (node) { return node.visit(_this, {}); }), caze.expSourceSpan);
  15124. });
  15125. this._icuDepth--;
  15126. if (this._isIcu || this._icuDepth > 0) {
  15127. // Returns an ICU node when:
  15128. // - the message (vs a part of the message) is an ICU message, or
  15129. // - the ICU message is nested.
  15130. var expPh = this._placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
  15131. i18nIcu.expressionPlaceholder = expPh;
  15132. this._placeholderToContent[expPh] = icu.switchValue;
  15133. return this._visitNode(icu, i18nIcu);
  15134. }
  15135. // Else returns a placeholder
  15136. // ICU placeholders should not be replaced with their original content but with the their
  15137. // translations. We need to create a new visitor (they are not re-entrant) to compute the
  15138. // message id.
  15139. // TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
  15140. var phName = this._placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
  15141. var visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
  15142. this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '', '');
  15143. var node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
  15144. return this._visitNode(icu, node);
  15145. };
  15146. _I18nVisitor.prototype.visitExpansionCase = function (icuCase, context) {
  15147. throw new Error('Unreachable code');
  15148. };
  15149. _I18nVisitor.prototype._visitTextWithInterpolation = function (text, sourceSpan) {
  15150. var splitInterpolation = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
  15151. if (!splitInterpolation) {
  15152. // No expression, return a single text
  15153. return new Text$1(text, sourceSpan);
  15154. }
  15155. // Return a group of text + expressions
  15156. var nodes = [];
  15157. var container = new Container(nodes, sourceSpan);
  15158. var _a = this._interpolationConfig, sDelimiter = _a.start, eDelimiter = _a.end;
  15159. for (var i = 0; i < splitInterpolation.strings.length - 1; i++) {
  15160. var expression = splitInterpolation.expressions[i];
  15161. var baseName = _extractPlaceholderName(expression) || 'INTERPOLATION';
  15162. var phName = this._placeholderRegistry.getPlaceholderName(baseName, expression);
  15163. if (splitInterpolation.strings[i].length) {
  15164. // No need to add empty strings
  15165. nodes.push(new Text$1(splitInterpolation.strings[i], sourceSpan));
  15166. }
  15167. nodes.push(new Placeholder(expression, phName, sourceSpan));
  15168. this._placeholderToContent[phName] = sDelimiter + expression + eDelimiter;
  15169. }
  15170. // The last index contains no expression
  15171. var lastStringIdx = splitInterpolation.strings.length - 1;
  15172. if (splitInterpolation.strings[lastStringIdx].length) {
  15173. nodes.push(new Text$1(splitInterpolation.strings[lastStringIdx], sourceSpan));
  15174. }
  15175. return container;
  15176. };
  15177. return _I18nVisitor;
  15178. }());
  15179. var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
  15180. function _extractPlaceholderName(input) {
  15181. return input.split(_CUSTOM_PH_EXP)[2];
  15182. }
  15183. /**
  15184. * @license
  15185. * Copyright Google Inc. All Rights Reserved.
  15186. *
  15187. * Use of this source code is governed by an MIT-style license that can be
  15188. * found in the LICENSE file at https://angular.io/license
  15189. */
  15190. function setI18nRefs(html, i18n) {
  15191. html.i18n = i18n;
  15192. }
  15193. /**
  15194. * This visitor walks over HTML parse tree and converts information stored in
  15195. * i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
  15196. * stored with other element's and attribute's information.
  15197. */
  15198. var I18nMetaVisitor = /** @class */ (function () {
  15199. function I18nMetaVisitor(interpolationConfig, keepI18nAttrs) {
  15200. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15201. if (keepI18nAttrs === void 0) { keepI18nAttrs = false; }
  15202. this.interpolationConfig = interpolationConfig;
  15203. this.keepI18nAttrs = keepI18nAttrs;
  15204. // i18n message generation factory
  15205. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  15206. }
  15207. I18nMetaVisitor.prototype._generateI18nMessage = function (nodes, meta, visitNodeFn) {
  15208. if (meta === void 0) { meta = ''; }
  15209. var parsed = typeof meta === 'string' ? parseI18nMeta(meta) : metaFromI18nMessage(meta);
  15210. var message = this._createI18nMessage(nodes, parsed.meaning || '', parsed.description || '', parsed.id || '', visitNodeFn);
  15211. if (!message.id) {
  15212. // generate (or restore) message id if not specified in template
  15213. message.id = typeof meta !== 'string' && meta.id || decimalDigest(message);
  15214. }
  15215. return message;
  15216. };
  15217. I18nMetaVisitor.prototype.visitElement = function (element, context) {
  15218. var e_1, _a, e_2, _b;
  15219. if (hasI18nAttrs(element)) {
  15220. var attrs = [];
  15221. var attrsMeta = {};
  15222. try {
  15223. for (var _c = __values(element.attrs), _d = _c.next(); !_d.done; _d = _c.next()) {
  15224. var attr = _d.value;
  15225. if (attr.name === I18N_ATTR) {
  15226. // root 'i18n' node attribute
  15227. var i18n_1 = element.i18n || attr.value;
  15228. var message = this._generateI18nMessage(element.children, i18n_1, setI18nRefs);
  15229. // do not assign empty i18n meta
  15230. if (message.nodes.length) {
  15231. element.i18n = message;
  15232. }
  15233. }
  15234. else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
  15235. // 'i18n-*' attributes
  15236. var key = attr.name.slice(I18N_ATTR_PREFIX.length);
  15237. attrsMeta[key] = attr.value;
  15238. }
  15239. else {
  15240. // non-i18n attributes
  15241. attrs.push(attr);
  15242. }
  15243. }
  15244. }
  15245. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  15246. finally {
  15247. try {
  15248. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  15249. }
  15250. finally { if (e_1) throw e_1.error; }
  15251. }
  15252. // set i18n meta for attributes
  15253. if (Object.keys(attrsMeta).length) {
  15254. try {
  15255. for (var attrs_1 = __values(attrs), attrs_1_1 = attrs_1.next(); !attrs_1_1.done; attrs_1_1 = attrs_1.next()) {
  15256. var attr = attrs_1_1.value;
  15257. var meta = attrsMeta[attr.name];
  15258. // do not create translation for empty attributes
  15259. if (meta !== undefined && attr.value) {
  15260. attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
  15261. }
  15262. }
  15263. }
  15264. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  15265. finally {
  15266. try {
  15267. if (attrs_1_1 && !attrs_1_1.done && (_b = attrs_1.return)) _b.call(attrs_1);
  15268. }
  15269. finally { if (e_2) throw e_2.error; }
  15270. }
  15271. }
  15272. if (!this.keepI18nAttrs) {
  15273. // update element's attributes,
  15274. // keeping only non-i18n related ones
  15275. element.attrs = attrs;
  15276. }
  15277. }
  15278. visitAll$1(this, element.children);
  15279. return element;
  15280. };
  15281. I18nMetaVisitor.prototype.visitExpansion = function (expansion, context) {
  15282. var message;
  15283. var meta = expansion.i18n;
  15284. if (meta instanceof IcuPlaceholder) {
  15285. // set ICU placeholder name (e.g. "ICU_1"),
  15286. // generated while processing root element contents,
  15287. // so we can reference it when we output translation
  15288. var name_1 = meta.name;
  15289. message = this._generateI18nMessage([expansion], meta);
  15290. var icu = icuFromI18nMessage(message);
  15291. icu.name = name_1;
  15292. }
  15293. else {
  15294. // when ICU is a root level translation
  15295. message = this._generateI18nMessage([expansion], meta);
  15296. }
  15297. expansion.i18n = message;
  15298. return expansion;
  15299. };
  15300. I18nMetaVisitor.prototype.visitText = function (text, context) { return text; };
  15301. I18nMetaVisitor.prototype.visitAttribute = function (attribute, context) { return attribute; };
  15302. I18nMetaVisitor.prototype.visitComment = function (comment, context) { return comment; };
  15303. I18nMetaVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  15304. return I18nMetaVisitor;
  15305. }());
  15306. /**
  15307. * @license
  15308. * Copyright Google Inc. All Rights Reserved.
  15309. *
  15310. * Use of this source code is governed by an MIT-style license that can be
  15311. * found in the LICENSE file at https://angular.io/license
  15312. */
  15313. var formatPh = function (value) { return "{$" + formatI18nPlaceholderName(value) + "}"; };
  15314. /**
  15315. * This visitor walks over i18n tree and generates its string representation,
  15316. * including ICUs and placeholders in {$PLACEHOLDER} format.
  15317. */
  15318. var SerializerVisitor = /** @class */ (function () {
  15319. function SerializerVisitor() {
  15320. }
  15321. SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
  15322. SerializerVisitor.prototype.visitContainer = function (container, context) {
  15323. var _this = this;
  15324. return container.children.map(function (child) { return child.visit(_this); }).join('');
  15325. };
  15326. SerializerVisitor.prototype.visitIcu = function (icu, context) {
  15327. var _this = this;
  15328. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  15329. return "{" + icu.expressionPlaceholder + ", " + icu.type + ", " + strCases.join(' ') + "}";
  15330. };
  15331. SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  15332. var _this = this;
  15333. return ph.isVoid ?
  15334. formatPh(ph.startName) :
  15335. "" + formatPh(ph.startName) + ph.children.map(function (child) { return child.visit(_this); }).join('') + formatPh(ph.closeName);
  15336. };
  15337. SerializerVisitor.prototype.visitPlaceholder = function (ph, context) { return formatPh(ph.name); };
  15338. SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return formatPh(ph.name); };
  15339. return SerializerVisitor;
  15340. }());
  15341. var serializerVisitor$1 = new SerializerVisitor();
  15342. function getSerializedI18nContent(message) {
  15343. return message.nodes.map(function (node) { return node.visit(serializerVisitor$1, null); }).join('');
  15344. }
  15345. /**
  15346. * @license
  15347. * Copyright Google Inc. All Rights Reserved.
  15348. *
  15349. * Use of this source code is governed by an MIT-style license that can be
  15350. * found in the LICENSE file at https://angular.io/license
  15351. */
  15352. // Selector attribute name of `<ng-content>`
  15353. var NG_CONTENT_SELECT_ATTR$1 = 'select';
  15354. // Attribute name of `ngProjectAs`.
  15355. var NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
  15356. // List of supported global targets for event listeners
  15357. var GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers$1.resolveWindow], ['document', Identifiers$1.resolveDocument], ['body', Identifiers$1.resolveBody]]);
  15358. var LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
  15359. // if (rf & flags) { .. }
  15360. function renderFlagCheckIfStmt(flags, statements) {
  15361. return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
  15362. }
  15363. function prepareEventListenerParameters(eventAst, handlerName, scope) {
  15364. if (handlerName === void 0) { handlerName = null; }
  15365. if (scope === void 0) { scope = null; }
  15366. var type = eventAst.type, name = eventAst.name, target = eventAst.target, phase = eventAst.phase, handler = eventAst.handler;
  15367. if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
  15368. throw new Error("Unexpected global target '" + target + "' defined for '" + name + "' event.\n Supported list of global targets: " + Array.from(GLOBAL_TARGET_RESOLVERS.keys()) + ".");
  15369. }
  15370. var implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
  15371. variable(CONTEXT_NAME) :
  15372. scope.getOrCreateSharedContextVar(0);
  15373. var bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', function () { return error('Unexpected interpolation'); }, eventAst.handlerSpan);
  15374. var statements = [];
  15375. if (scope) {
  15376. statements.push.apply(statements, __spread(scope.restoreViewStatement()));
  15377. statements.push.apply(statements, __spread(scope.variableDeclarations()));
  15378. }
  15379. statements.push.apply(statements, __spread(bindingExpr.render3Stmts));
  15380. var eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
  15381. var fnName = handlerName && sanitizeIdentifier(handlerName);
  15382. var fnArgs = [new FnParam('$event', DYNAMIC_TYPE)];
  15383. var handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
  15384. var params = [literal(eventName), handlerFn];
  15385. if (target) {
  15386. params.push(literal(false), // `useCapture` flag, defaults to `false`
  15387. importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
  15388. }
  15389. return params;
  15390. }
  15391. var TemplateDefinitionBuilder = /** @class */ (function () {
  15392. function TemplateDefinitionBuilder(constantPool, parentBindingScope, level, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds) {
  15393. var _this = this;
  15394. if (level === void 0) { level = 0; }
  15395. this.constantPool = constantPool;
  15396. this.level = level;
  15397. this.contextName = contextName;
  15398. this.i18nContext = i18nContext;
  15399. this.templateIndex = templateIndex;
  15400. this.templateName = templateName;
  15401. this.directiveMatcher = directiveMatcher;
  15402. this.directives = directives;
  15403. this.pipeTypeByName = pipeTypeByName;
  15404. this.pipes = pipes;
  15405. this._namespace = _namespace;
  15406. this.relativeContextFilePath = relativeContextFilePath;
  15407. this.i18nUseExternalIds = i18nUseExternalIds;
  15408. this._dataIndex = 0;
  15409. this._bindingContext = 0;
  15410. this._prefixCode = [];
  15411. /**
  15412. * List of callbacks to generate creation mode instructions. We store them here as we process
  15413. * the template so bindings in listeners are resolved only once all nodes have been visited.
  15414. * This ensures all local refs and context variables are available for matching.
  15415. */
  15416. this._creationCodeFns = [];
  15417. /**
  15418. * List of callbacks to generate update mode instructions. We store them here as we process
  15419. * the template so bindings are resolved only once all nodes have been visited. This ensures
  15420. * all local refs and context variables are available for matching.
  15421. */
  15422. this._updateCodeFns = [];
  15423. /**
  15424. * Memorizes the last node index for which a select instruction has been generated.
  15425. * We're initializing this to -1 to ensure the `select(0)` instruction is generated before any
  15426. * relevant update instructions.
  15427. */
  15428. this._lastNodeIndexWithFlush = -1;
  15429. /** Temporary variable declarations generated from visiting pipes, literals, etc. */
  15430. this._tempVariables = [];
  15431. /**
  15432. * List of callbacks to build nested templates. Nested templates must not be visited until
  15433. * after the parent template has finished visiting all of its nodes. This ensures that all
  15434. * local ref bindings in nested templates are able to find local ref values if the refs
  15435. * are defined after the template declaration.
  15436. */
  15437. this._nestedTemplateFns = [];
  15438. this._unsupported = unsupported;
  15439. // i18n context local to this template
  15440. this.i18n = null;
  15441. // Number of slots to reserve for pureFunctions
  15442. this._pureFunctionSlots = 0;
  15443. // Number of binding slots
  15444. this._bindingSlots = 0;
  15445. // Projection slots found in the template. Projection slots can distribute projected
  15446. // nodes based on a selector, or can just use the wildcard selector to match
  15447. // all nodes which aren't matching any selector.
  15448. this._ngContentReservedSlots = [];
  15449. // Number of non-default selectors found in all parent templates of this template. We need to
  15450. // track it to properly adjust projection slot index in the `projection` instruction.
  15451. this._ngContentSelectorsOffset = 0;
  15452. // Expression that should be used as implicit receiver when converting template
  15453. // expressions to output AST.
  15454. this._implicitReceiverExpr = null;
  15455. // These should be handled in the template or element directly.
  15456. this.visitReference = invalid$1;
  15457. this.visitVariable = invalid$1;
  15458. this.visitTextAttribute = invalid$1;
  15459. this.visitBoundAttribute = invalid$1;
  15460. this.visitBoundEvent = invalid$1;
  15461. this._bindingScope = parentBindingScope.nestedScope(level);
  15462. // Turn the relative context file path into an identifier by replacing non-alphanumeric
  15463. // characters with underscores.
  15464. this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
  15465. this._valueConverter = new ValueConverter(constantPool, function () { return _this.allocateDataSlot(); }, function (numSlots) { return _this.allocatePureFunctionSlots(numSlots); }, function (name, localName, slot, value) {
  15466. var pipeType = pipeTypeByName.get(name);
  15467. if (pipeType) {
  15468. _this.pipes.add(pipeType);
  15469. }
  15470. _this._bindingScope.set(_this.level, localName, value);
  15471. _this.creationInstruction(null, Identifiers$1.pipe, [literal(slot), literal(name)]);
  15472. });
  15473. }
  15474. TemplateDefinitionBuilder.prototype.registerContextVariables = function (variable$1) {
  15475. var scopedName = this._bindingScope.freshReferenceName();
  15476. var retrievalLevel = this.level;
  15477. var lhs = variable(variable$1.name + scopedName);
  15478. this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, function (scope, relativeLevel) {
  15479. var rhs;
  15480. if (scope.bindingLevel === retrievalLevel) {
  15481. // e.g. ctx
  15482. rhs = variable(CONTEXT_NAME);
  15483. }
  15484. else {
  15485. var sharedCtxVar = scope.getSharedContextName(retrievalLevel);
  15486. // e.g. ctx_r0 OR x(2);
  15487. rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
  15488. }
  15489. // e.g. const $item$ = x(2).$implicit;
  15490. return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
  15491. });
  15492. };
  15493. TemplateDefinitionBuilder.prototype.buildTemplateFunction = function (nodes, variables, ngContentSelectorsOffset, i18n) {
  15494. var _this = this;
  15495. if (ngContentSelectorsOffset === void 0) { ngContentSelectorsOffset = 0; }
  15496. this._ngContentSelectorsOffset = ngContentSelectorsOffset;
  15497. if (this._namespace !== Identifiers$1.namespaceHTML) {
  15498. this.creationInstruction(null, this._namespace);
  15499. }
  15500. // Create variable bindings
  15501. variables.forEach(function (v) { return _this.registerContextVariables(v); });
  15502. // Initiate i18n context in case:
  15503. // - this template has parent i18n context
  15504. // - or the template has i18n meta associated with it,
  15505. // but it's not initiated by the Element (e.g. <ng-template i18n>)
  15506. var initI18nContext = this.i18nContext || (isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
  15507. !(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
  15508. var selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
  15509. if (initI18nContext) {
  15510. this.i18nStart(null, i18n, selfClosingI18nInstruction);
  15511. }
  15512. // This is the initial pass through the nodes of this template. In this pass, we
  15513. // queue all creation mode and update mode instructions for generation in the second
  15514. // pass. It's necessary to separate the passes to ensure local refs are defined before
  15515. // resolving bindings. We also count bindings in this pass as we walk bound expressions.
  15516. visitAll(this, nodes);
  15517. // Add total binding count to pure function count so pure function instructions are
  15518. // generated with the correct slot offset when update instructions are processed.
  15519. this._pureFunctionSlots += this._bindingSlots;
  15520. // Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
  15521. // `pipeBind` update instructions), so we have to update the slot offsets manually
  15522. // to account for bindings.
  15523. this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
  15524. // Nested templates must be processed before creation instructions so template()
  15525. // instructions can be generated with the correct internal const count.
  15526. this._nestedTemplateFns.forEach(function (buildTemplateFn) { return buildTemplateFn(); });
  15527. // Output the `projectionDef` instruction when some `<ng-content>` tags are present.
  15528. // The `projectionDef` instruction is only emitted for the component template and
  15529. // is skipped for nested templates (<ng-template> tags).
  15530. if (this.level === 0 && this._ngContentReservedSlots.length) {
  15531. var parameters = [];
  15532. // By default the `projectionDef` instructions creates one slot for the wildcard
  15533. // selector if no parameters are passed. Therefore we only want to allocate a new
  15534. // array for the projection slots if the default projection slot is not sufficient.
  15535. if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
  15536. var r3ReservedSlots = this._ngContentReservedSlots.map(function (s) { return s !== '*' ? parseSelectorToR3Selector(s) : s; });
  15537. parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
  15538. }
  15539. // Since we accumulate ngContent selectors while processing template elements,
  15540. // we *prepend* `projectionDef` to creation instructions block, to put it before
  15541. // any `projection` instructions
  15542. this.creationInstruction(null, Identifiers$1.projectionDef, parameters, /* prepend */ true);
  15543. }
  15544. if (initI18nContext) {
  15545. this.i18nEnd(null, selfClosingI18nInstruction);
  15546. }
  15547. // Generate all the creation mode instructions (e.g. resolve bindings in listeners)
  15548. var creationStatements = this._creationCodeFns.map(function (fn) { return fn(); });
  15549. // Generate all the update mode instructions (e.g. resolve property or text bindings)
  15550. var updateStatements = this._updateCodeFns.map(function (fn) { return fn(); });
  15551. // Variable declaration must occur after binding resolution so we can generate context
  15552. // instructions that build on each other.
  15553. // e.g. const b = nextContext().$implicit(); const b = nextContext();
  15554. var creationVariables = this._bindingScope.viewSnapshotStatements();
  15555. var updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
  15556. var creationBlock = creationStatements.length > 0 ?
  15557. [renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
  15558. [];
  15559. var updateBlock = updateStatements.length > 0 ?
  15560. [renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
  15561. [];
  15562. return fn(
  15563. // i.e. (rf: RenderFlags, ctx: any)
  15564. [new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], __spread(this._prefixCode, creationBlock, updateBlock), INFERRED_TYPE, null, this.templateName);
  15565. };
  15566. // LocalResolver
  15567. TemplateDefinitionBuilder.prototype.getLocal = function (name) { return this._bindingScope.get(name); };
  15568. // LocalResolver
  15569. TemplateDefinitionBuilder.prototype.notifyImplicitReceiverUse = function () { this._bindingScope.notifyImplicitReceiverUse(); };
  15570. TemplateDefinitionBuilder.prototype.i18nTranslate = function (message, params, ref, transformFn) {
  15571. var _a;
  15572. if (params === void 0) { params = {}; }
  15573. var _ref = ref || variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  15574. // Closure Compiler requires const names to start with `MSG_` but disallows any other const to
  15575. // start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
  15576. var closureVar = this.i18nGenerateClosureVar(message.id);
  15577. var _params = {};
  15578. if (params && Object.keys(params).length) {
  15579. Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key)] = params[key]; });
  15580. }
  15581. var meta = metaFromI18nMessage(message);
  15582. var content = getSerializedI18nContent(message);
  15583. var statements = getTranslationDeclStmts(_ref, closureVar, content, meta, _params, transformFn);
  15584. (_a = this.constantPool.statements).push.apply(_a, __spread(statements));
  15585. return _ref;
  15586. };
  15587. TemplateDefinitionBuilder.prototype.i18nAppendBindings = function (expressions) {
  15588. var _this = this;
  15589. if (expressions.length > 0) {
  15590. expressions.forEach(function (expression) { return _this.i18n.appendBinding(expression); });
  15591. }
  15592. };
  15593. TemplateDefinitionBuilder.prototype.i18nBindProps = function (props) {
  15594. var _this = this;
  15595. var bound = {};
  15596. Object.keys(props).forEach(function (key) {
  15597. var prop = props[key];
  15598. if (prop instanceof Text) {
  15599. bound[key] = literal(prop.value);
  15600. }
  15601. else {
  15602. var value = prop.value.visit(_this._valueConverter);
  15603. _this.allocateBindingSlots(value);
  15604. if (value instanceof Interpolation) {
  15605. var strings = value.strings, expressions = value.expressions;
  15606. var _a = _this.i18n, id = _a.id, bindings = _a.bindings;
  15607. var label = assembleI18nBoundString(strings, bindings.size, id);
  15608. _this.i18nAppendBindings(expressions);
  15609. bound[key] = literal(label);
  15610. }
  15611. }
  15612. });
  15613. return bound;
  15614. };
  15615. TemplateDefinitionBuilder.prototype.i18nGenerateClosureVar = function (messageId) {
  15616. var name;
  15617. var suffix = this.fileBasedI18nSuffix.toUpperCase();
  15618. if (this.i18nUseExternalIds) {
  15619. var prefix = getTranslationConstPrefix("EXTERNAL_");
  15620. var uniqueSuffix = this.constantPool.uniqueName(suffix);
  15621. name = "" + prefix + sanitizeIdentifier(messageId) + "$$" + uniqueSuffix;
  15622. }
  15623. else {
  15624. var prefix = getTranslationConstPrefix(suffix);
  15625. name = this.constantPool.uniqueName(prefix);
  15626. }
  15627. return variable(name);
  15628. };
  15629. TemplateDefinitionBuilder.prototype.i18nUpdateRef = function (context) {
  15630. var icus = context.icus, meta = context.meta, isRoot = context.isRoot, isResolved = context.isResolved, isEmitted = context.isEmitted;
  15631. if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
  15632. context.isEmitted = true;
  15633. var placeholders = context.getSerializedPlaceholders();
  15634. var icuMapping_1 = {};
  15635. var params_1 = placeholders.size ? placeholdersToParams(placeholders) : {};
  15636. if (icus.size) {
  15637. icus.forEach(function (refs, key) {
  15638. if (refs.length === 1) {
  15639. // if we have one ICU defined for a given
  15640. // placeholder - just output its reference
  15641. params_1[key] = refs[0];
  15642. }
  15643. else {
  15644. // ... otherwise we need to activate post-processing
  15645. // to replace ICU placeholders with proper values
  15646. var placeholder = wrapI18nPlaceholder("" + I18N_ICU_MAPPING_PREFIX + key);
  15647. params_1[key] = literal(placeholder);
  15648. icuMapping_1[key] = literalArr(refs);
  15649. }
  15650. });
  15651. }
  15652. // translation requires post processing in 2 cases:
  15653. // - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
  15654. // - if we have multiple ICUs that refer to the same placeholder name
  15655. var needsPostprocessing = Array.from(placeholders.values()).some(function (value) { return value.length > 1; }) ||
  15656. Object.keys(icuMapping_1).length;
  15657. var transformFn = void 0;
  15658. if (needsPostprocessing) {
  15659. transformFn = function (raw) {
  15660. var args = [raw];
  15661. if (Object.keys(icuMapping_1).length) {
  15662. args.push(mapLiteral(icuMapping_1, true));
  15663. }
  15664. return instruction(null, Identifiers$1.i18nPostprocess, args);
  15665. };
  15666. }
  15667. this.i18nTranslate(meta, params_1, context.ref, transformFn);
  15668. }
  15669. };
  15670. TemplateDefinitionBuilder.prototype.i18nStart = function (span, meta, selfClosing) {
  15671. if (span === void 0) { span = null; }
  15672. var index = this.allocateDataSlot();
  15673. if (this.i18nContext) {
  15674. this.i18n = this.i18nContext.forkChildContext(index, this.templateIndex, meta);
  15675. }
  15676. else {
  15677. var ref_1 = variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  15678. this.i18n = new I18nContext(index, ref_1, 0, this.templateIndex, meta);
  15679. }
  15680. // generate i18nStart instruction
  15681. var _a = this.i18n, id = _a.id, ref = _a.ref;
  15682. var params = [literal(index), ref];
  15683. if (id > 0) {
  15684. // do not push 3rd argument (sub-block id)
  15685. // into i18nStart call for top level i18n context
  15686. params.push(literal(id));
  15687. }
  15688. this.creationInstruction(span, selfClosing ? Identifiers$1.i18n : Identifiers$1.i18nStart, params);
  15689. };
  15690. TemplateDefinitionBuilder.prototype.i18nEnd = function (span, selfClosing) {
  15691. var _this = this;
  15692. if (span === void 0) { span = null; }
  15693. if (!this.i18n) {
  15694. throw new Error('i18nEnd is executed with no i18n context present');
  15695. }
  15696. if (this.i18nContext) {
  15697. this.i18nContext.reconcileChildContext(this.i18n);
  15698. this.i18nUpdateRef(this.i18nContext);
  15699. }
  15700. else {
  15701. this.i18nUpdateRef(this.i18n);
  15702. }
  15703. // setup accumulated bindings
  15704. var _a = this.i18n, index = _a.index, bindings = _a.bindings;
  15705. if (bindings.size) {
  15706. var chainBindings_1 = [];
  15707. bindings.forEach(function (binding) {
  15708. chainBindings_1.push({ sourceSpan: span, value: function () { return _this.convertPropertyBinding(binding); } });
  15709. });
  15710. this.updateInstructionChain(index, Identifiers$1.i18nExp, chainBindings_1);
  15711. this.updateInstruction(index, span, Identifiers$1.i18nApply, [literal(index)]);
  15712. }
  15713. if (!selfClosing) {
  15714. this.creationInstruction(span, Identifiers$1.i18nEnd);
  15715. }
  15716. this.i18n = null; // reset local i18n context
  15717. };
  15718. TemplateDefinitionBuilder.prototype.visitContent = function (ngContent) {
  15719. var slot = this.allocateDataSlot();
  15720. var projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
  15721. var parameters = [literal(slot)];
  15722. var attributes = [];
  15723. this._ngContentReservedSlots.push(ngContent.selector);
  15724. ngContent.attributes.forEach(function (attribute) {
  15725. var name = attribute.name, value = attribute.value;
  15726. if (name === NG_PROJECT_AS_ATTR_NAME) {
  15727. attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attribute)));
  15728. }
  15729. else if (name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1) {
  15730. attributes.push(literal(name), literal(value));
  15731. }
  15732. });
  15733. if (attributes.length > 0) {
  15734. parameters.push(literal(projectionSlotIdx), literalArr(attributes));
  15735. }
  15736. else if (projectionSlotIdx !== 0) {
  15737. parameters.push(literal(projectionSlotIdx));
  15738. }
  15739. this.creationInstruction(ngContent.sourceSpan, Identifiers$1.projection, parameters);
  15740. if (this.i18n) {
  15741. this.i18n.appendProjection(ngContent.i18n, slot);
  15742. }
  15743. };
  15744. TemplateDefinitionBuilder.prototype.getNamespaceInstruction = function (namespaceKey) {
  15745. switch (namespaceKey) {
  15746. case 'math':
  15747. return Identifiers$1.namespaceMathML;
  15748. case 'svg':
  15749. return Identifiers$1.namespaceSVG;
  15750. default:
  15751. return Identifiers$1.namespaceHTML;
  15752. }
  15753. };
  15754. TemplateDefinitionBuilder.prototype.addNamespaceInstruction = function (nsInstruction, element) {
  15755. this._namespace = nsInstruction;
  15756. this.creationInstruction(element.sourceSpan, nsInstruction);
  15757. };
  15758. TemplateDefinitionBuilder.prototype.visitElement = function (element) {
  15759. var _this = this;
  15760. var e_1, _a;
  15761. var elementIndex = this.allocateDataSlot();
  15762. var stylingBuilder = new StylingBuilder(literal(elementIndex), null);
  15763. var isNonBindableMode = false;
  15764. var isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
  15765. if (isI18nRootElement && this.i18n) {
  15766. throw new Error("Could not mark an element as translatable inside of a translatable section");
  15767. }
  15768. var i18nAttrs = [];
  15769. var outputAttrs = [];
  15770. var _b = __read(splitNsName(element.name), 2), namespaceKey = _b[0], elementName = _b[1];
  15771. var isNgContainer$1 = isNgContainer(element.name);
  15772. try {
  15773. // Handle styling, i18n, ngNonBindable attributes
  15774. for (var _c = __values(element.attributes), _d = _c.next(); !_d.done; _d = _c.next()) {
  15775. var attr = _d.value;
  15776. var name_1 = attr.name, value = attr.value;
  15777. if (name_1 === NON_BINDABLE_ATTR) {
  15778. isNonBindableMode = true;
  15779. }
  15780. else if (name_1 === 'style') {
  15781. stylingBuilder.registerStyleAttr(value);
  15782. }
  15783. else if (name_1 === 'class') {
  15784. stylingBuilder.registerClassAttr(value);
  15785. }
  15786. else {
  15787. if (attr.i18n) {
  15788. // Place attributes into a separate array for i18n processing, but also keep such
  15789. // attributes in the main list to make them available for directive matching at runtime.
  15790. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  15791. // arguments
  15792. i18nAttrs.push(attr);
  15793. }
  15794. else {
  15795. outputAttrs.push(attr);
  15796. }
  15797. }
  15798. }
  15799. }
  15800. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  15801. finally {
  15802. try {
  15803. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  15804. }
  15805. finally { if (e_1) throw e_1.error; }
  15806. }
  15807. // Match directives on non i18n attributes
  15808. this.matchDirectives(element.name, element);
  15809. // Regular element or ng-container creation mode
  15810. var parameters = [literal(elementIndex)];
  15811. if (!isNgContainer$1) {
  15812. parameters.push(literal(elementName));
  15813. }
  15814. // Add the attributes
  15815. var attributes = [];
  15816. var allOtherInputs = [];
  15817. element.inputs.forEach(function (input) {
  15818. var stylingInputWasSet = stylingBuilder.registerBoundInput(input);
  15819. if (!stylingInputWasSet) {
  15820. if (input.type === 0 /* Property */ && input.i18n) {
  15821. // Place attributes into a separate array for i18n processing, but also keep such
  15822. // attributes in the main list to make them available for directive matching at runtime.
  15823. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  15824. // arguments
  15825. i18nAttrs.push(input);
  15826. }
  15827. else {
  15828. allOtherInputs.push(input);
  15829. }
  15830. }
  15831. });
  15832. outputAttrs.forEach(function (attr) {
  15833. if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
  15834. attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attr)));
  15835. }
  15836. else {
  15837. attributes.push.apply(attributes, __spread(getAttributeNameLiterals(attr.name), [literal(attr.value)]));
  15838. }
  15839. });
  15840. // add attributes for directive and projection matching purposes
  15841. attributes.push.apply(attributes, __spread(this.prepareNonRenderAttrs(allOtherInputs, element.outputs, stylingBuilder, [], i18nAttrs)));
  15842. parameters.push(this.toAttrsParam(attributes));
  15843. // local refs (ex.: <div #foo #bar="baz">)
  15844. parameters.push(this.prepareRefsParameter(element.references));
  15845. var wasInNamespace = this._namespace;
  15846. var currentNamespace = this.getNamespaceInstruction(namespaceKey);
  15847. // If the namespace is changing now, include an instruction to change it
  15848. // during element creation.
  15849. if (currentNamespace !== wasInNamespace) {
  15850. this.addNamespaceInstruction(currentNamespace, element);
  15851. }
  15852. if (this.i18n) {
  15853. this.i18n.appendElement(element.i18n, elementIndex);
  15854. }
  15855. var hasChildren = function () {
  15856. if (!isI18nRootElement && _this.i18n) {
  15857. // we do not append text node instructions and ICUs inside i18n section,
  15858. // so we exclude them while calculating whether current element has children
  15859. return !hasTextChildrenOnly(element.children);
  15860. }
  15861. return element.children.length > 0;
  15862. };
  15863. var createSelfClosingInstruction = !stylingBuilder.hasBindings && !isNgContainer$1 &&
  15864. element.outputs.length === 0 && i18nAttrs.length === 0 && !hasChildren();
  15865. var createSelfClosingI18nInstruction = !createSelfClosingInstruction &&
  15866. !stylingBuilder.hasBindings && hasTextChildrenOnly(element.children);
  15867. if (createSelfClosingInstruction) {
  15868. this.creationInstruction(element.sourceSpan, Identifiers$1.element, trimTrailingNulls(parameters));
  15869. }
  15870. else {
  15871. this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainerStart : Identifiers$1.elementStart, trimTrailingNulls(parameters));
  15872. if (isNonBindableMode) {
  15873. this.creationInstruction(element.sourceSpan, Identifiers$1.disableBindings);
  15874. }
  15875. // process i18n element attributes
  15876. if (i18nAttrs.length) {
  15877. var hasBindings_1 = false;
  15878. var i18nAttrArgs_1 = [];
  15879. var bindings_1 = [];
  15880. i18nAttrs.forEach(function (attr) {
  15881. var message = attr.i18n;
  15882. if (attr instanceof TextAttribute) {
  15883. i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message));
  15884. }
  15885. else {
  15886. var converted = attr.value.visit(_this._valueConverter);
  15887. _this.allocateBindingSlots(converted);
  15888. if (converted instanceof Interpolation) {
  15889. var placeholders = assembleBoundTextPlaceholders(message);
  15890. var params = placeholdersToParams(placeholders);
  15891. i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message, params));
  15892. converted.expressions.forEach(function (expression) {
  15893. hasBindings_1 = true;
  15894. bindings_1.push({
  15895. sourceSpan: element.sourceSpan,
  15896. value: function () { return _this.convertExpressionBinding(expression); }
  15897. });
  15898. });
  15899. }
  15900. }
  15901. });
  15902. if (bindings_1.length) {
  15903. this.updateInstructionChain(elementIndex, Identifiers$1.i18nExp, bindings_1);
  15904. }
  15905. if (i18nAttrArgs_1.length) {
  15906. var index = literal(this.allocateDataSlot());
  15907. var args = this.constantPool.getConstLiteral(literalArr(i18nAttrArgs_1), true);
  15908. this.creationInstruction(element.sourceSpan, Identifiers$1.i18nAttributes, [index, args]);
  15909. if (hasBindings_1) {
  15910. this.updateInstruction(elementIndex, element.sourceSpan, Identifiers$1.i18nApply, [index]);
  15911. }
  15912. }
  15913. }
  15914. // The style bindings code is placed into two distinct blocks within the template function AOT
  15915. // code: creation and update. The creation code contains the `styling` instructions
  15916. // which will apply the collected binding values to the element. `styling` is
  15917. // designed to run inside of `elementStart` and `elementEnd`. The update instructions
  15918. // (things like `styleProp`, `classProp`, etc..) are applied later on in this
  15919. // file
  15920. this.processStylingInstruction(elementIndex, stylingBuilder.buildStylingInstruction(element.sourceSpan, this.constantPool), true);
  15921. // Generate Listeners (outputs)
  15922. element.outputs.forEach(function (outputAst) {
  15923. _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter(element.name, outputAst, elementIndex));
  15924. });
  15925. // Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
  15926. // listeners, to make sure i18nAttributes instruction targets current element at runtime.
  15927. if (isI18nRootElement) {
  15928. this.i18nStart(element.sourceSpan, element.i18n, createSelfClosingI18nInstruction);
  15929. }
  15930. }
  15931. // the code here will collect all update-level styling instructions and add them to the
  15932. // update block of the template function AOT code. Instructions like `styleProp`,
  15933. // `styleMap`, `classMap`, `classProp` and `stylingApply`
  15934. // are all generated and assigned in the code below.
  15935. var stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
  15936. var limit = stylingInstructions.length - 1;
  15937. for (var i = 0; i <= limit; i++) {
  15938. var instruction_1 = stylingInstructions[i];
  15939. this._bindingSlots += instruction_1.allocateBindingSlots;
  15940. this.processStylingInstruction(elementIndex, instruction_1, false);
  15941. }
  15942. // the reason why `undefined` is used is because the renderer understands this as a
  15943. // special value to symbolize that there is no RHS to this binding
  15944. // TODO (matsko): revisit this once FW-959 is approached
  15945. var emptyValueBindInstruction = literal(undefined);
  15946. var propertyBindings = [];
  15947. var attributeBindings = [];
  15948. // Generate element input bindings
  15949. allOtherInputs.forEach(function (input) {
  15950. var inputType = input.type;
  15951. if (inputType === 4 /* Animation */) {
  15952. var value_1 = input.value.visit(_this._valueConverter);
  15953. // animation bindings can be presented in the following formats:
  15954. // 1. [@binding]="fooExp"
  15955. // 2. [@binding]="{value:fooExp, params:{...}}"
  15956. // 3. [@binding]
  15957. // 4. @binding
  15958. // All formats will be valid for when a synthetic binding is created.
  15959. // The reasoning for this is because the renderer should get each
  15960. // synthetic binding value in the order of the array that they are
  15961. // defined in...
  15962. var hasValue_1 = value_1 instanceof LiteralPrimitive ? !!value_1.value : true;
  15963. _this.allocateBindingSlots(value_1);
  15964. propertyBindings.push({
  15965. name: prepareSyntheticPropertyName(input.name),
  15966. sourceSpan: input.sourceSpan,
  15967. value: function () { return hasValue_1 ? _this.convertPropertyBinding(value_1) : emptyValueBindInstruction; }
  15968. });
  15969. }
  15970. else {
  15971. // we must skip attributes with associated i18n context, since these attributes are handled
  15972. // separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
  15973. if (input.i18n)
  15974. return;
  15975. var value_2 = input.value.visit(_this._valueConverter);
  15976. if (value_2 !== undefined) {
  15977. var params_2 = [];
  15978. var _a = __read(splitNsName(input.name), 2), attrNamespace = _a[0], attrName_1 = _a[1];
  15979. var isAttributeBinding = inputType === 1 /* Attribute */;
  15980. var sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
  15981. if (sanitizationRef)
  15982. params_2.push(sanitizationRef);
  15983. if (attrNamespace) {
  15984. var namespaceLiteral = literal(attrNamespace);
  15985. if (sanitizationRef) {
  15986. params_2.push(namespaceLiteral);
  15987. }
  15988. else {
  15989. // If there wasn't a sanitization ref, we need to add
  15990. // an extra param so that we can pass in the namespace.
  15991. params_2.push(literal(null), namespaceLiteral);
  15992. }
  15993. }
  15994. _this.allocateBindingSlots(value_2);
  15995. if (inputType === 0 /* Property */) {
  15996. if (value_2 instanceof Interpolation) {
  15997. // prop="{{value}}" and friends
  15998. _this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  15999. }
  16000. else {
  16001. // [prop]="value"
  16002. // Collect all the properties so that we can chain into a single function at the end.
  16003. propertyBindings.push({
  16004. name: attrName_1,
  16005. sourceSpan: input.sourceSpan,
  16006. value: function () { return _this.convertPropertyBinding(value_2); }, params: params_2
  16007. });
  16008. }
  16009. }
  16010. else if (inputType === 1 /* Attribute */) {
  16011. if (value_2 instanceof Interpolation && getInterpolationArgsLength(value_2) > 1) {
  16012. // attr.name="text{{value}}" and friends
  16013. _this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  16014. }
  16015. else {
  16016. var boundValue_1 = value_2 instanceof Interpolation ? value_2.expressions[0] : value_2;
  16017. // [attr.name]="value" or attr.name="{{value}}"
  16018. // Collect the attribute bindings so that they can be chained at the end.
  16019. attributeBindings.push({
  16020. name: attrName_1,
  16021. sourceSpan: input.sourceSpan,
  16022. value: function () { return _this.convertPropertyBinding(boundValue_1); }, params: params_2
  16023. });
  16024. }
  16025. }
  16026. else {
  16027. // class prop
  16028. _this.updateInstruction(elementIndex, input.sourceSpan, Identifiers$1.classProp, function () {
  16029. return __spread([
  16030. literal(elementIndex), literal(attrName_1), _this.convertPropertyBinding(value_2)
  16031. ], params_2);
  16032. });
  16033. }
  16034. }
  16035. }
  16036. });
  16037. if (propertyBindings.length > 0) {
  16038. this.updateInstructionChain(elementIndex, Identifiers$1.property, propertyBindings);
  16039. }
  16040. if (attributeBindings.length > 0) {
  16041. this.updateInstructionChain(elementIndex, Identifiers$1.attribute, attributeBindings);
  16042. }
  16043. // Traverse element child nodes
  16044. visitAll(this, element.children);
  16045. if (!isI18nRootElement && this.i18n) {
  16046. this.i18n.appendElement(element.i18n, elementIndex, true);
  16047. }
  16048. if (!createSelfClosingInstruction) {
  16049. // Finish element construction mode.
  16050. var span = element.endSourceSpan || element.sourceSpan;
  16051. if (isI18nRootElement) {
  16052. this.i18nEnd(span, createSelfClosingI18nInstruction);
  16053. }
  16054. if (isNonBindableMode) {
  16055. this.creationInstruction(span, Identifiers$1.enableBindings);
  16056. }
  16057. this.creationInstruction(span, isNgContainer$1 ? Identifiers$1.elementContainerEnd : Identifiers$1.elementEnd);
  16058. }
  16059. };
  16060. /**
  16061. * Adds an update instruction for an interpolated property or attribute, such as
  16062. * `prop="{{value}}"` or `attr.title="{{value}}"`
  16063. */
  16064. TemplateDefinitionBuilder.prototype.interpolatedUpdateInstruction = function (instruction, elementIndex, attrName, input, value, params) {
  16065. var _this = this;
  16066. this.updateInstruction(elementIndex, input.sourceSpan, instruction, function () { return __spread([literal(attrName)], _this.getUpdateInstructionArguments(value), params); });
  16067. };
  16068. TemplateDefinitionBuilder.prototype.visitTemplate = function (template) {
  16069. var _this = this;
  16070. var NG_TEMPLATE_TAG_NAME = 'ng-template';
  16071. var templateIndex = this.allocateDataSlot();
  16072. if (this.i18n) {
  16073. this.i18n.appendTemplate(template.i18n, templateIndex);
  16074. }
  16075. var tagName = sanitizeIdentifier(template.tagName || '');
  16076. var contextName = "" + this.contextName + (tagName ? '_' + tagName : '') + "_" + templateIndex;
  16077. var templateName = contextName + "_Template";
  16078. var parameters = [
  16079. literal(templateIndex),
  16080. variable(templateName),
  16081. // We don't care about the tag's namespace here, because we infer
  16082. // it based on the parent nodes inside the template instruction.
  16083. literal(template.tagName ? splitNsName(template.tagName)[1] : template.tagName),
  16084. ];
  16085. // find directives matching on a given <ng-template> node
  16086. this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
  16087. // prepare attributes parameter (including attributes used for directive matching)
  16088. var attrsExprs = [];
  16089. template.attributes.forEach(function (a) { attrsExprs.push(asLiteral(a.name), asLiteral(a.value)); });
  16090. attrsExprs.push.apply(attrsExprs, __spread(this.prepareNonRenderAttrs(template.inputs, template.outputs, undefined, template.templateAttrs)));
  16091. parameters.push(this.toAttrsParam(attrsExprs));
  16092. // local refs (ex.: <ng-template #foo>)
  16093. if (template.references && template.references.length) {
  16094. parameters.push(this.prepareRefsParameter(template.references));
  16095. parameters.push(importExpr(Identifiers$1.templateRefExtractor));
  16096. }
  16097. // Create the template function
  16098. var templateVisitor = new TemplateDefinitionBuilder(this.constantPool, this._bindingScope, this.level + 1, contextName, this.i18n, templateIndex, templateName, this.directiveMatcher, this.directives, this.pipeTypeByName, this.pipes, this._namespace, this.fileBasedI18nSuffix, this.i18nUseExternalIds);
  16099. // Nested templates must not be visited until after their parent templates have completed
  16100. // processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
  16101. // be able to support bindings in nested templates to local refs that occur after the
  16102. // template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
  16103. this._nestedTemplateFns.push(function () {
  16104. var _a;
  16105. var templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, _this._ngContentReservedSlots.length + _this._ngContentSelectorsOffset, template.i18n);
  16106. _this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName, null));
  16107. if (templateVisitor._ngContentReservedSlots.length) {
  16108. (_a = _this._ngContentReservedSlots).push.apply(_a, __spread(templateVisitor._ngContentReservedSlots));
  16109. }
  16110. });
  16111. // e.g. template(1, MyComp_Template_1)
  16112. this.creationInstruction(template.sourceSpan, Identifiers$1.templateCreate, function () {
  16113. parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
  16114. return trimTrailingNulls(parameters);
  16115. });
  16116. // handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
  16117. this.templatePropertyBindings(templateIndex, template.templateAttrs);
  16118. // Only add normal input/output binding instructions on explicit ng-template elements.
  16119. if (template.tagName === NG_TEMPLATE_TAG_NAME) {
  16120. // Add the input bindings
  16121. this.templatePropertyBindings(templateIndex, template.inputs);
  16122. // Generate listeners for directive output
  16123. template.outputs.forEach(function (outputAst) {
  16124. _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter('ng_template', outputAst, templateIndex));
  16125. });
  16126. }
  16127. };
  16128. TemplateDefinitionBuilder.prototype.visitBoundText = function (text) {
  16129. var _this = this;
  16130. if (this.i18n) {
  16131. var value_3 = text.value.visit(this._valueConverter);
  16132. this.allocateBindingSlots(value_3);
  16133. if (value_3 instanceof Interpolation) {
  16134. this.i18n.appendBoundText(text.i18n);
  16135. this.i18nAppendBindings(value_3.expressions);
  16136. }
  16137. return;
  16138. }
  16139. var nodeIndex = this.allocateDataSlot();
  16140. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(nodeIndex)]);
  16141. var value = text.value.visit(this._valueConverter);
  16142. this.allocateBindingSlots(value);
  16143. if (value instanceof Interpolation) {
  16144. this.updateInstruction(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), function () { return _this.getUpdateInstructionArguments(value); });
  16145. }
  16146. else {
  16147. this.updateInstruction(nodeIndex, text.sourceSpan, Identifiers$1.textBinding, function () { return [_this.convertPropertyBinding(value)]; });
  16148. }
  16149. };
  16150. TemplateDefinitionBuilder.prototype.visitText = function (text) {
  16151. // when a text element is located within a translatable
  16152. // block, we exclude this text element from instructions set,
  16153. // since it will be captured in i18n content and processed at runtime
  16154. if (!this.i18n) {
  16155. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(this.allocateDataSlot()), literal(text.value)]);
  16156. }
  16157. };
  16158. TemplateDefinitionBuilder.prototype.visitIcu = function (icu) {
  16159. var initWasInvoked = false;
  16160. // if an ICU was created outside of i18n block, we still treat
  16161. // it as a translatable entity and invoke i18nStart and i18nEnd
  16162. // to generate i18n context and the necessary instructions
  16163. if (!this.i18n) {
  16164. initWasInvoked = true;
  16165. this.i18nStart(null, icu.i18n, true);
  16166. }
  16167. var i18n = this.i18n;
  16168. var vars = this.i18nBindProps(icu.vars);
  16169. var placeholders = this.i18nBindProps(icu.placeholders);
  16170. // output ICU directly and keep ICU reference in context
  16171. var message = icu.i18n;
  16172. var transformFn = function (raw) {
  16173. return instruction(null, Identifiers$1.i18nPostprocess, [raw, mapLiteral(vars, true)]);
  16174. };
  16175. // in case the whole i18n message is a single ICU - we do not need to
  16176. // create a separate top-level translation, we can use the root ref instead
  16177. // and make this ICU a top-level translation
  16178. if (isSingleI18nIcu(i18n.meta)) {
  16179. this.i18nTranslate(message, placeholders, i18n.ref, transformFn);
  16180. }
  16181. else {
  16182. // output ICU directly and keep ICU reference in context
  16183. var ref = this.i18nTranslate(message, placeholders, undefined, transformFn);
  16184. i18n.appendIcu(icuFromI18nMessage(message).name, ref);
  16185. }
  16186. if (initWasInvoked) {
  16187. this.i18nEnd(null, true);
  16188. }
  16189. return null;
  16190. };
  16191. TemplateDefinitionBuilder.prototype.allocateDataSlot = function () { return this._dataIndex++; };
  16192. TemplateDefinitionBuilder.prototype.getConstCount = function () { return this._dataIndex; };
  16193. TemplateDefinitionBuilder.prototype.getVarCount = function () { return this._pureFunctionSlots; };
  16194. TemplateDefinitionBuilder.prototype.getNgContentSelectors = function () {
  16195. return this._ngContentReservedSlots.length ?
  16196. this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
  16197. null;
  16198. };
  16199. TemplateDefinitionBuilder.prototype.bindingContext = function () { return "" + this._bindingContext++; };
  16200. TemplateDefinitionBuilder.prototype.templatePropertyBindings = function (templateIndex, attrs) {
  16201. var _this = this;
  16202. var propertyBindings = [];
  16203. attrs.forEach(function (input) {
  16204. if (input instanceof BoundAttribute) {
  16205. var value_4 = input.value.visit(_this._valueConverter);
  16206. if (value_4 !== undefined) {
  16207. _this.allocateBindingSlots(value_4);
  16208. propertyBindings.push({
  16209. name: input.name,
  16210. sourceSpan: input.sourceSpan,
  16211. value: function () { return _this.convertPropertyBinding(value_4); }
  16212. });
  16213. }
  16214. }
  16215. });
  16216. if (propertyBindings.length > 0) {
  16217. this.updateInstructionChain(templateIndex, Identifiers$1.property, propertyBindings);
  16218. }
  16219. };
  16220. // Bindings must only be resolved after all local refs have been visited, so all
  16221. // instructions are queued in callbacks that execute once the initial pass has completed.
  16222. // Otherwise, we wouldn't be able to support local refs that are defined after their
  16223. // bindings. e.g. {{ foo }} <div #foo></div>
  16224. TemplateDefinitionBuilder.prototype.instructionFn = function (fns, span, reference, paramsOrFn, prepend) {
  16225. if (prepend === void 0) { prepend = false; }
  16226. fns[prepend ? 'unshift' : 'push'](function () {
  16227. var params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
  16228. return instruction(span, reference, params).toStmt();
  16229. });
  16230. };
  16231. TemplateDefinitionBuilder.prototype.processStylingInstruction = function (elementIndex, instruction, createMode) {
  16232. var _this = this;
  16233. if (instruction) {
  16234. var paramsFn = function () { return instruction.buildParams(function (value) { return _this.convertPropertyBinding(value); }); };
  16235. if (createMode) {
  16236. this.creationInstruction(instruction.sourceSpan, instruction.reference, paramsFn);
  16237. }
  16238. else {
  16239. this.updateInstruction(elementIndex, instruction.sourceSpan, instruction.reference, paramsFn);
  16240. }
  16241. }
  16242. };
  16243. TemplateDefinitionBuilder.prototype.creationInstruction = function (span, reference, paramsOrFn, prepend) {
  16244. this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
  16245. };
  16246. TemplateDefinitionBuilder.prototype.updateInstruction = function (nodeIndex, span, reference, paramsOrFn) {
  16247. this.addSelectInstructionIfNecessary(nodeIndex, span);
  16248. this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
  16249. };
  16250. TemplateDefinitionBuilder.prototype.updateInstructionChain = function (nodeIndex, reference, bindings) {
  16251. var span = bindings.length ? bindings[0].sourceSpan : null;
  16252. this.addSelectInstructionIfNecessary(nodeIndex, span);
  16253. this._updateCodeFns.push(function () {
  16254. var calls = bindings.map(function (property) {
  16255. var fnParams = __spread([property.value()], (property.params || []));
  16256. if (property.name) {
  16257. fnParams.unshift(literal(property.name));
  16258. }
  16259. return fnParams;
  16260. });
  16261. return chainedInstruction(span, reference, calls).toStmt();
  16262. });
  16263. };
  16264. TemplateDefinitionBuilder.prototype.addSelectInstructionIfNecessary = function (nodeIndex, span) {
  16265. if (this._lastNodeIndexWithFlush < nodeIndex) {
  16266. if (nodeIndex > 0) {
  16267. this.instructionFn(this._updateCodeFns, span, Identifiers$1.select, [literal(nodeIndex)]);
  16268. }
  16269. this._lastNodeIndexWithFlush = nodeIndex;
  16270. }
  16271. };
  16272. TemplateDefinitionBuilder.prototype.allocatePureFunctionSlots = function (numSlots) {
  16273. var originalSlots = this._pureFunctionSlots;
  16274. this._pureFunctionSlots += numSlots;
  16275. return originalSlots;
  16276. };
  16277. TemplateDefinitionBuilder.prototype.allocateBindingSlots = function (value) {
  16278. this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
  16279. };
  16280. /**
  16281. * Gets an expression that refers to the implicit receiver. The implicit
  16282. * receiver is always the root level context.
  16283. */
  16284. TemplateDefinitionBuilder.prototype.getImplicitReceiverExpr = function () {
  16285. if (this._implicitReceiverExpr) {
  16286. return this._implicitReceiverExpr;
  16287. }
  16288. return this._implicitReceiverExpr = this.level === 0 ?
  16289. variable(CONTEXT_NAME) :
  16290. this._bindingScope.getOrCreateSharedContextVar(0);
  16291. };
  16292. TemplateDefinitionBuilder.prototype.convertExpressionBinding = function (value) {
  16293. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple);
  16294. return convertedPropertyBinding.currValExpr;
  16295. };
  16296. TemplateDefinitionBuilder.prototype.convertPropertyBinding = function (value) {
  16297. var _a;
  16298. var interpolationFn = value instanceof Interpolation ? interpolate : function () { return error('Unexpected interpolation'); };
  16299. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple, interpolationFn);
  16300. var valExpr = convertedPropertyBinding.currValExpr;
  16301. (_a = this._tempVariables).push.apply(_a, __spread(convertedPropertyBinding.stmts));
  16302. return valExpr;
  16303. };
  16304. /**
  16305. * Gets a list of argument expressions to pass to an update instruction expression. Also updates
  16306. * the temp variables state with temp variables that were identified as needing to be created
  16307. * while visiting the arguments.
  16308. * @param value The original expression we will be resolving an arguments list from.
  16309. */
  16310. TemplateDefinitionBuilder.prototype.getUpdateInstructionArguments = function (value) {
  16311. var _a;
  16312. var _b = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext()), args = _b.args, stmts = _b.stmts;
  16313. (_a = this._tempVariables).push.apply(_a, __spread(stmts));
  16314. return args;
  16315. };
  16316. TemplateDefinitionBuilder.prototype.matchDirectives = function (tagName, elOrTpl) {
  16317. var _this = this;
  16318. if (this.directiveMatcher) {
  16319. var selector = createCssSelector(tagName, getAttrsForDirectiveMatching(elOrTpl));
  16320. this.directiveMatcher.match(selector, function (cssSelector, staticType) { _this.directives.add(staticType); });
  16321. }
  16322. };
  16323. /**
  16324. * Prepares all attribute expression values for the `TAttributes` array.
  16325. *
  16326. * The purpose of this function is to properly construct an attributes array that
  16327. * is passed into the `elementStart` (or just `element`) functions. Because there
  16328. * are many different types of attributes, the array needs to be constructed in a
  16329. * special way so that `elementStart` can properly evaluate them.
  16330. *
  16331. * The format looks like this:
  16332. *
  16333. * ```
  16334. * attrs = [prop, value, prop2, value2,
  16335. * CLASSES, class1, class2,
  16336. * STYLES, style1, value1, style2, value2,
  16337. * BINDINGS, name1, name2, name3,
  16338. * TEMPLATE, name4, name5, name6,
  16339. * I18N, name7, name8, ...]
  16340. * ```
  16341. *
  16342. * Note that this function will fully ignore all synthetic (@foo) attribute values
  16343. * because those values are intended to always be generated as property instructions.
  16344. */
  16345. TemplateDefinitionBuilder.prototype.prepareNonRenderAttrs = function (inputs, outputs, styles, templateAttrs, i18nAttrs) {
  16346. if (templateAttrs === void 0) { templateAttrs = []; }
  16347. if (i18nAttrs === void 0) { i18nAttrs = []; }
  16348. var alreadySeen = new Set();
  16349. var attrExprs = [];
  16350. function addAttrExpr(key, value) {
  16351. if (typeof key === 'string') {
  16352. if (!alreadySeen.has(key)) {
  16353. attrExprs.push.apply(attrExprs, __spread(getAttributeNameLiterals(key)));
  16354. value !== undefined && attrExprs.push(value);
  16355. alreadySeen.add(key);
  16356. }
  16357. }
  16358. else {
  16359. attrExprs.push(literal(key));
  16360. }
  16361. }
  16362. // it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
  16363. // comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
  16364. // as single property value cell by cell.
  16365. if (styles) {
  16366. styles.populateInitialStylingAttrs(attrExprs);
  16367. }
  16368. if (inputs.length || outputs.length) {
  16369. var attrsStartIndex = attrExprs.length;
  16370. for (var i = 0; i < inputs.length; i++) {
  16371. var input = inputs[i];
  16372. if (input.type !== 4 /* Animation */) {
  16373. addAttrExpr(input.name);
  16374. }
  16375. }
  16376. for (var i = 0; i < outputs.length; i++) {
  16377. var output = outputs[i];
  16378. if (output.type !== 1 /* Animation */) {
  16379. addAttrExpr(output.name);
  16380. }
  16381. }
  16382. // this is a cheap way of adding the marker only after all the input/output
  16383. // values have been filtered (by not including the animation ones) and added
  16384. // to the expressions. The marker is important because it tells the runtime
  16385. // code that this is where attributes without values start...
  16386. if (attrExprs.length) {
  16387. attrExprs.splice(attrsStartIndex, 0, literal(3 /* Bindings */));
  16388. }
  16389. }
  16390. if (templateAttrs.length) {
  16391. attrExprs.push(literal(4 /* Template */));
  16392. templateAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  16393. }
  16394. if (i18nAttrs.length) {
  16395. attrExprs.push(literal(6 /* I18n */));
  16396. i18nAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  16397. }
  16398. return attrExprs;
  16399. };
  16400. TemplateDefinitionBuilder.prototype.toAttrsParam = function (attrsExprs) {
  16401. return attrsExprs.length > 0 ?
  16402. this.constantPool.getConstLiteral(literalArr(attrsExprs), true) :
  16403. TYPED_NULL_EXPR;
  16404. };
  16405. TemplateDefinitionBuilder.prototype.prepareRefsParameter = function (references) {
  16406. var _this = this;
  16407. if (!references || references.length === 0) {
  16408. return TYPED_NULL_EXPR;
  16409. }
  16410. var refsParam = flatten(references.map(function (reference) {
  16411. var slot = _this.allocateDataSlot();
  16412. // Generate the update temporary.
  16413. var variableName = _this._bindingScope.freshReferenceName();
  16414. var retrievalLevel = _this.level;
  16415. var lhs = variable(variableName);
  16416. _this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, function (scope, relativeLevel) {
  16417. // e.g. nextContext(2);
  16418. var nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
  16419. // e.g. const $foo$ = reference(1);
  16420. var refExpr = lhs.set(importExpr(Identifiers$1.reference).callFn([literal(slot)]));
  16421. return nextContextStmt.concat(refExpr.toConstDecl());
  16422. }, true);
  16423. return [reference.name, reference.value];
  16424. }));
  16425. return this.constantPool.getConstLiteral(asLiteral(refsParam), true);
  16426. };
  16427. TemplateDefinitionBuilder.prototype.prepareListenerParameter = function (tagName, outputAst, index) {
  16428. var _this = this;
  16429. return function () {
  16430. var eventName = outputAst.name;
  16431. var bindingFnName = outputAst.type === 1 /* Animation */ ?
  16432. // synthetic @listener.foo values are treated the exact same as are standard listeners
  16433. prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
  16434. sanitizeIdentifier(eventName);
  16435. var handlerName = _this.templateName + "_" + tagName + "_" + bindingFnName + "_" + index + "_listener";
  16436. var scope = _this._bindingScope.nestedScope(_this._bindingScope.bindingLevel);
  16437. return prepareEventListenerParameters(outputAst, handlerName, scope);
  16438. };
  16439. };
  16440. return TemplateDefinitionBuilder;
  16441. }());
  16442. var ValueConverter = /** @class */ (function (_super) {
  16443. __extends(ValueConverter, _super);
  16444. function ValueConverter(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
  16445. var _this = _super.call(this) || this;
  16446. _this.constantPool = constantPool;
  16447. _this.allocateSlot = allocateSlot;
  16448. _this.allocatePureFunctionSlots = allocatePureFunctionSlots;
  16449. _this.definePipe = definePipe;
  16450. _this._pipeBindExprs = [];
  16451. return _this;
  16452. }
  16453. // AstMemoryEfficientTransformer
  16454. ValueConverter.prototype.visitPipe = function (pipe, context) {
  16455. // Allocate a slot to create the pipe
  16456. var slot = this.allocateSlot();
  16457. var slotPseudoLocal = "PIPE:" + slot;
  16458. // Allocate one slot for the result plus one slot per pipe argument
  16459. var pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
  16460. var target = new PropertyRead(pipe.span, new ImplicitReceiver(pipe.span), slotPseudoLocal);
  16461. var _a = pipeBindingCallInfo(pipe.args), identifier = _a.identifier, isVarLength = _a.isVarLength;
  16462. this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
  16463. var args = __spread([pipe.exp], pipe.args);
  16464. var convertedArgs = isVarLength ? this.visitAll([new LiteralArray(pipe.span, args)]) : this.visitAll(args);
  16465. var pipeBindExpr = new FunctionCall(pipe.span, target, __spread([
  16466. new LiteralPrimitive(pipe.span, slot),
  16467. new LiteralPrimitive(pipe.span, pureFunctionSlot)
  16468. ], convertedArgs));
  16469. this._pipeBindExprs.push(pipeBindExpr);
  16470. return pipeBindExpr;
  16471. };
  16472. ValueConverter.prototype.updatePipeSlotOffsets = function (bindingSlots) {
  16473. this._pipeBindExprs.forEach(function (pipe) {
  16474. // update the slot offset arg (index 1) to account for binding slots
  16475. var slotOffset = pipe.args[1];
  16476. slotOffset.value += bindingSlots;
  16477. });
  16478. };
  16479. ValueConverter.prototype.visitLiteralArray = function (array, context) {
  16480. var _this = this;
  16481. return new BuiltinFunctionCall(array.span, this.visitAll(array.expressions), function (values) {
  16482. // If the literal has calculated (non-literal) elements transform it into
  16483. // calls to literal factories that compose the literal and will cache intermediate
  16484. // values. Otherwise, just return an literal array that contains the values.
  16485. var literal = literalArr(values);
  16486. return values.every(function (a) { return a.isConstant(); }) ?
  16487. _this.constantPool.getConstLiteral(literal, true) :
  16488. getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  16489. });
  16490. };
  16491. ValueConverter.prototype.visitLiteralMap = function (map, context) {
  16492. var _this = this;
  16493. return new BuiltinFunctionCall(map.span, this.visitAll(map.values), function (values) {
  16494. // If the literal has calculated (non-literal) elements transform it into
  16495. // calls to literal factories that compose the literal and will cache intermediate
  16496. // values. Otherwise, just return an literal array that contains the values.
  16497. var literal = literalMap(values.map(function (value, index) { return ({ key: map.keys[index].key, value: value, quoted: map.keys[index].quoted }); }));
  16498. return values.every(function (a) { return a.isConstant(); }) ?
  16499. _this.constantPool.getConstLiteral(literal, true) :
  16500. getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  16501. });
  16502. };
  16503. return ValueConverter;
  16504. }(AstMemoryEfficientTransformer));
  16505. // Pipes always have at least one parameter, the value they operate on
  16506. var pipeBindingIdentifiers = [Identifiers$1.pipeBind1, Identifiers$1.pipeBind2, Identifiers$1.pipeBind3, Identifiers$1.pipeBind4];
  16507. function pipeBindingCallInfo(args) {
  16508. var identifier = pipeBindingIdentifiers[args.length];
  16509. return {
  16510. identifier: identifier || Identifiers$1.pipeBindV,
  16511. isVarLength: !identifier,
  16512. };
  16513. }
  16514. var pureFunctionIdentifiers = [
  16515. Identifiers$1.pureFunction0, Identifiers$1.pureFunction1, Identifiers$1.pureFunction2, Identifiers$1.pureFunction3, Identifiers$1.pureFunction4,
  16516. Identifiers$1.pureFunction5, Identifiers$1.pureFunction6, Identifiers$1.pureFunction7, Identifiers$1.pureFunction8
  16517. ];
  16518. function pureFunctionCallInfo(args) {
  16519. var identifier = pureFunctionIdentifiers[args.length];
  16520. return {
  16521. identifier: identifier || Identifiers$1.pureFunctionV,
  16522. isVarLength: !identifier,
  16523. };
  16524. }
  16525. function instruction(span, reference, params) {
  16526. return importExpr(reference, null, span).callFn(params, span);
  16527. }
  16528. function chainedInstruction(span, reference, calls) {
  16529. var expression = importExpr(reference, null, span);
  16530. if (calls.length > 0) {
  16531. for (var i = 0; i < calls.length; i++) {
  16532. expression = expression.callFn(calls[i], span);
  16533. }
  16534. }
  16535. else {
  16536. // Add a blank invocation, in case the `calls` array is empty.
  16537. expression = expression.callFn([], span);
  16538. }
  16539. return expression;
  16540. }
  16541. // e.g. x(2);
  16542. function generateNextContextExpr(relativeLevelDiff) {
  16543. return importExpr(Identifiers$1.nextContext)
  16544. .callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
  16545. }
  16546. function getLiteralFactory(constantPool, literal$1, allocateSlots) {
  16547. var _a = constantPool.getLiteralFactory(literal$1), literalFactory = _a.literalFactory, literalFactoryArguments = _a.literalFactoryArguments;
  16548. // Allocate 1 slot for the result plus 1 per argument
  16549. var startSlot = allocateSlots(1 + literalFactoryArguments.length);
  16550. literalFactoryArguments.length > 0 || error("Expected arguments to a literal factory function");
  16551. var _b = pureFunctionCallInfo(literalFactoryArguments), identifier = _b.identifier, isVarLength = _b.isVarLength;
  16552. // Literal factories are pure functions that only need to be re-invoked when the parameters
  16553. // change.
  16554. var args = [
  16555. literal(startSlot),
  16556. literalFactory,
  16557. ];
  16558. if (isVarLength) {
  16559. args.push(literalArr(literalFactoryArguments));
  16560. }
  16561. else {
  16562. args.push.apply(args, __spread(literalFactoryArguments));
  16563. }
  16564. return importExpr(identifier).callFn(args);
  16565. }
  16566. /**
  16567. * Gets an array of literals that can be added to an expression
  16568. * to represent the name and namespace of an attribute. E.g.
  16569. * `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
  16570. *
  16571. * @param name Name of the attribute, including the namespace.
  16572. */
  16573. function getAttributeNameLiterals(name) {
  16574. var _a = __read(splitNsName(name), 2), attributeNamespace = _a[0], attributeName = _a[1];
  16575. var nameLiteral = literal(attributeName);
  16576. if (attributeNamespace) {
  16577. return [
  16578. literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
  16579. ];
  16580. }
  16581. return [nameLiteral];
  16582. }
  16583. /** The prefix used to get a shared context in BindingScope's map. */
  16584. var SHARED_CONTEXT_KEY = '$$shared_ctx$$';
  16585. var BindingScope = /** @class */ (function () {
  16586. function BindingScope(bindingLevel, parent) {
  16587. if (bindingLevel === void 0) { bindingLevel = 0; }
  16588. if (parent === void 0) { parent = null; }
  16589. this.bindingLevel = bindingLevel;
  16590. this.parent = parent;
  16591. /** Keeps a map from local variables to their BindingData. */
  16592. this.map = new Map();
  16593. this.referenceNameIndex = 0;
  16594. this.restoreViewVariable = null;
  16595. }
  16596. Object.defineProperty(BindingScope, "ROOT_SCOPE", {
  16597. get: function () {
  16598. if (!BindingScope._ROOT_SCOPE) {
  16599. BindingScope._ROOT_SCOPE = new BindingScope().set(0, '$event', variable('$event'));
  16600. }
  16601. return BindingScope._ROOT_SCOPE;
  16602. },
  16603. enumerable: true,
  16604. configurable: true
  16605. });
  16606. BindingScope.prototype.get = function (name) {
  16607. var current = this;
  16608. while (current) {
  16609. var value = current.map.get(name);
  16610. if (value != null) {
  16611. if (current !== this) {
  16612. // make a local copy and reset the `declare` state
  16613. value = {
  16614. retrievalLevel: value.retrievalLevel,
  16615. lhs: value.lhs,
  16616. declareLocalCallback: value.declareLocalCallback,
  16617. declare: false,
  16618. priority: value.priority,
  16619. localRef: value.localRef
  16620. };
  16621. // Cache the value locally.
  16622. this.map.set(name, value);
  16623. // Possibly generate a shared context var
  16624. this.maybeGenerateSharedContextVar(value);
  16625. this.maybeRestoreView(value.retrievalLevel, value.localRef);
  16626. }
  16627. if (value.declareLocalCallback && !value.declare) {
  16628. value.declare = true;
  16629. }
  16630. return value.lhs;
  16631. }
  16632. current = current.parent;
  16633. }
  16634. // If we get to this point, we are looking for a property on the top level component
  16635. // - If level === 0, we are on the top and don't need to re-declare `ctx`.
  16636. // - If level > 0, we are in an embedded view. We need to retrieve the name of the
  16637. // local var we used to store the component context, e.g. const $comp$ = x();
  16638. return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
  16639. };
  16640. /**
  16641. * Create a local variable for later reference.
  16642. *
  16643. * @param retrievalLevel The level from which this value can be retrieved
  16644. * @param name Name of the variable.
  16645. * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
  16646. * @param priority The sorting priority of this var
  16647. * @param declareLocalCallback The callback to invoke when declaring this local var
  16648. * @param localRef Whether or not this is a local ref
  16649. */
  16650. BindingScope.prototype.set = function (retrievalLevel, name, lhs, priority, declareLocalCallback, localRef) {
  16651. if (priority === void 0) { priority = 0 /* DEFAULT */; }
  16652. if (this.map.has(name)) {
  16653. if (localRef) {
  16654. // Do not throw an error if it's a local ref and do not update existing value,
  16655. // so the first defined ref is always returned.
  16656. return this;
  16657. }
  16658. error("The name " + name + " is already defined in scope to be " + this.map.get(name));
  16659. }
  16660. this.map.set(name, {
  16661. retrievalLevel: retrievalLevel,
  16662. lhs: lhs,
  16663. declare: false,
  16664. declareLocalCallback: declareLocalCallback,
  16665. priority: priority,
  16666. localRef: localRef || false
  16667. });
  16668. return this;
  16669. };
  16670. // Implemented as part of LocalResolver.
  16671. BindingScope.prototype.getLocal = function (name) { return this.get(name); };
  16672. // Implemented as part of LocalResolver.
  16673. BindingScope.prototype.notifyImplicitReceiverUse = function () {
  16674. if (this.bindingLevel !== 0) {
  16675. // Since the implicit receiver is accessed in an embedded view, we need to
  16676. // ensure that we declare a shared context variable for the current template
  16677. // in the update variables.
  16678. this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
  16679. }
  16680. };
  16681. BindingScope.prototype.nestedScope = function (level) {
  16682. var newScope = new BindingScope(level, this);
  16683. if (level > 0)
  16684. newScope.generateSharedContextVar(0);
  16685. return newScope;
  16686. };
  16687. /**
  16688. * Gets or creates a shared context variable and returns its expression. Note that
  16689. * this does not mean that the shared variable will be declared. Variables in the
  16690. * binding scope will be only declared if they are used.
  16691. */
  16692. BindingScope.prototype.getOrCreateSharedContextVar = function (retrievalLevel) {
  16693. var bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
  16694. if (!this.map.has(bindingKey)) {
  16695. this.generateSharedContextVar(retrievalLevel);
  16696. }
  16697. return this.map.get(bindingKey).lhs;
  16698. };
  16699. BindingScope.prototype.getSharedContextName = function (retrievalLevel) {
  16700. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
  16701. return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
  16702. };
  16703. BindingScope.prototype.maybeGenerateSharedContextVar = function (value) {
  16704. if (value.priority === 1 /* CONTEXT */ &&
  16705. value.retrievalLevel < this.bindingLevel) {
  16706. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
  16707. if (sharedCtxObj) {
  16708. sharedCtxObj.declare = true;
  16709. }
  16710. else {
  16711. this.generateSharedContextVar(value.retrievalLevel);
  16712. }
  16713. }
  16714. };
  16715. BindingScope.prototype.generateSharedContextVar = function (retrievalLevel) {
  16716. var lhs = variable(CONTEXT_NAME + this.freshReferenceName());
  16717. this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
  16718. retrievalLevel: retrievalLevel,
  16719. lhs: lhs,
  16720. declareLocalCallback: function (scope, relativeLevel) {
  16721. // const ctx_r0 = nextContext(2);
  16722. return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
  16723. },
  16724. declare: false,
  16725. priority: 2 /* SHARED_CONTEXT */,
  16726. localRef: false
  16727. });
  16728. };
  16729. BindingScope.prototype.getComponentProperty = function (name) {
  16730. var componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
  16731. componentValue.declare = true;
  16732. this.maybeRestoreView(0, false);
  16733. return componentValue.lhs.prop(name);
  16734. };
  16735. BindingScope.prototype.maybeRestoreView = function (retrievalLevel, localRefLookup) {
  16736. // We want to restore the current view in listener fns if:
  16737. // 1 - we are accessing a value in a parent view, which requires walking the view tree rather
  16738. // than using the ctx arg. In this case, the retrieval and binding level will be different.
  16739. // 2 - we are looking up a local ref, which requires restoring the view where the local
  16740. // ref is stored
  16741. if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
  16742. if (!this.parent.restoreViewVariable) {
  16743. // parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
  16744. this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
  16745. }
  16746. this.restoreViewVariable = this.parent.restoreViewVariable;
  16747. }
  16748. };
  16749. BindingScope.prototype.restoreViewStatement = function () {
  16750. // restoreView($state$);
  16751. return this.restoreViewVariable ?
  16752. [instruction(null, Identifiers$1.restoreView, [this.restoreViewVariable]).toStmt()] :
  16753. [];
  16754. };
  16755. BindingScope.prototype.viewSnapshotStatements = function () {
  16756. // const $state$ = getCurrentView();
  16757. var getCurrentViewInstruction = instruction(null, Identifiers$1.getCurrentView, []);
  16758. return this.restoreViewVariable ?
  16759. [this.restoreViewVariable.set(getCurrentViewInstruction).toConstDecl()] :
  16760. [];
  16761. };
  16762. BindingScope.prototype.isListenerScope = function () { return this.parent && this.parent.bindingLevel === this.bindingLevel; };
  16763. BindingScope.prototype.variableDeclarations = function () {
  16764. var _this = this;
  16765. var currentContextLevel = 0;
  16766. return Array.from(this.map.values())
  16767. .filter(function (value) { return value.declare; })
  16768. .sort(function (a, b) { return b.retrievalLevel - a.retrievalLevel || b.priority - a.priority; })
  16769. .reduce(function (stmts, value) {
  16770. var levelDiff = _this.bindingLevel - value.retrievalLevel;
  16771. var currStmts = value.declareLocalCallback(_this, levelDiff - currentContextLevel);
  16772. currentContextLevel = levelDiff;
  16773. return stmts.concat(currStmts);
  16774. }, []);
  16775. };
  16776. BindingScope.prototype.freshReferenceName = function () {
  16777. var current = this;
  16778. // Find the top scope as it maintains the global reference count
  16779. while (current.parent)
  16780. current = current.parent;
  16781. var ref = "" + REFERENCE_PREFIX + current.referenceNameIndex++;
  16782. return ref;
  16783. };
  16784. return BindingScope;
  16785. }());
  16786. /**
  16787. * Creates a `CssSelector` given a tag name and a map of attributes
  16788. */
  16789. function createCssSelector(tag, attributes) {
  16790. var cssSelector = new CssSelector();
  16791. cssSelector.setElement(tag);
  16792. Object.getOwnPropertyNames(attributes).forEach(function (name) {
  16793. var value = attributes[name];
  16794. cssSelector.addAttribute(name, value);
  16795. if (name.toLowerCase() === 'class') {
  16796. var classes = value.trim().split(/\s+/);
  16797. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  16798. }
  16799. });
  16800. return cssSelector;
  16801. }
  16802. /**
  16803. * Creates an array of expressions out of an `ngProjectAs` attributes
  16804. * which can be added to the instruction parameters.
  16805. */
  16806. function getNgProjectAsLiteral(attribute) {
  16807. // Parse the attribute value into a CssSelectorList. Note that we only take the
  16808. // first selector, because we don't support multiple selectors in ngProjectAs.
  16809. var parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
  16810. return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
  16811. }
  16812. function interpolate(args) {
  16813. args = args.slice(1); // Ignore the length prefix added for render2
  16814. switch (args.length) {
  16815. case 3:
  16816. return importExpr(Identifiers$1.interpolation1).callFn(args);
  16817. case 5:
  16818. return importExpr(Identifiers$1.interpolation2).callFn(args);
  16819. case 7:
  16820. return importExpr(Identifiers$1.interpolation3).callFn(args);
  16821. case 9:
  16822. return importExpr(Identifiers$1.interpolation4).callFn(args);
  16823. case 11:
  16824. return importExpr(Identifiers$1.interpolation5).callFn(args);
  16825. case 13:
  16826. return importExpr(Identifiers$1.interpolation6).callFn(args);
  16827. case 15:
  16828. return importExpr(Identifiers$1.interpolation7).callFn(args);
  16829. case 17:
  16830. return importExpr(Identifiers$1.interpolation8).callFn(args);
  16831. }
  16832. (args.length >= 19 && args.length % 2 == 1) ||
  16833. error("Invalid interpolation argument length " + args.length);
  16834. return importExpr(Identifiers$1.interpolationV).callFn([literalArr(args)]);
  16835. }
  16836. /**
  16837. * Gets the instruction to generate for an interpolated property
  16838. * @param interpolation An Interpolation AST
  16839. */
  16840. function getPropertyInterpolationExpression(interpolation) {
  16841. switch (getInterpolationArgsLength(interpolation)) {
  16842. case 1:
  16843. return Identifiers$1.propertyInterpolate;
  16844. case 3:
  16845. return Identifiers$1.propertyInterpolate1;
  16846. case 5:
  16847. return Identifiers$1.propertyInterpolate2;
  16848. case 7:
  16849. return Identifiers$1.propertyInterpolate3;
  16850. case 9:
  16851. return Identifiers$1.propertyInterpolate4;
  16852. case 11:
  16853. return Identifiers$1.propertyInterpolate5;
  16854. case 13:
  16855. return Identifiers$1.propertyInterpolate6;
  16856. case 15:
  16857. return Identifiers$1.propertyInterpolate7;
  16858. case 17:
  16859. return Identifiers$1.propertyInterpolate8;
  16860. default:
  16861. return Identifiers$1.propertyInterpolateV;
  16862. }
  16863. }
  16864. /**
  16865. * Gets the instruction to generate for an interpolated attribute
  16866. * @param interpolation An Interpolation AST
  16867. */
  16868. function getAttributeInterpolationExpression(interpolation) {
  16869. switch (getInterpolationArgsLength(interpolation)) {
  16870. case 3:
  16871. return Identifiers$1.attributeInterpolate1;
  16872. case 5:
  16873. return Identifiers$1.attributeInterpolate2;
  16874. case 7:
  16875. return Identifiers$1.attributeInterpolate3;
  16876. case 9:
  16877. return Identifiers$1.attributeInterpolate4;
  16878. case 11:
  16879. return Identifiers$1.attributeInterpolate5;
  16880. case 13:
  16881. return Identifiers$1.attributeInterpolate6;
  16882. case 15:
  16883. return Identifiers$1.attributeInterpolate7;
  16884. case 17:
  16885. return Identifiers$1.attributeInterpolate8;
  16886. default:
  16887. return Identifiers$1.attributeInterpolateV;
  16888. }
  16889. }
  16890. /**
  16891. * Gets the instruction to generate for interpolated text.
  16892. * @param interpolation An Interpolation AST
  16893. */
  16894. function getTextInterpolationExpression(interpolation) {
  16895. switch (getInterpolationArgsLength(interpolation)) {
  16896. case 1:
  16897. return Identifiers$1.textInterpolate;
  16898. case 3:
  16899. return Identifiers$1.textInterpolate1;
  16900. case 5:
  16901. return Identifiers$1.textInterpolate2;
  16902. case 7:
  16903. return Identifiers$1.textInterpolate3;
  16904. case 9:
  16905. return Identifiers$1.textInterpolate4;
  16906. case 11:
  16907. return Identifiers$1.textInterpolate5;
  16908. case 13:
  16909. return Identifiers$1.textInterpolate6;
  16910. case 15:
  16911. return Identifiers$1.textInterpolate7;
  16912. case 17:
  16913. return Identifiers$1.textInterpolate8;
  16914. default:
  16915. return Identifiers$1.textInterpolateV;
  16916. }
  16917. }
  16918. /**
  16919. * Gets the number of arguments expected to be passed to a generated instruction in the case of
  16920. * interpolation instructions.
  16921. * @param interpolation An interpolation ast
  16922. */
  16923. function getInterpolationArgsLength(interpolation) {
  16924. var expressions = interpolation.expressions, strings = interpolation.strings;
  16925. if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
  16926. // If the interpolation has one interpolated value, but the prefix and suffix are both empty
  16927. // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
  16928. // `textInterpolate`.
  16929. return 1;
  16930. }
  16931. else {
  16932. return expressions.length + strings.length;
  16933. }
  16934. }
  16935. /**
  16936. * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
  16937. *
  16938. * @param template text of the template to parse
  16939. * @param templateUrl URL to use for source mapping of the parsed template
  16940. * @param options options to modify how the template is parsed
  16941. */
  16942. function parseTemplate(template, templateUrl, options) {
  16943. if (options === void 0) { options = {}; }
  16944. var interpolationConfig = options.interpolationConfig, preserveWhitespaces = options.preserveWhitespaces;
  16945. var bindingParser = makeBindingParser(interpolationConfig);
  16946. var htmlParser = new HtmlParser();
  16947. var parseResult = htmlParser.parse(template, templateUrl, __assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options, { tokenizeExpansionForms: true }));
  16948. if (parseResult.errors && parseResult.errors.length > 0) {
  16949. return { errors: parseResult.errors, nodes: [], styleUrls: [], styles: [] };
  16950. }
  16951. var rootNodes = parseResult.rootNodes;
  16952. // process i18n meta information (scan attributes, generate ids)
  16953. // before we run whitespace removal process, because existing i18n
  16954. // extraction process (ng xi18n) relies on a raw content to generate
  16955. // message ids
  16956. rootNodes =
  16957. visitAll$1(new I18nMetaVisitor(interpolationConfig, !preserveWhitespaces), rootNodes);
  16958. if (!preserveWhitespaces) {
  16959. rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
  16960. // run i18n meta visitor again in case we remove whitespaces, because
  16961. // that might affect generated i18n message content. During this pass
  16962. // i18n IDs generated at the first pass will be preserved, so we can mimic
  16963. // existing extraction process (ng xi18n)
  16964. rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
  16965. }
  16966. var _a = htmlAstToRender3Ast(rootNodes, bindingParser), nodes = _a.nodes, errors = _a.errors, styleUrls = _a.styleUrls, styles = _a.styles;
  16967. if (errors && errors.length > 0) {
  16968. return { errors: errors, nodes: [], styleUrls: [], styles: [] };
  16969. }
  16970. return { nodes: nodes, styleUrls: styleUrls, styles: styles };
  16971. }
  16972. /**
  16973. * Construct a `BindingParser` with a default configuration.
  16974. */
  16975. function makeBindingParser(interpolationConfig) {
  16976. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  16977. return new BindingParser(new Parser$1(new Lexer()), interpolationConfig, new DomElementSchemaRegistry(), null, []);
  16978. }
  16979. function resolveSanitizationFn(context, isAttribute) {
  16980. switch (context) {
  16981. case SecurityContext.HTML:
  16982. return importExpr(Identifiers$1.sanitizeHtml);
  16983. case SecurityContext.SCRIPT:
  16984. return importExpr(Identifiers$1.sanitizeScript);
  16985. case SecurityContext.STYLE:
  16986. // the compiler does not fill in an instruction for [style.prop?] binding
  16987. // values because the style algorithm knows internally what props are subject
  16988. // to sanitization (only [attr.style] values are explicitly sanitized)
  16989. return isAttribute ? importExpr(Identifiers$1.sanitizeStyle) : null;
  16990. case SecurityContext.URL:
  16991. return importExpr(Identifiers$1.sanitizeUrl);
  16992. case SecurityContext.RESOURCE_URL:
  16993. return importExpr(Identifiers$1.sanitizeResourceUrl);
  16994. default:
  16995. return null;
  16996. }
  16997. }
  16998. function isSingleElementTemplate(children) {
  16999. return children.length === 1 && children[0] instanceof Element;
  17000. }
  17001. function isTextNode(node) {
  17002. return node instanceof Text || node instanceof BoundText || node instanceof Icu;
  17003. }
  17004. function hasTextChildrenOnly(children) {
  17005. return children.every(isTextNode);
  17006. }
  17007. /**
  17008. * @license
  17009. * Copyright Google Inc. All Rights Reserved.
  17010. *
  17011. * Use of this source code is governed by an MIT-style license that can be
  17012. * found in the LICENSE file at https://angular.io/license
  17013. */
  17014. var EMPTY_ARRAY = [];
  17015. // This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
  17016. // If there is a match, the first matching group will contain the attribute name to bind.
  17017. var ATTR_REGEX = /attr\.([^\]]+)/;
  17018. function getStylingPrefix(name) {
  17019. return name.substring(0, 5); // style or class
  17020. }
  17021. function baseDirectiveFields(meta, constantPool, bindingParser) {
  17022. var definitionMap = new DefinitionMap();
  17023. // e.g. `type: MyDirective`
  17024. definitionMap.set('type', meta.type);
  17025. // e.g. `selectors: [['', 'someDir', '']]`
  17026. definitionMap.set('selectors', createDirectiveSelector(meta.selector));
  17027. // e.g. `factory: () => new MyApp(directiveInject(ElementRef))`
  17028. var result = compileFactoryFunction({
  17029. name: meta.name,
  17030. type: meta.type,
  17031. deps: meta.deps,
  17032. injectFn: Identifiers$1.directiveInject,
  17033. });
  17034. definitionMap.set('factory', result.factory);
  17035. if (meta.queries.length > 0) {
  17036. // e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
  17037. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
  17038. }
  17039. if (meta.viewQueries.length) {
  17040. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
  17041. }
  17042. // e.g. `hostBindings: (rf, ctx, elIndex) => { ... }
  17043. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name));
  17044. // e.g 'inputs: {a: 'a'}`
  17045. definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
  17046. // e.g 'outputs: {a: 'a'}`
  17047. definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
  17048. if (meta.exportAs !== null) {
  17049. definitionMap.set('exportAs', literalArr(meta.exportAs.map(function (e) { return literal(e); })));
  17050. }
  17051. return { definitionMap: definitionMap, statements: result.statements };
  17052. }
  17053. /**
  17054. * Add features to the definition map.
  17055. */
  17056. function addFeatures(definitionMap, meta) {
  17057. // e.g. `features: [NgOnChangesFeature()]`
  17058. var features = [];
  17059. var providers = meta.providers;
  17060. var viewProviders = meta.viewProviders;
  17061. if (providers || viewProviders) {
  17062. var args = [providers || new LiteralArrayExpr([])];
  17063. if (viewProviders) {
  17064. args.push(viewProviders);
  17065. }
  17066. features.push(importExpr(Identifiers$1.ProvidersFeature).callFn(args));
  17067. }
  17068. if (meta.usesInheritance) {
  17069. features.push(importExpr(Identifiers$1.InheritDefinitionFeature));
  17070. }
  17071. if (meta.lifecycle.usesOnChanges) {
  17072. features.push(importExpr(Identifiers$1.NgOnChangesFeature).callFn(EMPTY_ARRAY));
  17073. }
  17074. if (features.length) {
  17075. definitionMap.set('features', literalArr(features));
  17076. }
  17077. }
  17078. /**
  17079. * Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
  17080. */
  17081. function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
  17082. var _a = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _a.definitionMap, statements = _a.statements;
  17083. addFeatures(definitionMap, meta);
  17084. var expression = importExpr(Identifiers$1.defineDirective).callFn([definitionMap.toLiteralMap()]);
  17085. if (!meta.selector) {
  17086. throw new Error("Directive " + meta.name + " has no selector, please add it!");
  17087. }
  17088. var type = createTypeForDef(meta, Identifiers$1.DirectiveDefWithMeta);
  17089. return { expression: expression, type: type, statements: statements };
  17090. }
  17091. /**
  17092. * Compile a base definition for the render3 runtime as defined by {@link R3BaseRefMetadata}
  17093. * @param meta the metadata used for compilation.
  17094. */
  17095. function compileBaseDefFromMetadata(meta, constantPool, bindingParser) {
  17096. var definitionMap = new DefinitionMap();
  17097. if (meta.inputs) {
  17098. var inputs_1 = meta.inputs;
  17099. var inputsMap = Object.keys(inputs_1).map(function (key) {
  17100. var v = inputs_1[key];
  17101. var value = Array.isArray(v) ? literalArr(v.map(function (vx) { return literal(vx); })) : literal(v);
  17102. return { key: key, value: value, quoted: false };
  17103. });
  17104. definitionMap.set('inputs', literalMap(inputsMap));
  17105. }
  17106. if (meta.outputs) {
  17107. var outputs_1 = meta.outputs;
  17108. var outputsMap = Object.keys(outputs_1).map(function (key) {
  17109. var value = literal(outputs_1[key]);
  17110. return { key: key, value: value, quoted: false };
  17111. });
  17112. definitionMap.set('outputs', literalMap(outputsMap));
  17113. }
  17114. if (meta.viewQueries && meta.viewQueries.length > 0) {
  17115. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool));
  17116. }
  17117. if (meta.queries && meta.queries.length > 0) {
  17118. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool));
  17119. }
  17120. if (meta.host) {
  17121. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.name));
  17122. }
  17123. var expression = importExpr(Identifiers$1.defineBase).callFn([definitionMap.toLiteralMap()]);
  17124. var type = new ExpressionType(importExpr(Identifiers$1.BaseDef));
  17125. return { expression: expression, type: type };
  17126. }
  17127. /**
  17128. * Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
  17129. */
  17130. function compileComponentFromMetadata(meta, constantPool, bindingParser) {
  17131. var e_1, _a;
  17132. var _b = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _b.definitionMap, statements = _b.statements;
  17133. addFeatures(definitionMap, meta);
  17134. var selector = meta.selector && CssSelector.parse(meta.selector);
  17135. var firstSelector = selector && selector[0];
  17136. // e.g. `attr: ["class", ".my.app"]`
  17137. // This is optional an only included if the first selector of a component specifies attributes.
  17138. if (firstSelector) {
  17139. var selectorAttributes = firstSelector.getAttrs();
  17140. if (selectorAttributes.length) {
  17141. definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(function (value) { return value != null ? literal(value) : literal(undefined); })),
  17142. /* forceShared */ true));
  17143. }
  17144. }
  17145. // Generate the CSS matcher that recognize directive
  17146. var directiveMatcher = null;
  17147. if (meta.directives.length > 0) {
  17148. var matcher = new SelectorMatcher();
  17149. try {
  17150. for (var _c = __values(meta.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
  17151. var _e = _d.value, selector_1 = _e.selector, expression_1 = _e.expression;
  17152. matcher.addSelectables(CssSelector.parse(selector_1), expression_1);
  17153. }
  17154. }
  17155. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  17156. finally {
  17157. try {
  17158. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  17159. }
  17160. finally { if (e_1) throw e_1.error; }
  17161. }
  17162. directiveMatcher = matcher;
  17163. }
  17164. // e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
  17165. var templateTypeName = meta.name;
  17166. var templateName = templateTypeName ? templateTypeName + "_Template" : null;
  17167. var directivesUsed = new Set();
  17168. var pipesUsed = new Set();
  17169. var changeDetection = meta.changeDetection;
  17170. var template = meta.template;
  17171. var templateBuilder = new TemplateDefinitionBuilder(constantPool, BindingScope.ROOT_SCOPE, 0, templateTypeName, null, null, templateName, directiveMatcher, directivesUsed, meta.pipes, pipesUsed, Identifiers$1.namespaceHTML, meta.relativeContextFilePath, meta.i18nUseExternalIds);
  17172. var templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
  17173. // We need to provide this so that dynamically generated components know what
  17174. // projected content blocks to pass through to the component when it is instantiated.
  17175. var ngContentSelectors = templateBuilder.getNgContentSelectors();
  17176. if (ngContentSelectors) {
  17177. definitionMap.set('ngContentSelectors', ngContentSelectors);
  17178. }
  17179. // e.g. `consts: 2`
  17180. definitionMap.set('consts', literal(templateBuilder.getConstCount()));
  17181. // e.g. `vars: 2`
  17182. definitionMap.set('vars', literal(templateBuilder.getVarCount()));
  17183. definitionMap.set('template', templateFunctionExpression);
  17184. // e.g. `directives: [MyDirective]`
  17185. if (directivesUsed.size) {
  17186. var directivesExpr = literalArr(Array.from(directivesUsed));
  17187. if (meta.wrapDirectivesAndPipesInClosure) {
  17188. directivesExpr = fn([], [new ReturnStatement(directivesExpr)]);
  17189. }
  17190. definitionMap.set('directives', directivesExpr);
  17191. }
  17192. // e.g. `pipes: [MyPipe]`
  17193. if (pipesUsed.size) {
  17194. var pipesExpr = literalArr(Array.from(pipesUsed));
  17195. if (meta.wrapDirectivesAndPipesInClosure) {
  17196. pipesExpr = fn([], [new ReturnStatement(pipesExpr)]);
  17197. }
  17198. definitionMap.set('pipes', pipesExpr);
  17199. }
  17200. if (meta.encapsulation === null) {
  17201. meta.encapsulation = ViewEncapsulation.Emulated;
  17202. }
  17203. // e.g. `styles: [str1, str2]`
  17204. if (meta.styles && meta.styles.length) {
  17205. var styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
  17206. compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
  17207. meta.styles;
  17208. var strings = styleValues.map(function (str) { return literal(str); });
  17209. definitionMap.set('styles', literalArr(strings));
  17210. }
  17211. else if (meta.encapsulation === ViewEncapsulation.Emulated) {
  17212. // If there is no style, don't generate css selectors on elements
  17213. meta.encapsulation = ViewEncapsulation.None;
  17214. }
  17215. // Only set view encapsulation if it's not the default value
  17216. if (meta.encapsulation !== ViewEncapsulation.Emulated) {
  17217. definitionMap.set('encapsulation', literal(meta.encapsulation));
  17218. }
  17219. // e.g. `animation: [trigger('123', [])]`
  17220. if (meta.animations !== null) {
  17221. definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
  17222. }
  17223. // Only set the change detection flag if it's defined and it's not the default.
  17224. if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
  17225. definitionMap.set('changeDetection', literal(changeDetection));
  17226. }
  17227. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  17228. // string literal, which must be on one line.
  17229. var selectorForType = (meta.selector || '').replace(/\n/g, '');
  17230. var expression = importExpr(Identifiers$1.defineComponent).callFn([definitionMap.toLiteralMap()]);
  17231. var type = createTypeForDef(meta, Identifiers$1.ComponentDefWithMeta);
  17232. return { expression: expression, type: type, statements: statements };
  17233. }
  17234. function prepareQueryParams(query, constantPool) {
  17235. var parameters = [
  17236. getQueryPredicate(query, constantPool),
  17237. literal(query.descendants),
  17238. query.read || literal(null),
  17239. ];
  17240. return parameters;
  17241. }
  17242. // Turn a directive selector into an R3-compatible selector for directive def
  17243. function createDirectiveSelector(selector) {
  17244. return asLiteral(parseSelectorToR3Selector(selector));
  17245. }
  17246. function convertAttributesToExpressions(attributes) {
  17247. var e_2, _a;
  17248. var values = [];
  17249. try {
  17250. for (var _b = __values(Object.getOwnPropertyNames(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) {
  17251. var key = _c.value;
  17252. var value = attributes[key];
  17253. values.push(literal(key), value);
  17254. }
  17255. }
  17256. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  17257. finally {
  17258. try {
  17259. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  17260. }
  17261. finally { if (e_2) throw e_2.error; }
  17262. }
  17263. return values;
  17264. }
  17265. // Define and update any content queries
  17266. function createContentQueriesFunction(queries, constantPool, name) {
  17267. var e_3, _a;
  17268. var createStatements = [];
  17269. var updateStatements = [];
  17270. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  17271. try {
  17272. for (var queries_1 = __values(queries), queries_1_1 = queries_1.next(); !queries_1_1.done; queries_1_1 = queries_1.next()) {
  17273. var query = queries_1_1.value;
  17274. // creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
  17275. var args = __spread([variable('dirIndex')], prepareQueryParams(query, constantPool));
  17276. var queryInstruction = query.static ? Identifiers$1.staticContentQuery : Identifiers$1.contentQuery;
  17277. createStatements.push(importExpr(queryInstruction).callFn(args).toStmt());
  17278. // update, e.g. (r3.queryRefresh(tmp = r3.loadContentQuery()) && (ctx.someDir = tmp));
  17279. var temporary = tempAllocator();
  17280. var getQueryList = importExpr(Identifiers$1.loadContentQuery).callFn([]);
  17281. var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  17282. var updateDirective = variable(CONTEXT_NAME)
  17283. .prop(query.propertyName)
  17284. .set(query.first ? temporary.prop('first') : temporary);
  17285. updateStatements.push(refresh.and(updateDirective).toStmt());
  17286. }
  17287. }
  17288. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  17289. finally {
  17290. try {
  17291. if (queries_1_1 && !queries_1_1.done && (_a = queries_1.return)) _a.call(queries_1);
  17292. }
  17293. finally { if (e_3) throw e_3.error; }
  17294. }
  17295. var contentQueriesFnName = name ? name + "_ContentQueries" : null;
  17296. return fn([
  17297. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  17298. new FnParam('dirIndex', null)
  17299. ], [
  17300. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  17301. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  17302. ], INFERRED_TYPE, null, contentQueriesFnName);
  17303. }
  17304. function stringAsType(str) {
  17305. return expressionType(literal(str));
  17306. }
  17307. function stringMapAsType(map) {
  17308. var mapValues = Object.keys(map).map(function (key) {
  17309. var value = Array.isArray(map[key]) ? map[key][0] : map[key];
  17310. return {
  17311. key: key,
  17312. value: literal(value),
  17313. quoted: true,
  17314. };
  17315. });
  17316. return expressionType(literalMap(mapValues));
  17317. }
  17318. function stringArrayAsType(arr) {
  17319. return arr.length > 0 ? expressionType(literalArr(arr.map(function (value) { return literal(value); }))) :
  17320. NONE_TYPE;
  17321. }
  17322. function createTypeForDef(meta, typeBase) {
  17323. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  17324. // string literal, which must be on one line.
  17325. var selectorForType = (meta.selector || '').replace(/\n/g, '');
  17326. return expressionType(importExpr(typeBase, [
  17327. typeWithParameters(meta.type, meta.typeArgumentCount),
  17328. stringAsType(selectorForType),
  17329. meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
  17330. stringMapAsType(meta.inputs),
  17331. stringMapAsType(meta.outputs),
  17332. stringArrayAsType(meta.queries.map(function (q) { return q.propertyName; })),
  17333. ]));
  17334. }
  17335. // Define and update any view queries
  17336. function createViewQueriesFunction(viewQueries, constantPool, name) {
  17337. var createStatements = [];
  17338. var updateStatements = [];
  17339. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  17340. viewQueries.forEach(function (query) {
  17341. var queryInstruction = query.static ? Identifiers$1.staticViewQuery : Identifiers$1.viewQuery;
  17342. // creation, e.g. r3.viewQuery(somePredicate, true);
  17343. var queryDefinition = importExpr(queryInstruction).callFn(prepareQueryParams(query, constantPool));
  17344. createStatements.push(queryDefinition.toStmt());
  17345. // update, e.g. (r3.queryRefresh(tmp = r3.loadViewQuery()) && (ctx.someDir = tmp));
  17346. var temporary = tempAllocator();
  17347. var getQueryList = importExpr(Identifiers$1.loadViewQuery).callFn([]);
  17348. var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  17349. var updateDirective = variable(CONTEXT_NAME)
  17350. .prop(query.propertyName)
  17351. .set(query.first ? temporary.prop('first') : temporary);
  17352. updateStatements.push(refresh.and(updateDirective).toStmt());
  17353. });
  17354. var viewQueryFnName = name ? name + "_Query" : null;
  17355. return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
  17356. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  17357. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  17358. ], INFERRED_TYPE, null, viewQueryFnName);
  17359. }
  17360. // Return a host binding function or null if one is not necessary.
  17361. function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name) {
  17362. // Initialize hostVarsCount to number of bound host properties (interpolations illegal),
  17363. // except 'style' and 'class' properties, since they should *not* allocate host var slots
  17364. var hostVarsCount = Object.keys(hostBindingsMetadata.properties)
  17365. .filter(function (name) {
  17366. var prefix = getStylingPrefix(name);
  17367. return prefix !== 'style' && prefix !== 'class';
  17368. })
  17369. .length;
  17370. var elVarExp = variable('elIndex');
  17371. var bindingContext = variable(CONTEXT_NAME);
  17372. var styleBuilder = new StylingBuilder(elVarExp, bindingContext);
  17373. var _a = hostBindingsMetadata.specialAttributes, styleAttr = _a.styleAttr, classAttr = _a.classAttr;
  17374. if (styleAttr !== undefined) {
  17375. styleBuilder.registerStyleAttr(styleAttr);
  17376. }
  17377. if (classAttr !== undefined) {
  17378. styleBuilder.registerClassAttr(classAttr);
  17379. }
  17380. var createStatements = [];
  17381. var updateStatements = [];
  17382. var totalHostVarsCount = hostVarsCount;
  17383. var hostBindingSourceSpan = typeSourceSpan;
  17384. var directiveSummary = metadataAsSummary(hostBindingsMetadata);
  17385. var valueConverter;
  17386. var getValueConverter = function () {
  17387. if (!valueConverter) {
  17388. var hostVarsCountFn = function (numSlots) {
  17389. var originalVarsCount = totalHostVarsCount;
  17390. totalHostVarsCount += numSlots;
  17391. return originalVarsCount;
  17392. };
  17393. valueConverter = new ValueConverter(constantPool, function () { return error('Unexpected node'); }, // new nodes are illegal here
  17394. hostVarsCountFn, function () { return error('Unexpected pipe'); }); // pipes are illegal here
  17395. }
  17396. return valueConverter;
  17397. };
  17398. // Calculate host event bindings
  17399. var eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
  17400. if (eventBindings && eventBindings.length) {
  17401. var listeners = createHostListeners(eventBindings, name);
  17402. createStatements.push.apply(createStatements, __spread(listeners));
  17403. }
  17404. // Calculate the host property bindings
  17405. var bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
  17406. (bindings || []).forEach(function (binding) {
  17407. var name = binding.name;
  17408. var stylingInputWasSet = styleBuilder.registerInputBasedOnName(name, binding.expression, binding.sourceSpan);
  17409. if (!stylingInputWasSet) {
  17410. // resolve literal arrays and literal objects
  17411. var value = binding.expression.visit(getValueConverter());
  17412. var bindingExpr = bindingFn(bindingContext, value);
  17413. var _a = getBindingNameAndInstruction(binding), bindingName = _a.bindingName, instruction = _a.instruction, isAttribute = _a.isAttribute;
  17414. var securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
  17415. .filter(function (context) { return context !== SecurityContext.NONE; });
  17416. var sanitizerFn = null;
  17417. if (securityContexts.length) {
  17418. if (securityContexts.length === 2 &&
  17419. securityContexts.indexOf(SecurityContext.URL) > -1 &&
  17420. securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
  17421. // Special case for some URL attributes (such as "src" and "href") that may be a part
  17422. // of different security contexts. In this case we use special santitization function and
  17423. // select the actual sanitizer at runtime based on a tag name that is provided while
  17424. // invoking sanitization function.
  17425. sanitizerFn = importExpr(Identifiers$1.sanitizeUrlOrResourceUrl);
  17426. }
  17427. else {
  17428. sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
  17429. }
  17430. }
  17431. var instructionParams = [literal(bindingName), bindingExpr.currValExpr];
  17432. if (sanitizerFn) {
  17433. instructionParams.push(sanitizerFn);
  17434. }
  17435. if (!isAttribute) {
  17436. if (!sanitizerFn) {
  17437. // append `null` in front of `nativeOnly` flag if no sanitizer fn defined
  17438. instructionParams.push(literal(null));
  17439. }
  17440. // host bindings must have nativeOnly prop set to true
  17441. instructionParams.push(literal(true));
  17442. }
  17443. updateStatements.push.apply(updateStatements, __spread(bindingExpr.stmts));
  17444. updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
  17445. }
  17446. });
  17447. // since we're dealing with directives/components and both have hostBinding
  17448. // functions, we need to generate a special hostAttrs instruction that deals
  17449. // with both the assignment of styling as well as static attributes to the host
  17450. // element. The instruction below will instruct all initial styling (styling
  17451. // that is inside of a host binding within a directive/component) to be attached
  17452. // to the host element alongside any of the provided host attributes that were
  17453. // collected earlier.
  17454. var hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
  17455. var hostInstruction = styleBuilder.buildHostAttrsInstruction(null, hostAttrs, constantPool);
  17456. if (hostInstruction) {
  17457. createStatements.push(createStylingStmt(hostInstruction, bindingContext, bindingFn));
  17458. }
  17459. if (styleBuilder.hasBindings) {
  17460. // singular style/class bindings (things like `[style.prop]` and `[class.name]`)
  17461. // MUST be registered on a given element within the component/directive
  17462. // templateFn/hostBindingsFn functions. The instruction below will figure out
  17463. // what all the bindings are and then generate the statements required to register
  17464. // those bindings to the element via `styling`.
  17465. var stylingInstruction = styleBuilder.buildStylingInstruction(null, constantPool);
  17466. if (stylingInstruction) {
  17467. createStatements.push(createStylingStmt(stylingInstruction, bindingContext, bindingFn));
  17468. }
  17469. // finally each binding that was registered in the statement above will need to be added to
  17470. // the update block of a component/directive templateFn/hostBindingsFn so that the bindings
  17471. // are evaluated and updated for the element.
  17472. styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(function (instruction) {
  17473. totalHostVarsCount += instruction.allocateBindingSlots;
  17474. updateStatements.push(createStylingStmt(instruction, bindingContext, bindingFn));
  17475. });
  17476. }
  17477. if (totalHostVarsCount) {
  17478. createStatements.unshift(importExpr(Identifiers$1.allocHostVars).callFn([literal(totalHostVarsCount)]).toStmt());
  17479. }
  17480. if (createStatements.length > 0 || updateStatements.length > 0) {
  17481. var hostBindingsFnName = name ? name + "_HostBindings" : null;
  17482. var statements = [];
  17483. if (createStatements.length > 0) {
  17484. statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
  17485. }
  17486. if (updateStatements.length > 0) {
  17487. statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
  17488. }
  17489. return fn([
  17490. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  17491. new FnParam(elVarExp.name, NUMBER_TYPE)
  17492. ], statements, INFERRED_TYPE, null, hostBindingsFnName);
  17493. }
  17494. return null;
  17495. }
  17496. function bindingFn(implicit, value) {
  17497. return convertPropertyBinding(null, implicit, value, 'b', BindingForm.TrySimple, function () { return error('Unexpected interpolation'); });
  17498. }
  17499. function createStylingStmt(instruction, bindingContext, bindingFn) {
  17500. var params = instruction.buildParams(function (value) { return bindingFn(bindingContext, value).currValExpr; });
  17501. return importExpr(instruction.reference, null, instruction.sourceSpan)
  17502. .callFn(params, instruction.sourceSpan)
  17503. .toStmt();
  17504. }
  17505. function getBindingNameAndInstruction(binding) {
  17506. var bindingName = binding.name;
  17507. var instruction;
  17508. // Check to see if this is an attr binding or a property binding
  17509. var attrMatches = bindingName.match(ATTR_REGEX);
  17510. if (attrMatches) {
  17511. bindingName = attrMatches[1];
  17512. instruction = Identifiers$1.attribute;
  17513. }
  17514. else {
  17515. if (binding.isAnimation) {
  17516. bindingName = prepareSyntheticPropertyName(bindingName);
  17517. // host bindings that have a synthetic property (e.g. @foo) should always be rendered
  17518. // in the context of the component and not the parent. Therefore there is a special
  17519. // compatibility instruction available for this purpose.
  17520. instruction = Identifiers$1.updateSyntheticHostBinding;
  17521. }
  17522. else {
  17523. instruction = Identifiers$1.property;
  17524. }
  17525. }
  17526. return { bindingName: bindingName, instruction: instruction, isAttribute: !!attrMatches };
  17527. }
  17528. function createHostListeners(eventBindings, name) {
  17529. return eventBindings.map(function (binding) {
  17530. var bindingName = binding.name && sanitizeIdentifier(binding.name);
  17531. var bindingFnName = binding.type === 1 /* Animation */ ?
  17532. prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
  17533. bindingName;
  17534. var handlerName = name && bindingName ? name + "_" + bindingFnName + "_HostBindingHandler" : null;
  17535. var params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
  17536. var instruction = binding.type == 1 /* Animation */ ? Identifiers$1.componentHostSyntheticListener : Identifiers$1.listener;
  17537. return importExpr(instruction).callFn(params).toStmt();
  17538. });
  17539. }
  17540. function metadataAsSummary(meta) {
  17541. // clang-format off
  17542. return {
  17543. // This is used by the BindingParser, which only deals with listeners and properties. There's no
  17544. // need to pass attributes to it.
  17545. hostAttributes: {},
  17546. hostListeners: meta.listeners,
  17547. hostProperties: meta.properties,
  17548. };
  17549. // clang-format on
  17550. }
  17551. var HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
  17552. function parseHostBindings(host) {
  17553. var e_4, _a;
  17554. var attributes = {};
  17555. var listeners = {};
  17556. var properties = {};
  17557. var specialAttributes = {};
  17558. try {
  17559. for (var _b = __values(Object.keys(host)), _c = _b.next(); !_c.done; _c = _b.next()) {
  17560. var key = _c.value;
  17561. var value = host[key];
  17562. var matches = key.match(HOST_REG_EXP$1);
  17563. if (matches === null) {
  17564. switch (key) {
  17565. case 'class':
  17566. if (typeof value !== 'string') {
  17567. // TODO(alxhub): make this a diagnostic.
  17568. throw new Error("Class binding must be string");
  17569. }
  17570. specialAttributes.classAttr = value;
  17571. break;
  17572. case 'style':
  17573. if (typeof value !== 'string') {
  17574. // TODO(alxhub): make this a diagnostic.
  17575. throw new Error("Style binding must be string");
  17576. }
  17577. specialAttributes.styleAttr = value;
  17578. break;
  17579. default:
  17580. if (typeof value === 'string') {
  17581. attributes[key] = literal(value);
  17582. }
  17583. else {
  17584. attributes[key] = value;
  17585. }
  17586. }
  17587. }
  17588. else if (matches[1 /* Binding */] != null) {
  17589. if (typeof value !== 'string') {
  17590. // TODO(alxhub): make this a diagnostic.
  17591. throw new Error("Property binding must be string");
  17592. }
  17593. // synthetic properties (the ones that have a `@` as a prefix)
  17594. // are still treated the same as regular properties. Therefore
  17595. // there is no point in storing them in a separate map.
  17596. properties[matches[1 /* Binding */]] = value;
  17597. }
  17598. else if (matches[2 /* Event */] != null) {
  17599. if (typeof value !== 'string') {
  17600. // TODO(alxhub): make this a diagnostic.
  17601. throw new Error("Event binding must be string");
  17602. }
  17603. listeners[matches[2 /* Event */]] = value;
  17604. }
  17605. }
  17606. }
  17607. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  17608. finally {
  17609. try {
  17610. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  17611. }
  17612. finally { if (e_4) throw e_4.error; }
  17613. }
  17614. return { attributes: attributes, listeners: listeners, properties: properties, specialAttributes: specialAttributes };
  17615. }
  17616. /**
  17617. * Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
  17618. * given set of host bindings has no errors.
  17619. *
  17620. * @param bindings set of host bindings to verify.
  17621. * @param sourceSpan source span where host bindings were defined.
  17622. * @returns array of errors associated with a given set of host bindings.
  17623. */
  17624. function verifyHostBindings(bindings, sourceSpan) {
  17625. var summary = metadataAsSummary(bindings);
  17626. // TODO: abstract out host bindings verification logic and use it instead of
  17627. // creating events and properties ASTs to detect errors (FW-996)
  17628. var bindingParser = makeBindingParser();
  17629. bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
  17630. bindingParser.createBoundHostProperties(summary, sourceSpan);
  17631. return bindingParser.errors;
  17632. }
  17633. function compileStyles(styles, selector, hostSelector) {
  17634. var shadowCss = new ShadowCss();
  17635. return styles.map(function (style) { return shadowCss.shimCssText(style, selector, hostSelector); });
  17636. }
  17637. /**
  17638. * @license
  17639. * Copyright Google Inc. All Rights Reserved.
  17640. *
  17641. * Use of this source code is governed by an MIT-style license that can be
  17642. * found in the LICENSE file at https://angular.io/license
  17643. */
  17644. /**
  17645. * An interface for retrieving documents by URL that the compiler uses
  17646. * to load templates.
  17647. */
  17648. var ResourceLoader = /** @class */ (function () {
  17649. function ResourceLoader() {
  17650. }
  17651. ResourceLoader.prototype.get = function (url) { return ''; };
  17652. return ResourceLoader;
  17653. }());
  17654. /**
  17655. * @license
  17656. * Copyright Google Inc. All Rights Reserved.
  17657. *
  17658. * Use of this source code is governed by an MIT-style license that can be
  17659. * found in the LICENSE file at https://angular.io/license
  17660. */
  17661. var CompilerFacadeImpl = /** @class */ (function () {
  17662. function CompilerFacadeImpl(jitEvaluator) {
  17663. if (jitEvaluator === void 0) { jitEvaluator = new JitEvaluator(); }
  17664. this.jitEvaluator = jitEvaluator;
  17665. this.R3ResolvedDependencyType = R3ResolvedDependencyType;
  17666. this.ResourceLoader = ResourceLoader;
  17667. this.elementSchemaRegistry = new DomElementSchemaRegistry();
  17668. }
  17669. CompilerFacadeImpl.prototype.compilePipe = function (angularCoreEnv, sourceMapUrl, facade) {
  17670. var res = compilePipeFromMetadata({
  17671. name: facade.name,
  17672. type: new WrappedNodeExpr(facade.type),
  17673. typeArgumentCount: facade.typeArgumentCount,
  17674. deps: convertR3DependencyMetadataArray(facade.deps),
  17675. pipeName: facade.pipeName,
  17676. pure: facade.pure,
  17677. });
  17678. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  17679. };
  17680. CompilerFacadeImpl.prototype.compileInjectable = function (angularCoreEnv, sourceMapUrl, facade) {
  17681. var _a = compileInjectable({
  17682. name: facade.name,
  17683. type: new WrappedNodeExpr(facade.type),
  17684. typeArgumentCount: facade.typeArgumentCount,
  17685. providedIn: computeProvidedIn(facade.providedIn),
  17686. useClass: wrapExpression(facade, USE_CLASS),
  17687. useFactory: wrapExpression(facade, USE_FACTORY),
  17688. useValue: wrapExpression(facade, USE_VALUE),
  17689. useExisting: wrapExpression(facade, USE_EXISTING),
  17690. ctorDeps: convertR3DependencyMetadataArray(facade.ctorDeps),
  17691. userDeps: convertR3DependencyMetadataArray(facade.userDeps) || undefined,
  17692. }), expression = _a.expression, statements = _a.statements;
  17693. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
  17694. };
  17695. CompilerFacadeImpl.prototype.compileInjector = function (angularCoreEnv, sourceMapUrl, facade) {
  17696. var meta = {
  17697. name: facade.name,
  17698. type: new WrappedNodeExpr(facade.type),
  17699. deps: convertR3DependencyMetadataArray(facade.deps),
  17700. providers: new WrappedNodeExpr(facade.providers),
  17701. imports: facade.imports.map(function (i) { return new WrappedNodeExpr(i); }),
  17702. };
  17703. var res = compileInjector(meta);
  17704. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  17705. };
  17706. CompilerFacadeImpl.prototype.compileNgModule = function (angularCoreEnv, sourceMapUrl, facade) {
  17707. var meta = {
  17708. type: new WrappedNodeExpr(facade.type),
  17709. bootstrap: facade.bootstrap.map(wrapReference),
  17710. declarations: facade.declarations.map(wrapReference),
  17711. imports: facade.imports.map(wrapReference),
  17712. exports: facade.exports.map(wrapReference),
  17713. emitInline: true,
  17714. containsForwardDecls: false,
  17715. schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
  17716. id: facade.id ? new WrappedNodeExpr(facade.id) : null,
  17717. };
  17718. var res = compileNgModule(meta);
  17719. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  17720. };
  17721. CompilerFacadeImpl.prototype.compileDirective = function (angularCoreEnv, sourceMapUrl, facade) {
  17722. var constantPool = new ConstantPool();
  17723. var bindingParser = makeBindingParser();
  17724. var meta = convertDirectiveFacadeToMetadata(facade);
  17725. var res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
  17726. var preStatements = __spread(constantPool.statements, res.statements);
  17727. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, preStatements);
  17728. };
  17729. CompilerFacadeImpl.prototype.compileComponent = function (angularCoreEnv, sourceMapUrl, facade) {
  17730. // The ConstantPool is a requirement of the JIT'er.
  17731. var constantPool = new ConstantPool();
  17732. var interpolationConfig = facade.interpolation ?
  17733. InterpolationConfig.fromArray(facade.interpolation) :
  17734. DEFAULT_INTERPOLATION_CONFIG;
  17735. // Parse the template and check for errors.
  17736. var template = parseTemplate(facade.template, sourceMapUrl, { preserveWhitespaces: facade.preserveWhitespaces, interpolationConfig: interpolationConfig });
  17737. if (template.errors !== undefined) {
  17738. var errors = template.errors.map(function (err) { return err.toString(); }).join(', ');
  17739. throw new Error("Errors during JIT compilation of template for " + facade.name + ": " + errors);
  17740. }
  17741. // Compile the component metadata, including template, into an expression.
  17742. // TODO(alxhub): implement inputs, outputs, queries, etc.
  17743. var res = compileComponentFromMetadata(__assign({}, facade, convertDirectiveFacadeToMetadata(facade), { selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(), template: template, wrapDirectivesAndPipesInClosure: false, styles: facade.styles || [], encapsulation: facade.encapsulation, interpolation: interpolationConfig, changeDetection: facade.changeDetection, animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null, viewProviders: facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) :
  17744. null, relativeContextFilePath: '', i18nUseExternalIds: true }), constantPool, makeBindingParser(interpolationConfig));
  17745. var preStatements = __spread(constantPool.statements, res.statements);
  17746. return this.jitExpression(res.expression, angularCoreEnv, "ng:///" + facade.name + ".js", preStatements);
  17747. };
  17748. CompilerFacadeImpl.prototype.compileBase = function (angularCoreEnv, sourceMapUrl, facade) {
  17749. var constantPool = new ConstantPool();
  17750. var typeSourceSpan = this.createParseSourceSpan('Base', facade.name, "ng:///" + facade.name + ".js");
  17751. var meta = __assign({}, facade, { typeSourceSpan: typeSourceSpan, viewQueries: facade.viewQueries ? facade.viewQueries.map(convertToR3QueryMetadata) :
  17752. facade.viewQueries, queries: facade.queries ? facade.queries.map(convertToR3QueryMetadata) : facade.queries, host: extractHostBindings(facade.propMetadata, typeSourceSpan) });
  17753. var res = compileBaseDefFromMetadata(meta, constantPool, makeBindingParser());
  17754. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
  17755. };
  17756. CompilerFacadeImpl.prototype.createParseSourceSpan = function (kind, typeName, sourceUrl) {
  17757. return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
  17758. };
  17759. /**
  17760. * JIT compiles an expression and returns the result of executing that expression.
  17761. *
  17762. * @param def the definition which will be compiled and executed to get the value to patch
  17763. * @param context an object map of @angular/core symbol names to symbols which will be available
  17764. * in the context of the compiled expression
  17765. * @param sourceUrl a URL to use for the source map of the compiled expression
  17766. * @param preStatements a collection of statements that should be evaluated before the expression.
  17767. */
  17768. CompilerFacadeImpl.prototype.jitExpression = function (def, context, sourceUrl, preStatements) {
  17769. // The ConstantPool may contain Statements which declare variables used in the final expression.
  17770. // Therefore, its statements need to precede the actual JIT operation. The final statement is a
  17771. // declaration of $def which is set to the expression being compiled.
  17772. var statements = __spread(preStatements, [
  17773. new DeclareVarStmt('$def', def, undefined, [StmtModifier.Exported]),
  17774. ]);
  17775. var res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
  17776. return res['$def'];
  17777. };
  17778. return CompilerFacadeImpl;
  17779. }());
  17780. var USE_CLASS = Object.keys({ useClass: null })[0];
  17781. var USE_FACTORY = Object.keys({ useFactory: null })[0];
  17782. var USE_VALUE = Object.keys({ useValue: null })[0];
  17783. var USE_EXISTING = Object.keys({ useExisting: null })[0];
  17784. var wrapReference = function (value) {
  17785. var wrapped = new WrappedNodeExpr(value);
  17786. return { value: wrapped, type: wrapped };
  17787. };
  17788. function convertToR3QueryMetadata(facade) {
  17789. return __assign({}, facade, { predicate: Array.isArray(facade.predicate) ? facade.predicate :
  17790. new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static });
  17791. }
  17792. function convertDirectiveFacadeToMetadata(facade) {
  17793. var inputsFromMetadata = parseInputOutputs(facade.inputs || []);
  17794. var outputsFromMetadata = parseInputOutputs(facade.outputs || []);
  17795. var propMetadata = facade.propMetadata;
  17796. var inputsFromType = {};
  17797. var outputsFromType = {};
  17798. var _loop_1 = function (field) {
  17799. if (propMetadata.hasOwnProperty(field)) {
  17800. propMetadata[field].forEach(function (ann) {
  17801. if (isInput(ann)) {
  17802. inputsFromType[field] =
  17803. ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
  17804. }
  17805. else if (isOutput(ann)) {
  17806. outputsFromType[field] = ann.bindingPropertyName || field;
  17807. }
  17808. });
  17809. }
  17810. };
  17811. for (var field in propMetadata) {
  17812. _loop_1(field);
  17813. }
  17814. return __assign({}, facade, { typeSourceSpan: facade.typeSourceSpan, type: new WrappedNodeExpr(facade.type), deps: convertR3DependencyMetadataArray(facade.deps), host: extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host), inputs: __assign({}, inputsFromMetadata, inputsFromType), outputs: __assign({}, outputsFromMetadata, outputsFromType), queries: facade.queries.map(convertToR3QueryMetadata), providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null, viewQueries: facade.viewQueries.map(convertToR3QueryMetadata) });
  17815. }
  17816. function wrapExpression(obj, property) {
  17817. if (obj.hasOwnProperty(property)) {
  17818. return new WrappedNodeExpr(obj[property]);
  17819. }
  17820. else {
  17821. return undefined;
  17822. }
  17823. }
  17824. function computeProvidedIn(providedIn) {
  17825. if (providedIn == null || typeof providedIn === 'string') {
  17826. return new LiteralExpr(providedIn);
  17827. }
  17828. else {
  17829. return new WrappedNodeExpr(providedIn);
  17830. }
  17831. }
  17832. function convertR3DependencyMetadata(facade) {
  17833. var tokenExpr;
  17834. if (facade.token === null) {
  17835. tokenExpr = new LiteralExpr(null);
  17836. }
  17837. else if (facade.resolved === R3ResolvedDependencyType.Attribute) {
  17838. tokenExpr = new LiteralExpr(facade.token);
  17839. }
  17840. else {
  17841. tokenExpr = new WrappedNodeExpr(facade.token);
  17842. }
  17843. return {
  17844. token: tokenExpr,
  17845. resolved: facade.resolved,
  17846. host: facade.host,
  17847. optional: facade.optional,
  17848. self: facade.self,
  17849. skipSelf: facade.skipSelf
  17850. };
  17851. }
  17852. function convertR3DependencyMetadataArray(facades) {
  17853. return facades == null ? null : facades.map(convertR3DependencyMetadata);
  17854. }
  17855. function extractHostBindings(propMetadata, sourceSpan, host) {
  17856. // First parse the declarations from the metadata.
  17857. var bindings = parseHostBindings(host || {});
  17858. // After that check host bindings for errors
  17859. var errors = verifyHostBindings(bindings, sourceSpan);
  17860. if (errors.length) {
  17861. throw new Error(errors.map(function (error) { return error.msg; }).join('\n'));
  17862. }
  17863. var _loop_2 = function (field) {
  17864. if (propMetadata.hasOwnProperty(field)) {
  17865. propMetadata[field].forEach(function (ann) {
  17866. if (isHostBinding(ann)) {
  17867. bindings.properties[ann.hostPropertyName || field] = field;
  17868. }
  17869. else if (isHostListener(ann)) {
  17870. bindings.listeners[ann.eventName || field] = field + "(" + (ann.args || []).join(',') + ")";
  17871. }
  17872. });
  17873. }
  17874. };
  17875. // Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
  17876. for (var field in propMetadata) {
  17877. _loop_2(field);
  17878. }
  17879. return bindings;
  17880. }
  17881. function isHostBinding(value) {
  17882. return value.ngMetadataName === 'HostBinding';
  17883. }
  17884. function isHostListener(value) {
  17885. return value.ngMetadataName === 'HostListener';
  17886. }
  17887. function isInput(value) {
  17888. return value.ngMetadataName === 'Input';
  17889. }
  17890. function isOutput(value) {
  17891. return value.ngMetadataName === 'Output';
  17892. }
  17893. function parseInputOutputs(values) {
  17894. return values.reduce(function (map, value) {
  17895. var _a = __read(value.split(',').map(function (piece) { return piece.trim(); }), 2), field = _a[0], property = _a[1];
  17896. map[field] = property || field;
  17897. return map;
  17898. }, {});
  17899. }
  17900. function publishFacade(global) {
  17901. var ng = global.ng || (global.ng = {});
  17902. ng.ɵcompilerFacade = new CompilerFacadeImpl();
  17903. }
  17904. /**
  17905. * @license
  17906. * Copyright Google Inc. All Rights Reserved.
  17907. *
  17908. * Use of this source code is governed by an MIT-style license that can be
  17909. * found in the LICENSE file at https://angular.io/license
  17910. */
  17911. var VERSION$1 = new Version('8.1.3');
  17912. /**
  17913. * @license
  17914. * Copyright Google Inc. All Rights Reserved.
  17915. *
  17916. * Use of this source code is governed by an MIT-style license that can be
  17917. * found in the LICENSE file at https://angular.io/license
  17918. */
  17919. var CompilerConfig = /** @class */ (function () {
  17920. function CompilerConfig(_a) {
  17921. var _b = _a === void 0 ? {} : _a, _c = _b.defaultEncapsulation, defaultEncapsulation = _c === void 0 ? ViewEncapsulation.Emulated : _c, _d = _b.useJit, useJit = _d === void 0 ? true : _d, _e = _b.jitDevMode, jitDevMode = _e === void 0 ? false : _e, _f = _b.missingTranslation, missingTranslation = _f === void 0 ? null : _f, preserveWhitespaces = _b.preserveWhitespaces, strictInjectionParameters = _b.strictInjectionParameters;
  17922. this.defaultEncapsulation = defaultEncapsulation;
  17923. this.useJit = !!useJit;
  17924. this.jitDevMode = !!jitDevMode;
  17925. this.missingTranslation = missingTranslation;
  17926. this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
  17927. this.strictInjectionParameters = strictInjectionParameters === true;
  17928. }
  17929. return CompilerConfig;
  17930. }());
  17931. function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting) {
  17932. if (defaultSetting === void 0) { defaultSetting = false; }
  17933. return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
  17934. }
  17935. /**
  17936. * @license
  17937. * Copyright Google Inc. All Rights Reserved.
  17938. *
  17939. * Use of this source code is governed by an MIT-style license that can be
  17940. * found in the LICENSE file at https://angular.io/license
  17941. */
  17942. var DirectiveNormalizer = /** @class */ (function () {
  17943. function DirectiveNormalizer(_resourceLoader, _urlResolver, _htmlParser, _config) {
  17944. this._resourceLoader = _resourceLoader;
  17945. this._urlResolver = _urlResolver;
  17946. this._htmlParser = _htmlParser;
  17947. this._config = _config;
  17948. this._resourceLoaderCache = new Map();
  17949. }
  17950. DirectiveNormalizer.prototype.clearCache = function () { this._resourceLoaderCache.clear(); };
  17951. DirectiveNormalizer.prototype.clearCacheFor = function (normalizedDirective) {
  17952. var _this = this;
  17953. if (!normalizedDirective.isComponent) {
  17954. return;
  17955. }
  17956. var template = normalizedDirective.template;
  17957. this._resourceLoaderCache.delete(template.templateUrl);
  17958. template.externalStylesheets.forEach(function (stylesheet) { _this._resourceLoaderCache.delete(stylesheet.moduleUrl); });
  17959. };
  17960. DirectiveNormalizer.prototype._fetch = function (url) {
  17961. var result = this._resourceLoaderCache.get(url);
  17962. if (!result) {
  17963. result = this._resourceLoader.get(url);
  17964. this._resourceLoaderCache.set(url, result);
  17965. }
  17966. return result;
  17967. };
  17968. DirectiveNormalizer.prototype.normalizeTemplate = function (prenormData) {
  17969. var _this = this;
  17970. if (isDefined(prenormData.template)) {
  17971. if (isDefined(prenormData.templateUrl)) {
  17972. throw syntaxError("'" + stringify(prenormData.componentType) + "' component cannot define both template and templateUrl");
  17973. }
  17974. if (typeof prenormData.template !== 'string') {
  17975. throw syntaxError("The template specified for component " + stringify(prenormData.componentType) + " is not a string");
  17976. }
  17977. }
  17978. else if (isDefined(prenormData.templateUrl)) {
  17979. if (typeof prenormData.templateUrl !== 'string') {
  17980. throw syntaxError("The templateUrl specified for component " + stringify(prenormData.componentType) + " is not a string");
  17981. }
  17982. }
  17983. else {
  17984. throw syntaxError("No template specified for component " + stringify(prenormData.componentType));
  17985. }
  17986. if (isDefined(prenormData.preserveWhitespaces) &&
  17987. typeof prenormData.preserveWhitespaces !== 'boolean') {
  17988. throw syntaxError("The preserveWhitespaces option for component " + stringify(prenormData.componentType) + " must be a boolean");
  17989. }
  17990. return SyncAsync.then(this._preParseTemplate(prenormData), function (preparsedTemplate) { return _this._normalizeTemplateMetadata(prenormData, preparsedTemplate); });
  17991. };
  17992. DirectiveNormalizer.prototype._preParseTemplate = function (prenomData) {
  17993. var _this = this;
  17994. var template;
  17995. var templateUrl;
  17996. if (prenomData.template != null) {
  17997. template = prenomData.template;
  17998. templateUrl = prenomData.moduleUrl;
  17999. }
  18000. else {
  18001. templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
  18002. template = this._fetch(templateUrl);
  18003. }
  18004. return SyncAsync.then(template, function (template) { return _this._preparseLoadedTemplate(prenomData, template, templateUrl); });
  18005. };
  18006. DirectiveNormalizer.prototype._preparseLoadedTemplate = function (prenormData, template, templateAbsUrl) {
  18007. var isInline = !!prenormData.template;
  18008. var interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
  18009. var templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline: isInline, templateUrl: templateAbsUrl });
  18010. var rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  18011. if (rootNodesAndErrors.errors.length > 0) {
  18012. var errorString = rootNodesAndErrors.errors.join('\n');
  18013. throw syntaxError("Template parse errors:\n" + errorString);
  18014. }
  18015. var templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
  18016. var visitor = new TemplatePreparseVisitor();
  18017. visitAll$1(visitor, rootNodesAndErrors.rootNodes);
  18018. var templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
  18019. var styles = templateMetadataStyles.styles.concat(templateStyles.styles);
  18020. var inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
  18021. var styleUrls = this
  18022. ._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
  18023. .styleUrls;
  18024. return {
  18025. template: template,
  18026. templateUrl: templateAbsUrl, isInline: isInline,
  18027. htmlAst: rootNodesAndErrors, styles: styles, inlineStyleUrls: inlineStyleUrls, styleUrls: styleUrls,
  18028. ngContentSelectors: visitor.ngContentSelectors,
  18029. };
  18030. };
  18031. DirectiveNormalizer.prototype._normalizeTemplateMetadata = function (prenormData, preparsedTemplate) {
  18032. var _this = this;
  18033. return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), function (externalStylesheets) { return _this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets); });
  18034. };
  18035. DirectiveNormalizer.prototype._normalizeLoadedTemplateMetadata = function (prenormData, preparsedTemplate, stylesheets) {
  18036. // Algorithm:
  18037. // - produce exactly 1 entry per original styleUrl in
  18038. // CompileTemplateMetadata.externalStylesheets with all styles inlined
  18039. // - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
  18040. // Reason: be able to determine how many stylesheets there are even without loading
  18041. // the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
  18042. // (as resource loading may be async)
  18043. var _this = this;
  18044. var styles = __spread(preparsedTemplate.styles);
  18045. this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
  18046. var styleUrls = preparsedTemplate.styleUrls;
  18047. var externalStylesheets = styleUrls.map(function (styleUrl) {
  18048. var stylesheet = stylesheets.get(styleUrl);
  18049. var styles = __spread(stylesheet.styles);
  18050. _this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
  18051. return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
  18052. });
  18053. var encapsulation = prenormData.encapsulation;
  18054. if (encapsulation == null) {
  18055. encapsulation = this._config.defaultEncapsulation;
  18056. }
  18057. if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
  18058. styleUrls.length === 0) {
  18059. encapsulation = ViewEncapsulation.None;
  18060. }
  18061. return new CompileTemplateMetadata({
  18062. encapsulation: encapsulation,
  18063. template: preparsedTemplate.template,
  18064. templateUrl: preparsedTemplate.templateUrl,
  18065. htmlAst: preparsedTemplate.htmlAst, styles: styles, styleUrls: styleUrls,
  18066. ngContentSelectors: preparsedTemplate.ngContentSelectors,
  18067. animations: prenormData.animations,
  18068. interpolation: prenormData.interpolation,
  18069. isInline: preparsedTemplate.isInline, externalStylesheets: externalStylesheets,
  18070. preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
  18071. });
  18072. };
  18073. DirectiveNormalizer.prototype._inlineStyles = function (styleUrls, stylesheets, targetStyles) {
  18074. var _this = this;
  18075. styleUrls.forEach(function (styleUrl) {
  18076. var stylesheet = stylesheets.get(styleUrl);
  18077. stylesheet.styles.forEach(function (style) { return targetStyles.push(style); });
  18078. _this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
  18079. });
  18080. };
  18081. DirectiveNormalizer.prototype._loadMissingExternalStylesheets = function (styleUrls, loadedStylesheets) {
  18082. var _this = this;
  18083. if (loadedStylesheets === void 0) { loadedStylesheets = new Map(); }
  18084. return SyncAsync.then(SyncAsync.all(styleUrls.filter(function (styleUrl) { return !loadedStylesheets.has(styleUrl); })
  18085. .map(function (styleUrl) { return SyncAsync.then(_this._fetch(styleUrl), function (loadedStyle) {
  18086. var stylesheet = _this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
  18087. loadedStylesheets.set(styleUrl, stylesheet);
  18088. return _this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
  18089. }); })), function (_) { return loadedStylesheets; });
  18090. };
  18091. DirectiveNormalizer.prototype._normalizeStylesheet = function (stylesheet) {
  18092. var _this = this;
  18093. var moduleUrl = stylesheet.moduleUrl;
  18094. var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
  18095. .map(function (url) { return _this._urlResolver.resolve(moduleUrl, url); });
  18096. var allStyles = stylesheet.styles.map(function (style) {
  18097. var styleWithImports = extractStyleUrls(_this._urlResolver, moduleUrl, style);
  18098. allStyleUrls.push.apply(allStyleUrls, __spread(styleWithImports.styleUrls));
  18099. return styleWithImports.style;
  18100. });
  18101. return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
  18102. };
  18103. return DirectiveNormalizer;
  18104. }());
  18105. var TemplatePreparseVisitor = /** @class */ (function () {
  18106. function TemplatePreparseVisitor() {
  18107. this.ngContentSelectors = [];
  18108. this.styles = [];
  18109. this.styleUrls = [];
  18110. this.ngNonBindableStackCount = 0;
  18111. }
  18112. TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
  18113. var preparsedElement = preparseElement(ast);
  18114. switch (preparsedElement.type) {
  18115. case PreparsedElementType.NG_CONTENT:
  18116. if (this.ngNonBindableStackCount === 0) {
  18117. this.ngContentSelectors.push(preparsedElement.selectAttr);
  18118. }
  18119. break;
  18120. case PreparsedElementType.STYLE:
  18121. var textContent_1 = '';
  18122. ast.children.forEach(function (child) {
  18123. if (child instanceof Text$3) {
  18124. textContent_1 += child.value;
  18125. }
  18126. });
  18127. this.styles.push(textContent_1);
  18128. break;
  18129. case PreparsedElementType.STYLESHEET:
  18130. this.styleUrls.push(preparsedElement.hrefAttr);
  18131. break;
  18132. default:
  18133. break;
  18134. }
  18135. if (preparsedElement.nonBindable) {
  18136. this.ngNonBindableStackCount++;
  18137. }
  18138. visitAll$1(this, ast.children);
  18139. if (preparsedElement.nonBindable) {
  18140. this.ngNonBindableStackCount--;
  18141. }
  18142. return null;
  18143. };
  18144. TemplatePreparseVisitor.prototype.visitExpansion = function (ast, context) { visitAll$1(this, ast.cases); };
  18145. TemplatePreparseVisitor.prototype.visitExpansionCase = function (ast, context) {
  18146. visitAll$1(this, ast.expression);
  18147. };
  18148. TemplatePreparseVisitor.prototype.visitComment = function (ast, context) { return null; };
  18149. TemplatePreparseVisitor.prototype.visitAttribute = function (ast, context) { return null; };
  18150. TemplatePreparseVisitor.prototype.visitText = function (ast, context) { return null; };
  18151. return TemplatePreparseVisitor;
  18152. }());
  18153. /**
  18154. * @license
  18155. * Copyright Google Inc. All Rights Reserved.
  18156. *
  18157. * Use of this source code is governed by an MIT-style license that can be
  18158. * found in the LICENSE file at https://angular.io/license
  18159. */
  18160. var QUERY_METADATA_IDENTIFIERS = [
  18161. createViewChild,
  18162. createViewChildren,
  18163. createContentChild,
  18164. createContentChildren,
  18165. ];
  18166. /*
  18167. * Resolve a `Type` for {@link Directive}.
  18168. *
  18169. * This interface can be overridden by the application developer to create custom behavior.
  18170. *
  18171. * See {@link Compiler}
  18172. */
  18173. var DirectiveResolver = /** @class */ (function () {
  18174. function DirectiveResolver(_reflector) {
  18175. this._reflector = _reflector;
  18176. }
  18177. DirectiveResolver.prototype.isDirective = function (type) {
  18178. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  18179. return typeMetadata && typeMetadata.some(isDirectiveMetadata);
  18180. };
  18181. DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) {
  18182. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  18183. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  18184. if (typeMetadata) {
  18185. var metadata = findLast(typeMetadata, isDirectiveMetadata);
  18186. if (metadata) {
  18187. var propertyMetadata = this._reflector.propMetadata(type);
  18188. var guards = this._reflector.guards(type);
  18189. return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
  18190. }
  18191. }
  18192. if (throwIfNotFound) {
  18193. throw new Error("No Directive annotation found on " + stringify(type));
  18194. }
  18195. return null;
  18196. };
  18197. DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata, guards, directiveType) {
  18198. var inputs = [];
  18199. var outputs = [];
  18200. var host = {};
  18201. var queries = {};
  18202. Object.keys(propertyMetadata).forEach(function (propName) {
  18203. var input = findLast(propertyMetadata[propName], function (a) { return createInput.isTypeOf(a); });
  18204. if (input) {
  18205. if (input.bindingPropertyName) {
  18206. inputs.push(propName + ": " + input.bindingPropertyName);
  18207. }
  18208. else {
  18209. inputs.push(propName);
  18210. }
  18211. }
  18212. var output = findLast(propertyMetadata[propName], function (a) { return createOutput.isTypeOf(a); });
  18213. if (output) {
  18214. if (output.bindingPropertyName) {
  18215. outputs.push(propName + ": " + output.bindingPropertyName);
  18216. }
  18217. else {
  18218. outputs.push(propName);
  18219. }
  18220. }
  18221. var hostBindings = propertyMetadata[propName].filter(function (a) { return createHostBinding.isTypeOf(a); });
  18222. hostBindings.forEach(function (hostBinding) {
  18223. if (hostBinding.hostPropertyName) {
  18224. var startWith = hostBinding.hostPropertyName[0];
  18225. if (startWith === '(') {
  18226. throw new Error("@HostBinding can not bind to events. Use @HostListener instead.");
  18227. }
  18228. else if (startWith === '[') {
  18229. throw new Error("@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.");
  18230. }
  18231. host["[" + hostBinding.hostPropertyName + "]"] = propName;
  18232. }
  18233. else {
  18234. host["[" + propName + "]"] = propName;
  18235. }
  18236. });
  18237. var hostListeners = propertyMetadata[propName].filter(function (a) { return createHostListener.isTypeOf(a); });
  18238. hostListeners.forEach(function (hostListener) {
  18239. var args = hostListener.args || [];
  18240. host["(" + hostListener.eventName + ")"] = propName + "(" + args.join(',') + ")";
  18241. });
  18242. var query = findLast(propertyMetadata[propName], function (a) { return QUERY_METADATA_IDENTIFIERS.some(function (i) { return i.isTypeOf(a); }); });
  18243. if (query) {
  18244. queries[propName] = query;
  18245. }
  18246. });
  18247. return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
  18248. };
  18249. DirectiveResolver.prototype._extractPublicName = function (def) { return splitAtColon(def, [null, def])[1].trim(); };
  18250. DirectiveResolver.prototype._dedupeBindings = function (bindings) {
  18251. var names = new Set();
  18252. var publicNames = new Set();
  18253. var reversedResult = [];
  18254. // go last to first to allow later entries to overwrite previous entries
  18255. for (var i = bindings.length - 1; i >= 0; i--) {
  18256. var binding = bindings[i];
  18257. var name_1 = this._extractPublicName(binding);
  18258. publicNames.add(name_1);
  18259. if (!names.has(name_1)) {
  18260. names.add(name_1);
  18261. reversedResult.push(binding);
  18262. }
  18263. }
  18264. return reversedResult.reverse();
  18265. };
  18266. DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, guards, directiveType) {
  18267. var mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
  18268. var mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
  18269. var mergedHost = directive.host ? __assign({}, directive.host, host) : host;
  18270. var mergedQueries = directive.queries ? __assign({}, directive.queries, queries) : queries;
  18271. if (createComponent.isTypeOf(directive)) {
  18272. var comp = directive;
  18273. return createComponent({
  18274. selector: comp.selector,
  18275. inputs: mergedInputs,
  18276. outputs: mergedOutputs,
  18277. host: mergedHost,
  18278. exportAs: comp.exportAs,
  18279. moduleId: comp.moduleId,
  18280. queries: mergedQueries,
  18281. changeDetection: comp.changeDetection,
  18282. providers: comp.providers,
  18283. viewProviders: comp.viewProviders,
  18284. entryComponents: comp.entryComponents,
  18285. template: comp.template,
  18286. templateUrl: comp.templateUrl,
  18287. styles: comp.styles,
  18288. styleUrls: comp.styleUrls,
  18289. encapsulation: comp.encapsulation,
  18290. animations: comp.animations,
  18291. interpolation: comp.interpolation,
  18292. preserveWhitespaces: directive.preserveWhitespaces,
  18293. });
  18294. }
  18295. else {
  18296. return createDirective({
  18297. selector: directive.selector,
  18298. inputs: mergedInputs,
  18299. outputs: mergedOutputs,
  18300. host: mergedHost,
  18301. exportAs: directive.exportAs,
  18302. queries: mergedQueries,
  18303. providers: directive.providers, guards: guards
  18304. });
  18305. }
  18306. };
  18307. return DirectiveResolver;
  18308. }());
  18309. function isDirectiveMetadata(type) {
  18310. return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
  18311. }
  18312. function findLast(arr, condition) {
  18313. for (var i = arr.length - 1; i >= 0; i--) {
  18314. if (condition(arr[i])) {
  18315. return arr[i];
  18316. }
  18317. }
  18318. return null;
  18319. }
  18320. /**
  18321. * @license
  18322. * Copyright Google Inc. All Rights Reserved.
  18323. *
  18324. * Use of this source code is governed by an MIT-style license that can be
  18325. * found in the LICENSE file at https://angular.io/license
  18326. */
  18327. /**
  18328. * An i18n error.
  18329. */
  18330. var I18nError = /** @class */ (function (_super) {
  18331. __extends(I18nError, _super);
  18332. function I18nError(span, msg) {
  18333. return _super.call(this, span, msg) || this;
  18334. }
  18335. return I18nError;
  18336. }(ParseError));
  18337. /**
  18338. * @license
  18339. * Copyright Google Inc. All Rights Reserved.
  18340. *
  18341. * Use of this source code is governed by an MIT-style license that can be
  18342. * found in the LICENSE file at https://angular.io/license
  18343. */
  18344. var _I18N_ATTR = 'i18n';
  18345. var _I18N_ATTR_PREFIX = 'i18n-';
  18346. var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
  18347. var MEANING_SEPARATOR = '|';
  18348. var ID_SEPARATOR = '@@';
  18349. var i18nCommentsWarned = false;
  18350. function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
  18351. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  18352. return visitor.merge(nodes, translations, interpolationConfig);
  18353. }
  18354. var ExtractionResult = /** @class */ (function () {
  18355. function ExtractionResult(messages, errors) {
  18356. this.messages = messages;
  18357. this.errors = errors;
  18358. }
  18359. return ExtractionResult;
  18360. }());
  18361. var _VisitorMode;
  18362. (function (_VisitorMode) {
  18363. _VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
  18364. _VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
  18365. })(_VisitorMode || (_VisitorMode = {}));
  18366. /**
  18367. * This Visitor is used:
  18368. * 1. to extract all the translatable strings from an html AST (see `extract()`),
  18369. * 2. to replace the translatable strings with the actual translations (see `merge()`)
  18370. *
  18371. * @internal
  18372. */
  18373. var _Visitor$2 = /** @class */ (function () {
  18374. function _Visitor(_implicitTags, _implicitAttrs) {
  18375. this._implicitTags = _implicitTags;
  18376. this._implicitAttrs = _implicitAttrs;
  18377. }
  18378. /**
  18379. * Extracts the messages from the tree
  18380. */
  18381. _Visitor.prototype.extract = function (nodes, interpolationConfig) {
  18382. var _this = this;
  18383. this._init(_VisitorMode.Extract, interpolationConfig);
  18384. nodes.forEach(function (node) { return node.visit(_this, null); });
  18385. if (this._inI18nBlock) {
  18386. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  18387. }
  18388. return new ExtractionResult(this._messages, this._errors);
  18389. };
  18390. /**
  18391. * Returns a tree where all translatable nodes are translated
  18392. */
  18393. _Visitor.prototype.merge = function (nodes, translations, interpolationConfig) {
  18394. this._init(_VisitorMode.Merge, interpolationConfig);
  18395. this._translations = translations;
  18396. // Construct a single fake root element
  18397. var wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
  18398. var translatedNode = wrapper.visit(this, null);
  18399. if (this._inI18nBlock) {
  18400. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  18401. }
  18402. return new ParseTreeResult(translatedNode.children, this._errors);
  18403. };
  18404. _Visitor.prototype.visitExpansionCase = function (icuCase, context) {
  18405. // Parse cases for translatable html attributes
  18406. var expression = visitAll$1(this, icuCase.expression, context);
  18407. if (this._mode === _VisitorMode.Merge) {
  18408. return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
  18409. }
  18410. };
  18411. _Visitor.prototype.visitExpansion = function (icu, context) {
  18412. this._mayBeAddBlockChildren(icu);
  18413. var wasInIcu = this._inIcu;
  18414. if (!this._inIcu) {
  18415. // nested ICU messages should not be extracted but top-level translated as a whole
  18416. if (this._isInTranslatableSection) {
  18417. this._addMessage([icu]);
  18418. }
  18419. this._inIcu = true;
  18420. }
  18421. var cases = visitAll$1(this, icu.cases, context);
  18422. if (this._mode === _VisitorMode.Merge) {
  18423. icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
  18424. }
  18425. this._inIcu = wasInIcu;
  18426. return icu;
  18427. };
  18428. _Visitor.prototype.visitComment = function (comment, context) {
  18429. var isOpening = _isOpeningComment(comment);
  18430. if (isOpening && this._isInTranslatableSection) {
  18431. this._reportError(comment, 'Could not start a block inside a translatable section');
  18432. return;
  18433. }
  18434. var isClosing = _isClosingComment(comment);
  18435. if (isClosing && !this._inI18nBlock) {
  18436. this._reportError(comment, 'Trying to close an unopened block');
  18437. return;
  18438. }
  18439. if (!this._inI18nNode && !this._inIcu) {
  18440. if (!this._inI18nBlock) {
  18441. if (isOpening) {
  18442. // deprecated from v5 you should use <ng-container i18n> instead of i18n comments
  18443. if (!i18nCommentsWarned && console && console.warn) {
  18444. i18nCommentsWarned = true;
  18445. var details = comment.sourceSpan.details ? ", " + comment.sourceSpan.details : '';
  18446. // TODO(ocombe): use a log service once there is a public one available
  18447. console.warn("I18n comments are deprecated, use an <ng-container> element instead (" + comment.sourceSpan.start + details + ")");
  18448. }
  18449. this._inI18nBlock = true;
  18450. this._blockStartDepth = this._depth;
  18451. this._blockChildren = [];
  18452. this._blockMeaningAndDesc =
  18453. comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
  18454. this._openTranslatableSection(comment);
  18455. }
  18456. }
  18457. else {
  18458. if (isClosing) {
  18459. if (this._depth == this._blockStartDepth) {
  18460. this._closeTranslatableSection(comment, this._blockChildren);
  18461. this._inI18nBlock = false;
  18462. var message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
  18463. // merge attributes in sections
  18464. var nodes = this._translateMessage(comment, message);
  18465. return visitAll$1(this, nodes);
  18466. }
  18467. else {
  18468. this._reportError(comment, 'I18N blocks should not cross element boundaries');
  18469. return;
  18470. }
  18471. }
  18472. }
  18473. }
  18474. };
  18475. _Visitor.prototype.visitText = function (text, context) {
  18476. if (this._isInTranslatableSection) {
  18477. this._mayBeAddBlockChildren(text);
  18478. }
  18479. return text;
  18480. };
  18481. _Visitor.prototype.visitElement = function (el, context) {
  18482. var _this = this;
  18483. this._mayBeAddBlockChildren(el);
  18484. this._depth++;
  18485. var wasInI18nNode = this._inI18nNode;
  18486. var wasInImplicitNode = this._inImplicitNode;
  18487. var childNodes = [];
  18488. var translatedChildNodes = undefined;
  18489. // Extract:
  18490. // - top level nodes with the (implicit) "i18n" attribute if not already in a section
  18491. // - ICU messages
  18492. var i18nAttr = _getI18nAttr(el);
  18493. var i18nMeta = i18nAttr ? i18nAttr.value : '';
  18494. var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
  18495. !this._isInTranslatableSection;
  18496. var isTopLevelImplicit = !wasInImplicitNode && isImplicit;
  18497. this._inImplicitNode = wasInImplicitNode || isImplicit;
  18498. if (!this._isInTranslatableSection && !this._inIcu) {
  18499. if (i18nAttr || isTopLevelImplicit) {
  18500. this._inI18nNode = true;
  18501. var message = this._addMessage(el.children, i18nMeta);
  18502. translatedChildNodes = this._translateMessage(el, message);
  18503. }
  18504. if (this._mode == _VisitorMode.Extract) {
  18505. var isTranslatable = i18nAttr || isTopLevelImplicit;
  18506. if (isTranslatable)
  18507. this._openTranslatableSection(el);
  18508. visitAll$1(this, el.children);
  18509. if (isTranslatable)
  18510. this._closeTranslatableSection(el, el.children);
  18511. }
  18512. }
  18513. else {
  18514. if (i18nAttr || isTopLevelImplicit) {
  18515. this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
  18516. }
  18517. if (this._mode == _VisitorMode.Extract) {
  18518. // Descend into child nodes for extraction
  18519. visitAll$1(this, el.children);
  18520. }
  18521. }
  18522. if (this._mode === _VisitorMode.Merge) {
  18523. var visitNodes = translatedChildNodes || el.children;
  18524. visitNodes.forEach(function (child) {
  18525. var visited = child.visit(_this, context);
  18526. if (visited && !_this._isInTranslatableSection) {
  18527. // Do not add the children from translatable sections (= i18n blocks here)
  18528. // They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
  18529. childNodes = childNodes.concat(visited);
  18530. }
  18531. });
  18532. }
  18533. this._visitAttributesOf(el);
  18534. this._depth--;
  18535. this._inI18nNode = wasInI18nNode;
  18536. this._inImplicitNode = wasInImplicitNode;
  18537. if (this._mode === _VisitorMode.Merge) {
  18538. var translatedAttrs = this._translateAttributes(el);
  18539. return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
  18540. }
  18541. return null;
  18542. };
  18543. _Visitor.prototype.visitAttribute = function (attribute, context) {
  18544. throw new Error('unreachable code');
  18545. };
  18546. _Visitor.prototype._init = function (mode, interpolationConfig) {
  18547. this._mode = mode;
  18548. this._inI18nBlock = false;
  18549. this._inI18nNode = false;
  18550. this._depth = 0;
  18551. this._inIcu = false;
  18552. this._msgCountAtSectionStart = undefined;
  18553. this._errors = [];
  18554. this._messages = [];
  18555. this._inImplicitNode = false;
  18556. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  18557. };
  18558. // looks for translatable attributes
  18559. _Visitor.prototype._visitAttributesOf = function (el) {
  18560. var _this = this;
  18561. var explicitAttrNameToValue = {};
  18562. var implicitAttrNames = this._implicitAttrs[el.name] || [];
  18563. el.attrs.filter(function (attr) { return attr.name.startsWith(_I18N_ATTR_PREFIX); })
  18564. .forEach(function (attr) { return explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  18565. attr.value; });
  18566. el.attrs.forEach(function (attr) {
  18567. if (attr.name in explicitAttrNameToValue) {
  18568. _this._addMessage([attr], explicitAttrNameToValue[attr.name]);
  18569. }
  18570. else if (implicitAttrNames.some(function (name) { return attr.name === name; })) {
  18571. _this._addMessage([attr]);
  18572. }
  18573. });
  18574. };
  18575. // add a translatable message
  18576. _Visitor.prototype._addMessage = function (ast, msgMeta) {
  18577. if (ast.length == 0 ||
  18578. ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
  18579. // Do not create empty messages
  18580. return null;
  18581. }
  18582. var _a = _parseMessageMeta(msgMeta), meaning = _a.meaning, description = _a.description, id = _a.id;
  18583. var message = this._createI18nMessage(ast, meaning, description, id);
  18584. this._messages.push(message);
  18585. return message;
  18586. };
  18587. // Translates the given message given the `TranslationBundle`
  18588. // This is used for translating elements / blocks - see `_translateAttributes` for attributes
  18589. // no-op when called in extraction mode (returns [])
  18590. _Visitor.prototype._translateMessage = function (el, message) {
  18591. if (message && this._mode === _VisitorMode.Merge) {
  18592. var nodes = this._translations.get(message);
  18593. if (nodes) {
  18594. return nodes;
  18595. }
  18596. this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
  18597. }
  18598. return [];
  18599. };
  18600. // translate the attributes of an element and remove i18n specific attributes
  18601. _Visitor.prototype._translateAttributes = function (el) {
  18602. var _this = this;
  18603. var attributes = el.attrs;
  18604. var i18nParsedMessageMeta = {};
  18605. attributes.forEach(function (attr) {
  18606. if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  18607. i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  18608. _parseMessageMeta(attr.value);
  18609. }
  18610. });
  18611. var translatedAttributes = [];
  18612. attributes.forEach(function (attr) {
  18613. if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  18614. // strip i18n specific attributes
  18615. return;
  18616. }
  18617. if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
  18618. var _a = i18nParsedMessageMeta[attr.name], meaning = _a.meaning, description = _a.description, id = _a.id;
  18619. var message = _this._createI18nMessage([attr], meaning, description, id);
  18620. var nodes = _this._translations.get(message);
  18621. if (nodes) {
  18622. if (nodes.length == 0) {
  18623. translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan));
  18624. }
  18625. else if (nodes[0] instanceof Text$3) {
  18626. var value = nodes[0].value;
  18627. translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan));
  18628. }
  18629. else {
  18630. _this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  18631. }
  18632. }
  18633. else {
  18634. _this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  18635. }
  18636. }
  18637. else {
  18638. translatedAttributes.push(attr);
  18639. }
  18640. });
  18641. return translatedAttributes;
  18642. };
  18643. /**
  18644. * Add the node as a child of the block when:
  18645. * - we are in a block,
  18646. * - we are not inside a ICU message (those are handled separately),
  18647. * - the node is a "direct child" of the block
  18648. */
  18649. _Visitor.prototype._mayBeAddBlockChildren = function (node) {
  18650. if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
  18651. this._blockChildren.push(node);
  18652. }
  18653. };
  18654. /**
  18655. * Marks the start of a section, see `_closeTranslatableSection`
  18656. */
  18657. _Visitor.prototype._openTranslatableSection = function (node) {
  18658. if (this._isInTranslatableSection) {
  18659. this._reportError(node, 'Unexpected section start');
  18660. }
  18661. else {
  18662. this._msgCountAtSectionStart = this._messages.length;
  18663. }
  18664. };
  18665. Object.defineProperty(_Visitor.prototype, "_isInTranslatableSection", {
  18666. /**
  18667. * A translatable section could be:
  18668. * - the content of translatable element,
  18669. * - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
  18670. */
  18671. get: function () {
  18672. return this._msgCountAtSectionStart !== void 0;
  18673. },
  18674. enumerable: true,
  18675. configurable: true
  18676. });
  18677. /**
  18678. * Terminates a section.
  18679. *
  18680. * If a section has only one significant children (comments not significant) then we should not
  18681. * keep the message from this children:
  18682. *
  18683. * `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
  18684. * - one for the <p> content with meaning and description,
  18685. * - another one for the ICU message.
  18686. *
  18687. * In this case the last message is discarded as it contains less information (the AST is
  18688. * otherwise identical).
  18689. *
  18690. * Note that we should still keep messages extracted from attributes inside the section (ie in the
  18691. * ICU message here)
  18692. */
  18693. _Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
  18694. if (!this._isInTranslatableSection) {
  18695. this._reportError(node, 'Unexpected section end');
  18696. return;
  18697. }
  18698. var startIndex = this._msgCountAtSectionStart;
  18699. var significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment ? 0 : 1); }, 0);
  18700. if (significantChildren == 1) {
  18701. for (var i = this._messages.length - 1; i >= startIndex; i--) {
  18702. var ast = this._messages[i].nodes;
  18703. if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
  18704. this._messages.splice(i, 1);
  18705. break;
  18706. }
  18707. }
  18708. }
  18709. this._msgCountAtSectionStart = undefined;
  18710. };
  18711. _Visitor.prototype._reportError = function (node, msg) {
  18712. this._errors.push(new I18nError(node.sourceSpan, msg));
  18713. };
  18714. return _Visitor;
  18715. }());
  18716. function _isOpeningComment(n) {
  18717. return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
  18718. }
  18719. function _isClosingComment(n) {
  18720. return !!(n instanceof Comment && n.value && n.value === '/i18n');
  18721. }
  18722. function _getI18nAttr(p) {
  18723. return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
  18724. }
  18725. function _parseMessageMeta(i18n) {
  18726. if (!i18n)
  18727. return { meaning: '', description: '', id: '' };
  18728. var idIndex = i18n.indexOf(ID_SEPARATOR);
  18729. var descIndex = i18n.indexOf(MEANING_SEPARATOR);
  18730. var _a = __read((idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  18731. var _b = __read((descIndex > -1) ?
  18732. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  18733. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  18734. return { meaning: meaning, description: description, id: id };
  18735. }
  18736. /**
  18737. * @license
  18738. * Copyright Google Inc. All Rights Reserved.
  18739. *
  18740. * Use of this source code is governed by an MIT-style license that can be
  18741. * found in the LICENSE file at https://angular.io/license
  18742. */
  18743. var XmlTagDefinition = /** @class */ (function () {
  18744. function XmlTagDefinition() {
  18745. this.closedByParent = false;
  18746. this.contentType = TagContentType.PARSABLE_DATA;
  18747. this.isVoid = false;
  18748. this.ignoreFirstLf = false;
  18749. this.canSelfClose = true;
  18750. }
  18751. XmlTagDefinition.prototype.requireExtraParent = function (currentParent) { return false; };
  18752. XmlTagDefinition.prototype.isClosedByChild = function (name) { return false; };
  18753. return XmlTagDefinition;
  18754. }());
  18755. var _TAG_DEFINITION = new XmlTagDefinition();
  18756. function getXmlTagDefinition(tagName) {
  18757. return _TAG_DEFINITION;
  18758. }
  18759. /**
  18760. * @license
  18761. * Copyright Google Inc. All Rights Reserved.
  18762. *
  18763. * Use of this source code is governed by an MIT-style license that can be
  18764. * found in the LICENSE file at https://angular.io/license
  18765. */
  18766. var XmlParser = /** @class */ (function (_super) {
  18767. __extends(XmlParser, _super);
  18768. function XmlParser() {
  18769. return _super.call(this, getXmlTagDefinition) || this;
  18770. }
  18771. XmlParser.prototype.parse = function (source, url, options) {
  18772. return _super.prototype.parse.call(this, source, url, options);
  18773. };
  18774. return XmlParser;
  18775. }(Parser));
  18776. /**
  18777. * @license
  18778. * Copyright Google Inc. All Rights Reserved.
  18779. *
  18780. * Use of this source code is governed by an MIT-style license that can be
  18781. * found in the LICENSE file at https://angular.io/license
  18782. */
  18783. var _VERSION = '1.2';
  18784. var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
  18785. // TODO(vicb): make this a param (s/_/-/)
  18786. var _DEFAULT_SOURCE_LANG = 'en';
  18787. var _PLACEHOLDER_TAG$1 = 'x';
  18788. var _MARKER_TAG = 'mrk';
  18789. var _FILE_TAG = 'file';
  18790. var _SOURCE_TAG$1 = 'source';
  18791. var _SEGMENT_SOURCE_TAG = 'seg-source';
  18792. var _TARGET_TAG = 'target';
  18793. var _UNIT_TAG = 'trans-unit';
  18794. var _CONTEXT_GROUP_TAG = 'context-group';
  18795. var _CONTEXT_TAG = 'context';
  18796. // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
  18797. // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
  18798. var Xliff = /** @class */ (function (_super) {
  18799. __extends(Xliff, _super);
  18800. function Xliff() {
  18801. return _super !== null && _super.apply(this, arguments) || this;
  18802. }
  18803. Xliff.prototype.write = function (messages, locale) {
  18804. var visitor = new _WriteVisitor();
  18805. var transUnits = [];
  18806. messages.forEach(function (message) {
  18807. var _a;
  18808. var contextTags = [];
  18809. message.sources.forEach(function (source) {
  18810. var contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
  18811. contextGroupTag.children.push(new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'sourcefile' }, [new Text$2(source.filePath)]), new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'linenumber' }, [new Text$2("" + source.startLine)]), new CR(8));
  18812. contextTags.push(new CR(8), contextGroupTag);
  18813. });
  18814. var transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
  18815. (_a = transUnit.children).push.apply(_a, __spread([new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes))], contextTags));
  18816. if (message.description) {
  18817. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
  18818. }
  18819. if (message.meaning) {
  18820. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
  18821. }
  18822. transUnit.children.push(new CR(6));
  18823. transUnits.push(new CR(6), transUnit);
  18824. });
  18825. var body = new Tag('body', {}, __spread(transUnits, [new CR(4)]));
  18826. var file = new Tag('file', {
  18827. 'source-language': locale || _DEFAULT_SOURCE_LANG,
  18828. datatype: 'plaintext',
  18829. original: 'ng2.template',
  18830. }, [new CR(4), body, new CR(2)]);
  18831. var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
  18832. return serialize([
  18833. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  18834. ]);
  18835. };
  18836. Xliff.prototype.load = function (content, url) {
  18837. // xliff to xml nodes
  18838. var xliffParser = new XliffParser();
  18839. var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  18840. // xml nodes to i18n nodes
  18841. var i18nNodesByMsgId = {};
  18842. var converter = new XmlToI18n();
  18843. Object.keys(msgIdToHtml).forEach(function (msgId) {
  18844. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  18845. errors.push.apply(errors, __spread(e));
  18846. i18nNodesByMsgId[msgId] = i18nNodes;
  18847. });
  18848. if (errors.length) {
  18849. throw new Error("xliff parse errors:\n" + errors.join('\n'));
  18850. }
  18851. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  18852. };
  18853. Xliff.prototype.digest = function (message) { return digest(message); };
  18854. return Xliff;
  18855. }(Serializer));
  18856. var _WriteVisitor = /** @class */ (function () {
  18857. function _WriteVisitor() {
  18858. }
  18859. _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  18860. _WriteVisitor.prototype.visitContainer = function (container, context) {
  18861. var _this = this;
  18862. var nodes = [];
  18863. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  18864. return nodes;
  18865. };
  18866. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  18867. var _this = this;
  18868. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  18869. Object.keys(icu.cases).forEach(function (c) {
  18870. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  18871. });
  18872. nodes.push(new Text$2("}"));
  18873. return nodes;
  18874. };
  18875. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  18876. var ctype = getCtypeForTag(ph.tag);
  18877. if (ph.isVoid) {
  18878. // void tags have no children nor closing tags
  18879. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + "/>" })];
  18880. }
  18881. var startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + ">" });
  18882. var closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype: ctype, 'equiv-text': "</" + ph.tag + ">" });
  18883. return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
  18884. };
  18885. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  18886. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': "{{" + ph.value + "}}" })];
  18887. };
  18888. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  18889. var equivText = "{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}";
  18890. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
  18891. };
  18892. _WriteVisitor.prototype.serialize = function (nodes) {
  18893. var _this = this;
  18894. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  18895. };
  18896. return _WriteVisitor;
  18897. }());
  18898. // TODO(vicb): add error management (structure)
  18899. // Extract messages as xml nodes from the xliff file
  18900. var XliffParser = /** @class */ (function () {
  18901. function XliffParser() {
  18902. this._locale = null;
  18903. }
  18904. XliffParser.prototype.parse = function (xliff, url) {
  18905. this._unitMlString = null;
  18906. this._msgIdToHtml = {};
  18907. var xml = new XmlParser().parse(xliff, url);
  18908. this._errors = xml.errors;
  18909. visitAll$1(this, xml.rootNodes, null);
  18910. return {
  18911. msgIdToHtml: this._msgIdToHtml,
  18912. errors: this._errors,
  18913. locale: this._locale,
  18914. };
  18915. };
  18916. XliffParser.prototype.visitElement = function (element, context) {
  18917. switch (element.name) {
  18918. case _UNIT_TAG:
  18919. this._unitMlString = null;
  18920. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  18921. if (!idAttr) {
  18922. this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
  18923. }
  18924. else {
  18925. var id = idAttr.value;
  18926. if (this._msgIdToHtml.hasOwnProperty(id)) {
  18927. this._addError(element, "Duplicated translations for msg " + id);
  18928. }
  18929. else {
  18930. visitAll$1(this, element.children, null);
  18931. if (typeof this._unitMlString === 'string') {
  18932. this._msgIdToHtml[id] = this._unitMlString;
  18933. }
  18934. else {
  18935. this._addError(element, "Message " + id + " misses a translation");
  18936. }
  18937. }
  18938. }
  18939. break;
  18940. // ignore those tags
  18941. case _SOURCE_TAG$1:
  18942. case _SEGMENT_SOURCE_TAG:
  18943. break;
  18944. case _TARGET_TAG:
  18945. var innerTextStart = element.startSourceSpan.end.offset;
  18946. var innerTextEnd = element.endSourceSpan.start.offset;
  18947. var content = element.startSourceSpan.start.file.content;
  18948. var innerText = content.slice(innerTextStart, innerTextEnd);
  18949. this._unitMlString = innerText;
  18950. break;
  18951. case _FILE_TAG:
  18952. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
  18953. if (localeAttr) {
  18954. this._locale = localeAttr.value;
  18955. }
  18956. visitAll$1(this, element.children, null);
  18957. break;
  18958. default:
  18959. // TODO(vicb): assert file structure, xliff version
  18960. // For now only recurse on unhandled nodes
  18961. visitAll$1(this, element.children, null);
  18962. }
  18963. };
  18964. XliffParser.prototype.visitAttribute = function (attribute, context) { };
  18965. XliffParser.prototype.visitText = function (text, context) { };
  18966. XliffParser.prototype.visitComment = function (comment, context) { };
  18967. XliffParser.prototype.visitExpansion = function (expansion, context) { };
  18968. XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  18969. XliffParser.prototype._addError = function (node, message) {
  18970. this._errors.push(new I18nError(node.sourceSpan, message));
  18971. };
  18972. return XliffParser;
  18973. }());
  18974. // Convert ml nodes (xliff syntax) to i18n nodes
  18975. var XmlToI18n = /** @class */ (function () {
  18976. function XmlToI18n() {
  18977. }
  18978. XmlToI18n.prototype.convert = function (message, url) {
  18979. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  18980. this._errors = xmlIcu.errors;
  18981. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  18982. [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
  18983. return {
  18984. i18nNodes: i18nNodes,
  18985. errors: this._errors,
  18986. };
  18987. };
  18988. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  18989. XmlToI18n.prototype.visitElement = function (el, context) {
  18990. if (el.name === _PLACEHOLDER_TAG$1) {
  18991. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
  18992. if (nameAttr) {
  18993. return new Placeholder('', nameAttr.value, el.sourceSpan);
  18994. }
  18995. this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"id\" attribute");
  18996. return null;
  18997. }
  18998. if (el.name === _MARKER_TAG) {
  18999. return [].concat.apply([], __spread(visitAll$1(this, el.children)));
  19000. }
  19001. this._addError(el, "Unexpected tag");
  19002. return null;
  19003. };
  19004. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19005. var caseMap = {};
  19006. visitAll$1(this, icu.cases).forEach(function (c) {
  19007. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19008. });
  19009. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19010. };
  19011. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19012. return {
  19013. value: icuCase.value,
  19014. nodes: visitAll$1(this, icuCase.expression),
  19015. };
  19016. };
  19017. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19018. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19019. XmlToI18n.prototype._addError = function (node, message) {
  19020. this._errors.push(new I18nError(node.sourceSpan, message));
  19021. };
  19022. return XmlToI18n;
  19023. }());
  19024. function getCtypeForTag(tag) {
  19025. switch (tag.toLowerCase()) {
  19026. case 'br':
  19027. return 'lb';
  19028. case 'img':
  19029. return 'image';
  19030. default:
  19031. return "x-" + tag;
  19032. }
  19033. }
  19034. /**
  19035. * @license
  19036. * Copyright Google Inc. All Rights Reserved.
  19037. *
  19038. * Use of this source code is governed by an MIT-style license that can be
  19039. * found in the LICENSE file at https://angular.io/license
  19040. */
  19041. var _VERSION$1 = '2.0';
  19042. var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
  19043. // TODO(vicb): make this a param (s/_/-/)
  19044. var _DEFAULT_SOURCE_LANG$1 = 'en';
  19045. var _PLACEHOLDER_TAG$2 = 'ph';
  19046. var _PLACEHOLDER_SPANNING_TAG = 'pc';
  19047. var _MARKER_TAG$1 = 'mrk';
  19048. var _XLIFF_TAG = 'xliff';
  19049. var _SOURCE_TAG$2 = 'source';
  19050. var _TARGET_TAG$1 = 'target';
  19051. var _UNIT_TAG$1 = 'unit';
  19052. // http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
  19053. var Xliff2 = /** @class */ (function (_super) {
  19054. __extends(Xliff2, _super);
  19055. function Xliff2() {
  19056. return _super !== null && _super.apply(this, arguments) || this;
  19057. }
  19058. Xliff2.prototype.write = function (messages, locale) {
  19059. var visitor = new _WriteVisitor$1();
  19060. var units = [];
  19061. messages.forEach(function (message) {
  19062. var unit = new Tag(_UNIT_TAG$1, { id: message.id });
  19063. var notes = new Tag('notes');
  19064. if (message.description || message.meaning) {
  19065. if (message.description) {
  19066. notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
  19067. }
  19068. if (message.meaning) {
  19069. notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
  19070. }
  19071. }
  19072. message.sources.forEach(function (source) {
  19073. notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
  19074. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  19075. ]));
  19076. });
  19077. notes.children.push(new CR(6));
  19078. unit.children.push(new CR(6), notes);
  19079. var segment = new Tag('segment');
  19080. segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
  19081. unit.children.push(new CR(6), segment, new CR(4));
  19082. units.push(new CR(4), unit);
  19083. });
  19084. var file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, __spread(units, [new CR(2)]));
  19085. var xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
  19086. return serialize([
  19087. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  19088. ]);
  19089. };
  19090. Xliff2.prototype.load = function (content, url) {
  19091. // xliff to xml nodes
  19092. var xliff2Parser = new Xliff2Parser();
  19093. var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19094. // xml nodes to i18n nodes
  19095. var i18nNodesByMsgId = {};
  19096. var converter = new XmlToI18n$1();
  19097. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19098. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  19099. errors.push.apply(errors, __spread(e));
  19100. i18nNodesByMsgId[msgId] = i18nNodes;
  19101. });
  19102. if (errors.length) {
  19103. throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
  19104. }
  19105. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19106. };
  19107. Xliff2.prototype.digest = function (message) { return decimalDigest(message); };
  19108. return Xliff2;
  19109. }(Serializer));
  19110. var _WriteVisitor$1 = /** @class */ (function () {
  19111. function _WriteVisitor() {
  19112. }
  19113. _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  19114. _WriteVisitor.prototype.visitContainer = function (container, context) {
  19115. var _this = this;
  19116. var nodes = [];
  19117. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  19118. return nodes;
  19119. };
  19120. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  19121. var _this = this;
  19122. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  19123. Object.keys(icu.cases).forEach(function (c) {
  19124. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  19125. });
  19126. nodes.push(new Text$2("}"));
  19127. return nodes;
  19128. };
  19129. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19130. var _this = this;
  19131. var type = getTypeForTag(ph.tag);
  19132. if (ph.isVoid) {
  19133. var tagPh = new Tag(_PLACEHOLDER_TAG$2, {
  19134. id: (this._nextPlaceholderId++).toString(),
  19135. equiv: ph.startName,
  19136. type: type,
  19137. disp: "<" + ph.tag + "/>",
  19138. });
  19139. return [tagPh];
  19140. }
  19141. var tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
  19142. id: (this._nextPlaceholderId++).toString(),
  19143. equivStart: ph.startName,
  19144. equivEnd: ph.closeName,
  19145. type: type,
  19146. dispStart: "<" + ph.tag + ">",
  19147. dispEnd: "</" + ph.tag + ">",
  19148. });
  19149. var nodes = [].concat.apply([], __spread(ph.children.map(function (node) { return node.visit(_this); })));
  19150. if (nodes.length) {
  19151. nodes.forEach(function (node) { return tagPc.children.push(node); });
  19152. }
  19153. else {
  19154. tagPc.children.push(new Text$2(''));
  19155. }
  19156. return [tagPc];
  19157. };
  19158. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  19159. var idStr = (this._nextPlaceholderId++).toString();
  19160. return [new Tag(_PLACEHOLDER_TAG$2, {
  19161. id: idStr,
  19162. equiv: ph.name,
  19163. disp: "{{" + ph.value + "}}",
  19164. })];
  19165. };
  19166. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  19167. var cases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  19168. var idStr = (this._nextPlaceholderId++).toString();
  19169. return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: "{" + ph.value.expression + ", " + ph.value.type + ", " + cases + "}" })];
  19170. };
  19171. _WriteVisitor.prototype.serialize = function (nodes) {
  19172. var _this = this;
  19173. this._nextPlaceholderId = 0;
  19174. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  19175. };
  19176. return _WriteVisitor;
  19177. }());
  19178. // Extract messages as xml nodes from the xliff file
  19179. var Xliff2Parser = /** @class */ (function () {
  19180. function Xliff2Parser() {
  19181. this._locale = null;
  19182. }
  19183. Xliff2Parser.prototype.parse = function (xliff, url) {
  19184. this._unitMlString = null;
  19185. this._msgIdToHtml = {};
  19186. var xml = new XmlParser().parse(xliff, url);
  19187. this._errors = xml.errors;
  19188. visitAll$1(this, xml.rootNodes, null);
  19189. return {
  19190. msgIdToHtml: this._msgIdToHtml,
  19191. errors: this._errors,
  19192. locale: this._locale,
  19193. };
  19194. };
  19195. Xliff2Parser.prototype.visitElement = function (element, context) {
  19196. switch (element.name) {
  19197. case _UNIT_TAG$1:
  19198. this._unitMlString = null;
  19199. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19200. if (!idAttr) {
  19201. this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
  19202. }
  19203. else {
  19204. var id = idAttr.value;
  19205. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19206. this._addError(element, "Duplicated translations for msg " + id);
  19207. }
  19208. else {
  19209. visitAll$1(this, element.children, null);
  19210. if (typeof this._unitMlString === 'string') {
  19211. this._msgIdToHtml[id] = this._unitMlString;
  19212. }
  19213. else {
  19214. this._addError(element, "Message " + id + " misses a translation");
  19215. }
  19216. }
  19217. }
  19218. break;
  19219. case _SOURCE_TAG$2:
  19220. // ignore source message
  19221. break;
  19222. case _TARGET_TAG$1:
  19223. var innerTextStart = element.startSourceSpan.end.offset;
  19224. var innerTextEnd = element.endSourceSpan.start.offset;
  19225. var content = element.startSourceSpan.start.file.content;
  19226. var innerText = content.slice(innerTextStart, innerTextEnd);
  19227. this._unitMlString = innerText;
  19228. break;
  19229. case _XLIFF_TAG:
  19230. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
  19231. if (localeAttr) {
  19232. this._locale = localeAttr.value;
  19233. }
  19234. var versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
  19235. if (versionAttr) {
  19236. var version = versionAttr.value;
  19237. if (version !== '2.0') {
  19238. this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
  19239. }
  19240. else {
  19241. visitAll$1(this, element.children, null);
  19242. }
  19243. }
  19244. break;
  19245. default:
  19246. visitAll$1(this, element.children, null);
  19247. }
  19248. };
  19249. Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
  19250. Xliff2Parser.prototype.visitText = function (text, context) { };
  19251. Xliff2Parser.prototype.visitComment = function (comment, context) { };
  19252. Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
  19253. Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19254. Xliff2Parser.prototype._addError = function (node, message) {
  19255. this._errors.push(new I18nError(node.sourceSpan, message));
  19256. };
  19257. return Xliff2Parser;
  19258. }());
  19259. // Convert ml nodes (xliff syntax) to i18n nodes
  19260. var XmlToI18n$1 = /** @class */ (function () {
  19261. function XmlToI18n() {
  19262. }
  19263. XmlToI18n.prototype.convert = function (message, url) {
  19264. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19265. this._errors = xmlIcu.errors;
  19266. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19267. [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
  19268. return {
  19269. i18nNodes: i18nNodes,
  19270. errors: this._errors,
  19271. };
  19272. };
  19273. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19274. XmlToI18n.prototype.visitElement = function (el, context) {
  19275. var _this = this;
  19276. switch (el.name) {
  19277. case _PLACEHOLDER_TAG$2:
  19278. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
  19279. if (nameAttr) {
  19280. return [new Placeholder('', nameAttr.value, el.sourceSpan)];
  19281. }
  19282. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equiv\" attribute");
  19283. break;
  19284. case _PLACEHOLDER_SPANNING_TAG:
  19285. var startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
  19286. var endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
  19287. if (!startAttr) {
  19288. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivStart\" attribute");
  19289. }
  19290. else if (!endAttr) {
  19291. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivEnd\" attribute");
  19292. }
  19293. else {
  19294. var startId = startAttr.value;
  19295. var endId = endAttr.value;
  19296. var nodes = [];
  19297. return nodes.concat.apply(nodes, __spread([new Placeholder('', startId, el.sourceSpan)], el.children.map(function (node) { return node.visit(_this, null); }), [new Placeholder('', endId, el.sourceSpan)]));
  19298. }
  19299. break;
  19300. case _MARKER_TAG$1:
  19301. return [].concat.apply([], __spread(visitAll$1(this, el.children)));
  19302. default:
  19303. this._addError(el, "Unexpected tag");
  19304. }
  19305. return null;
  19306. };
  19307. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19308. var caseMap = {};
  19309. visitAll$1(this, icu.cases).forEach(function (c) {
  19310. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19311. });
  19312. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19313. };
  19314. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19315. return {
  19316. value: icuCase.value,
  19317. nodes: [].concat.apply([], __spread(visitAll$1(this, icuCase.expression))),
  19318. };
  19319. };
  19320. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19321. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19322. XmlToI18n.prototype._addError = function (node, message) {
  19323. this._errors.push(new I18nError(node.sourceSpan, message));
  19324. };
  19325. return XmlToI18n;
  19326. }());
  19327. function getTypeForTag(tag) {
  19328. switch (tag.toLowerCase()) {
  19329. case 'br':
  19330. case 'b':
  19331. case 'i':
  19332. case 'u':
  19333. return 'fmt';
  19334. case 'img':
  19335. return 'image';
  19336. case 'a':
  19337. return 'link';
  19338. default:
  19339. return 'other';
  19340. }
  19341. }
  19342. /**
  19343. * @license
  19344. * Copyright Google Inc. All Rights Reserved.
  19345. *
  19346. * Use of this source code is governed by an MIT-style license that can be
  19347. * found in the LICENSE file at https://angular.io/license
  19348. */
  19349. var _TRANSLATIONS_TAG = 'translationbundle';
  19350. var _TRANSLATION_TAG = 'translation';
  19351. var _PLACEHOLDER_TAG$3 = 'ph';
  19352. var Xtb = /** @class */ (function (_super) {
  19353. __extends(Xtb, _super);
  19354. function Xtb() {
  19355. return _super !== null && _super.apply(this, arguments) || this;
  19356. }
  19357. Xtb.prototype.write = function (messages, locale) { throw new Error('Unsupported'); };
  19358. Xtb.prototype.load = function (content, url) {
  19359. // xtb to xml nodes
  19360. var xtbParser = new XtbParser();
  19361. var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19362. // xml nodes to i18n nodes
  19363. var i18nNodesByMsgId = {};
  19364. var converter = new XmlToI18n$2();
  19365. // Because we should be able to load xtb files that rely on features not supported by angular,
  19366. // we need to delay the conversion of html to i18n nodes so that non angular messages are not
  19367. // converted
  19368. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19369. var valueFn = function () {
  19370. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
  19371. if (errors.length) {
  19372. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  19373. }
  19374. return i18nNodes;
  19375. };
  19376. createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
  19377. });
  19378. if (errors.length) {
  19379. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  19380. }
  19381. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19382. };
  19383. Xtb.prototype.digest = function (message) { return digest$1(message); };
  19384. Xtb.prototype.createNameMapper = function (message) {
  19385. return new SimplePlaceholderMapper(message, toPublicName);
  19386. };
  19387. return Xtb;
  19388. }(Serializer));
  19389. function createLazyProperty(messages, id, valueFn) {
  19390. Object.defineProperty(messages, id, {
  19391. configurable: true,
  19392. enumerable: true,
  19393. get: function () {
  19394. var value = valueFn();
  19395. Object.defineProperty(messages, id, { enumerable: true, value: value });
  19396. return value;
  19397. },
  19398. set: function (_) { throw new Error('Could not overwrite an XTB translation'); },
  19399. });
  19400. }
  19401. // Extract messages as xml nodes from the xtb file
  19402. var XtbParser = /** @class */ (function () {
  19403. function XtbParser() {
  19404. this._locale = null;
  19405. }
  19406. XtbParser.prototype.parse = function (xtb, url) {
  19407. this._bundleDepth = 0;
  19408. this._msgIdToHtml = {};
  19409. // We can not parse the ICU messages at this point as some messages might not originate
  19410. // from Angular that could not be lex'd.
  19411. var xml = new XmlParser().parse(xtb, url);
  19412. this._errors = xml.errors;
  19413. visitAll$1(this, xml.rootNodes);
  19414. return {
  19415. msgIdToHtml: this._msgIdToHtml,
  19416. errors: this._errors,
  19417. locale: this._locale,
  19418. };
  19419. };
  19420. XtbParser.prototype.visitElement = function (element, context) {
  19421. switch (element.name) {
  19422. case _TRANSLATIONS_TAG:
  19423. this._bundleDepth++;
  19424. if (this._bundleDepth > 1) {
  19425. this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
  19426. }
  19427. var langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
  19428. if (langAttr) {
  19429. this._locale = langAttr.value;
  19430. }
  19431. visitAll$1(this, element.children, null);
  19432. this._bundleDepth--;
  19433. break;
  19434. case _TRANSLATION_TAG:
  19435. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19436. if (!idAttr) {
  19437. this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
  19438. }
  19439. else {
  19440. var id = idAttr.value;
  19441. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19442. this._addError(element, "Duplicated translations for msg " + id);
  19443. }
  19444. else {
  19445. var innerTextStart = element.startSourceSpan.end.offset;
  19446. var innerTextEnd = element.endSourceSpan.start.offset;
  19447. var content = element.startSourceSpan.start.file.content;
  19448. var innerText = content.slice(innerTextStart, innerTextEnd);
  19449. this._msgIdToHtml[id] = innerText;
  19450. }
  19451. }
  19452. break;
  19453. default:
  19454. this._addError(element, 'Unexpected tag');
  19455. }
  19456. };
  19457. XtbParser.prototype.visitAttribute = function (attribute, context) { };
  19458. XtbParser.prototype.visitText = function (text, context) { };
  19459. XtbParser.prototype.visitComment = function (comment, context) { };
  19460. XtbParser.prototype.visitExpansion = function (expansion, context) { };
  19461. XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19462. XtbParser.prototype._addError = function (node, message) {
  19463. this._errors.push(new I18nError(node.sourceSpan, message));
  19464. };
  19465. return XtbParser;
  19466. }());
  19467. // Convert ml nodes (xtb syntax) to i18n nodes
  19468. var XmlToI18n$2 = /** @class */ (function () {
  19469. function XmlToI18n() {
  19470. }
  19471. XmlToI18n.prototype.convert = function (message, url) {
  19472. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19473. this._errors = xmlIcu.errors;
  19474. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19475. [] :
  19476. visitAll$1(this, xmlIcu.rootNodes);
  19477. return {
  19478. i18nNodes: i18nNodes,
  19479. errors: this._errors,
  19480. };
  19481. };
  19482. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19483. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19484. var caseMap = {};
  19485. visitAll$1(this, icu.cases).forEach(function (c) {
  19486. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19487. });
  19488. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19489. };
  19490. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19491. return {
  19492. value: icuCase.value,
  19493. nodes: visitAll$1(this, icuCase.expression),
  19494. };
  19495. };
  19496. XmlToI18n.prototype.visitElement = function (el, context) {
  19497. if (el.name === _PLACEHOLDER_TAG$3) {
  19498. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
  19499. if (nameAttr) {
  19500. return new Placeholder('', nameAttr.value, el.sourceSpan);
  19501. }
  19502. this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
  19503. }
  19504. else {
  19505. this._addError(el, "Unexpected tag");
  19506. }
  19507. return null;
  19508. };
  19509. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19510. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19511. XmlToI18n.prototype._addError = function (node, message) {
  19512. this._errors.push(new I18nError(node.sourceSpan, message));
  19513. };
  19514. return XmlToI18n;
  19515. }());
  19516. /**
  19517. * @license
  19518. * Copyright Google Inc. All Rights Reserved.
  19519. *
  19520. * Use of this source code is governed by an MIT-style license that can be
  19521. * found in the LICENSE file at https://angular.io/license
  19522. */
  19523. /**
  19524. * A container for translated messages
  19525. */
  19526. var TranslationBundle = /** @class */ (function () {
  19527. function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
  19528. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  19529. if (missingTranslationStrategy === void 0) { missingTranslationStrategy = MissingTranslationStrategy.Warning; }
  19530. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  19531. this.digest = digest;
  19532. this.mapperFactory = mapperFactory;
  19533. this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
  19534. }
  19535. // Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
  19536. TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
  19537. var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
  19538. var digestFn = function (m) { return serializer.digest(m); };
  19539. var mapperFactory = function (m) { return serializer.createNameMapper(m); };
  19540. return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
  19541. };
  19542. // Returns the translation as HTML nodes from the given source message.
  19543. TranslationBundle.prototype.get = function (srcMsg) {
  19544. var html = this._i18nToHtml.convert(srcMsg);
  19545. if (html.errors.length) {
  19546. throw new Error(html.errors.join('\n'));
  19547. }
  19548. return html.nodes;
  19549. };
  19550. TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
  19551. return TranslationBundle;
  19552. }());
  19553. var I18nToHtmlVisitor = /** @class */ (function () {
  19554. function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
  19555. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  19556. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  19557. this._locale = _locale;
  19558. this._digest = _digest;
  19559. this._mapperFactory = _mapperFactory;
  19560. this._missingTranslationStrategy = _missingTranslationStrategy;
  19561. this._console = _console;
  19562. this._contextStack = [];
  19563. this._errors = [];
  19564. }
  19565. I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
  19566. this._contextStack.length = 0;
  19567. this._errors.length = 0;
  19568. // i18n to text
  19569. var text = this._convertToText(srcMsg);
  19570. // text to html
  19571. var url = srcMsg.nodes[0].sourceSpan.start.file.url;
  19572. var html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
  19573. return {
  19574. nodes: html.rootNodes,
  19575. errors: __spread(this._errors, html.errors),
  19576. };
  19577. };
  19578. I18nToHtmlVisitor.prototype.visitText = function (text, context) {
  19579. // `convert()` uses an `HtmlParser` to return `html.Node`s
  19580. // we should then make sure that any special characters are escaped
  19581. return escapeXml(text.value);
  19582. };
  19583. I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
  19584. var _this = this;
  19585. return container.children.map(function (n) { return n.visit(_this); }).join('');
  19586. };
  19587. I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
  19588. var _this = this;
  19589. var cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  19590. // TODO(vicb): Once all format switch to using expression placeholders
  19591. // we should throw when the placeholder is not in the source message
  19592. var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
  19593. this._srcMsg.placeholders[icu.expression] :
  19594. icu.expression;
  19595. return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
  19596. };
  19597. I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
  19598. var phName = this._mapper(ph.name);
  19599. if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
  19600. return this._srcMsg.placeholders[phName];
  19601. }
  19602. if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
  19603. return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
  19604. }
  19605. this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
  19606. return '';
  19607. };
  19608. // Loaded message contains only placeholders (vs tag and icu placeholders).
  19609. // However when a translation can not be found, we need to serialize the source message
  19610. // which can contain tag placeholders
  19611. I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19612. var _this = this;
  19613. var tag = "" + ph.tag;
  19614. var attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
  19615. if (ph.isVoid) {
  19616. return "<" + tag + " " + attrs + "/>";
  19617. }
  19618. var children = ph.children.map(function (c) { return c.visit(_this); }).join('');
  19619. return "<" + tag + " " + attrs + ">" + children + "</" + tag + ">";
  19620. };
  19621. // Loaded message contains only placeholders (vs tag and icu placeholders).
  19622. // However when a translation can not be found, we need to serialize the source message
  19623. // which can contain tag placeholders
  19624. I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  19625. // An ICU placeholder references the source message to be serialized
  19626. return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
  19627. };
  19628. /**
  19629. * Convert a source message to a translated text string:
  19630. * - text nodes are replaced with their translation,
  19631. * - placeholders are replaced with their content,
  19632. * - ICU nodes are converted to ICU expressions.
  19633. */
  19634. I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
  19635. var _this = this;
  19636. var id = this._digest(srcMsg);
  19637. var mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
  19638. var nodes;
  19639. this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
  19640. this._srcMsg = srcMsg;
  19641. if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
  19642. // When there is a translation use its nodes as the source
  19643. // And create a mapper to convert serialized placeholder names to internal names
  19644. nodes = this._i18nNodesByMsgId[id];
  19645. this._mapper = function (name) { return mapper ? mapper.toInternalName(name) : name; };
  19646. }
  19647. else {
  19648. // When no translation has been found
  19649. // - report an error / a warning / nothing,
  19650. // - use the nodes from the original message
  19651. // - placeholders are already internal and need no mapper
  19652. if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
  19653. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  19654. this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
  19655. }
  19656. else if (this._console &&
  19657. this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
  19658. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  19659. this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
  19660. }
  19661. nodes = srcMsg.nodes;
  19662. this._mapper = function (name) { return name; };
  19663. }
  19664. var text = nodes.map(function (node) { return node.visit(_this); }).join('');
  19665. var context = this._contextStack.pop();
  19666. this._srcMsg = context.msg;
  19667. this._mapper = context.mapper;
  19668. return text;
  19669. };
  19670. I18nToHtmlVisitor.prototype._addError = function (el, msg) {
  19671. this._errors.push(new I18nError(el.sourceSpan, msg));
  19672. };
  19673. return I18nToHtmlVisitor;
  19674. }());
  19675. /**
  19676. * @license
  19677. * Copyright Google Inc. All Rights Reserved.
  19678. *
  19679. * Use of this source code is governed by an MIT-style license that can be
  19680. * found in the LICENSE file at https://angular.io/license
  19681. */
  19682. var I18NHtmlParser = /** @class */ (function () {
  19683. function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
  19684. if (missingTranslation === void 0) { missingTranslation = MissingTranslationStrategy.Warning; }
  19685. this._htmlParser = _htmlParser;
  19686. if (translations) {
  19687. var serializer = createSerializer(translationsFormat);
  19688. this._translationBundle =
  19689. TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
  19690. }
  19691. else {
  19692. this._translationBundle =
  19693. new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
  19694. }
  19695. }
  19696. I18NHtmlParser.prototype.parse = function (source, url, options) {
  19697. if (options === void 0) { options = {}; }
  19698. var interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  19699. var parseResult = this._htmlParser.parse(source, url, __assign({ interpolationConfig: interpolationConfig }, options));
  19700. if (parseResult.errors.length) {
  19701. return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
  19702. }
  19703. return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
  19704. };
  19705. return I18NHtmlParser;
  19706. }());
  19707. function createSerializer(format) {
  19708. format = (format || 'xlf').toLowerCase();
  19709. switch (format) {
  19710. case 'xmb':
  19711. return new Xmb();
  19712. case 'xtb':
  19713. return new Xtb();
  19714. case 'xliff2':
  19715. case 'xlf2':
  19716. return new Xliff2();
  19717. case 'xliff':
  19718. case 'xlf':
  19719. default:
  19720. return new Xliff();
  19721. }
  19722. }
  19723. /**
  19724. * @license
  19725. * Copyright Google Inc. All Rights Reserved.
  19726. *
  19727. * Use of this source code is governed by an MIT-style license that can be
  19728. * found in the LICENSE file at https://angular.io/license
  19729. */
  19730. /**
  19731. * @license
  19732. * Copyright Google Inc. All Rights Reserved.
  19733. *
  19734. * Use of this source code is governed by an MIT-style license that can be
  19735. * found in the LICENSE file at https://angular.io/license
  19736. */
  19737. /**
  19738. * @license
  19739. * Copyright Google Inc. All Rights Reserved.
  19740. *
  19741. * Use of this source code is governed by an MIT-style license that can be
  19742. * found in the LICENSE file at https://angular.io/license
  19743. */
  19744. var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
  19745. var GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
  19746. var JIT_SUMMARY_FILE = /\.ngsummary\./;
  19747. var JIT_SUMMARY_NAME = /NgSummary$/;
  19748. function ngfactoryFilePath(filePath, forceSourceFile) {
  19749. if (forceSourceFile === void 0) { forceSourceFile = false; }
  19750. var urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
  19751. return urlWithSuffix[0] + ".ngfactory" + normalizeGenFileSuffix(urlWithSuffix[1]);
  19752. }
  19753. function stripGeneratedFileSuffix(filePath) {
  19754. return filePath.replace(GENERATED_FILE, '.');
  19755. }
  19756. function isGeneratedFile(filePath) {
  19757. return GENERATED_FILE.test(filePath);
  19758. }
  19759. function splitTypescriptSuffix(path, forceSourceFile) {
  19760. if (forceSourceFile === void 0) { forceSourceFile = false; }
  19761. if (path.endsWith('.d.ts')) {
  19762. return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
  19763. }
  19764. var lastDot = path.lastIndexOf('.');
  19765. if (lastDot !== -1) {
  19766. return [path.substring(0, lastDot), path.substring(lastDot)];
  19767. }
  19768. return [path, ''];
  19769. }
  19770. function normalizeGenFileSuffix(srcFileSuffix) {
  19771. return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
  19772. }
  19773. function summaryFileName(fileName) {
  19774. var fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
  19775. return fileNameWithoutSuffix + ".ngsummary.json";
  19776. }
  19777. function summaryForJitFileName(fileName, forceSourceFile) {
  19778. if (forceSourceFile === void 0) { forceSourceFile = false; }
  19779. var urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
  19780. return urlWithSuffix[0] + ".ngsummary" + urlWithSuffix[1];
  19781. }
  19782. function stripSummaryForJitFileSuffix(filePath) {
  19783. return filePath.replace(JIT_SUMMARY_FILE, '.');
  19784. }
  19785. function summaryForJitName(symbolName) {
  19786. return symbolName + "NgSummary";
  19787. }
  19788. function stripSummaryForJitNameSuffix(symbolName) {
  19789. return symbolName.replace(JIT_SUMMARY_NAME, '');
  19790. }
  19791. var LOWERED_SYMBOL = /\u0275\d+/;
  19792. function isLoweredSymbol(name) {
  19793. return LOWERED_SYMBOL.test(name);
  19794. }
  19795. /**
  19796. * @license
  19797. * Copyright Google Inc. All Rights Reserved.
  19798. *
  19799. * Use of this source code is governed by an MIT-style license that can be
  19800. * found in the LICENSE file at https://angular.io/license
  19801. */
  19802. var LifecycleHooks;
  19803. (function (LifecycleHooks) {
  19804. LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
  19805. LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
  19806. LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
  19807. LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
  19808. LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
  19809. LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
  19810. LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
  19811. LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
  19812. })(LifecycleHooks || (LifecycleHooks = {}));
  19813. var LIFECYCLE_HOOKS_VALUES = [
  19814. LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
  19815. LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
  19816. LifecycleHooks.AfterViewChecked
  19817. ];
  19818. function hasLifecycleHook(reflector, hook, token) {
  19819. return reflector.hasLifecycleHook(token, getHookName(hook));
  19820. }
  19821. function getAllLifecycleHooks(reflector, token) {
  19822. return LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return hasLifecycleHook(reflector, hook, token); });
  19823. }
  19824. function getHookName(hook) {
  19825. switch (hook) {
  19826. case LifecycleHooks.OnInit:
  19827. return 'ngOnInit';
  19828. case LifecycleHooks.OnDestroy:
  19829. return 'ngOnDestroy';
  19830. case LifecycleHooks.DoCheck:
  19831. return 'ngDoCheck';
  19832. case LifecycleHooks.OnChanges:
  19833. return 'ngOnChanges';
  19834. case LifecycleHooks.AfterContentInit:
  19835. return 'ngAfterContentInit';
  19836. case LifecycleHooks.AfterContentChecked:
  19837. return 'ngAfterContentChecked';
  19838. case LifecycleHooks.AfterViewInit:
  19839. return 'ngAfterViewInit';
  19840. case LifecycleHooks.AfterViewChecked:
  19841. return 'ngAfterViewChecked';
  19842. default:
  19843. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  19844. // However Closure Compiler does not understand that and reports an error in typed mode.
  19845. // The `throw new Error` below works around the problem, and the unexpected: never variable
  19846. // makes sure tsc still checks this code is unreachable.
  19847. var unexpected = hook;
  19848. throw new Error("unexpected " + unexpected);
  19849. }
  19850. }
  19851. /**
  19852. * @license
  19853. * Copyright Google Inc. All Rights Reserved.
  19854. *
  19855. * Use of this source code is governed by an MIT-style license that can be
  19856. * found in the LICENSE file at https://angular.io/license
  19857. */
  19858. var ERROR_COMPONENT_TYPE = 'ngComponentType';
  19859. // Design notes:
  19860. // - don't lazily create metadata:
  19861. // For some metadata, we need to do async work sometimes,
  19862. // so the user has to kick off this loading.
  19863. // But we want to report errors even when the async work is
  19864. // not required to check that the user would have been able
  19865. // to wait correctly.
  19866. var CompileMetadataResolver = /** @class */ (function () {
  19867. function CompileMetadataResolver(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
  19868. this._config = _config;
  19869. this._htmlParser = _htmlParser;
  19870. this._ngModuleResolver = _ngModuleResolver;
  19871. this._directiveResolver = _directiveResolver;
  19872. this._pipeResolver = _pipeResolver;
  19873. this._summaryResolver = _summaryResolver;
  19874. this._schemaRegistry = _schemaRegistry;
  19875. this._directiveNormalizer = _directiveNormalizer;
  19876. this._console = _console;
  19877. this._staticSymbolCache = _staticSymbolCache;
  19878. this._reflector = _reflector;
  19879. this._errorCollector = _errorCollector;
  19880. this._nonNormalizedDirectiveCache = new Map();
  19881. this._directiveCache = new Map();
  19882. this._summaryCache = new Map();
  19883. this._pipeCache = new Map();
  19884. this._ngModuleCache = new Map();
  19885. this._ngModuleOfTypes = new Map();
  19886. this._shallowModuleCache = new Map();
  19887. }
  19888. CompileMetadataResolver.prototype.getReflector = function () { return this._reflector; };
  19889. CompileMetadataResolver.prototype.clearCacheFor = function (type) {
  19890. var dirMeta = this._directiveCache.get(type);
  19891. this._directiveCache.delete(type);
  19892. this._nonNormalizedDirectiveCache.delete(type);
  19893. this._summaryCache.delete(type);
  19894. this._pipeCache.delete(type);
  19895. this._ngModuleOfTypes.delete(type);
  19896. // Clear all of the NgModule as they contain transitive information!
  19897. this._ngModuleCache.clear();
  19898. if (dirMeta) {
  19899. this._directiveNormalizer.clearCacheFor(dirMeta);
  19900. }
  19901. };
  19902. CompileMetadataResolver.prototype.clearCache = function () {
  19903. this._directiveCache.clear();
  19904. this._nonNormalizedDirectiveCache.clear();
  19905. this._summaryCache.clear();
  19906. this._pipeCache.clear();
  19907. this._ngModuleCache.clear();
  19908. this._ngModuleOfTypes.clear();
  19909. this._directiveNormalizer.clearCache();
  19910. };
  19911. CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
  19912. var delegate = null;
  19913. var proxyClass = function () {
  19914. if (!delegate) {
  19915. throw new Error("Illegal state: Class " + name + " for type " + stringify(baseType) + " is not compiled yet!");
  19916. }
  19917. return delegate.apply(this, arguments);
  19918. };
  19919. proxyClass.setDelegate = function (d) {
  19920. delegate = d;
  19921. proxyClass.prototype = d.prototype;
  19922. };
  19923. // Make stringify work correctly
  19924. proxyClass.overriddenName = name;
  19925. return proxyClass;
  19926. };
  19927. CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
  19928. if (dirType instanceof StaticSymbol) {
  19929. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
  19930. }
  19931. else {
  19932. return this._createProxyClass(dirType, name);
  19933. }
  19934. };
  19935. CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
  19936. return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
  19937. };
  19938. CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
  19939. return this.getGeneratedClass(dirType, hostViewClassName(dirType));
  19940. };
  19941. CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
  19942. var name = identifierName({ reference: dirType }) + "_Host";
  19943. if (dirType instanceof StaticSymbol) {
  19944. return this._staticSymbolCache.get(dirType.filePath, name);
  19945. }
  19946. return this._createProxyClass(dirType, name);
  19947. };
  19948. CompileMetadataResolver.prototype.getRendererType = function (dirType) {
  19949. if (dirType instanceof StaticSymbol) {
  19950. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
  19951. }
  19952. else {
  19953. // returning an object as proxy,
  19954. // that we fill later during runtime compilation.
  19955. return {};
  19956. }
  19957. };
  19958. CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
  19959. if (dirType instanceof StaticSymbol) {
  19960. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
  19961. }
  19962. else {
  19963. var hostView = this.getHostComponentViewClass(dirType);
  19964. // Note: ngContentSelectors will be filled later once the template is
  19965. // loaded.
  19966. var createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
  19967. return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
  19968. }
  19969. };
  19970. CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
  19971. var _a;
  19972. if (!(factory instanceof StaticSymbol)) {
  19973. (_a = factory.ngContentSelectors).push.apply(_a, __spread(ngContentSelectors));
  19974. }
  19975. };
  19976. CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
  19977. var typeSummary = this._summaryCache.get(type);
  19978. if (!typeSummary) {
  19979. var summary = this._summaryResolver.resolveSummary(type);
  19980. typeSummary = summary ? summary.type : null;
  19981. this._summaryCache.set(type, typeSummary || null);
  19982. }
  19983. return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
  19984. };
  19985. CompileMetadataResolver.prototype.getHostComponentMetadata = function (compMeta, hostViewType) {
  19986. var hostType = this.getHostComponentType(compMeta.type.reference);
  19987. if (!hostViewType) {
  19988. hostViewType = this.getHostComponentViewClass(hostType);
  19989. }
  19990. // Note: ! is ok here as this method should only be called with normalized directive
  19991. // metadata, which always fills in the selector.
  19992. var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
  19993. var templateUrl = '';
  19994. var htmlAst = this._htmlParser.parse(template, templateUrl);
  19995. return CompileDirectiveMetadata.create({
  19996. isHost: true,
  19997. type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
  19998. template: new CompileTemplateMetadata({
  19999. encapsulation: ViewEncapsulation.None,
  20000. template: template,
  20001. templateUrl: templateUrl,
  20002. htmlAst: htmlAst,
  20003. styles: [],
  20004. styleUrls: [],
  20005. ngContentSelectors: [],
  20006. animations: [],
  20007. isInline: true,
  20008. externalStylesheets: [],
  20009. interpolation: null,
  20010. preserveWhitespaces: false,
  20011. }),
  20012. exportAs: null,
  20013. changeDetection: ChangeDetectionStrategy.Default,
  20014. inputs: [],
  20015. outputs: [],
  20016. host: {},
  20017. isComponent: true,
  20018. selector: '*',
  20019. providers: [],
  20020. viewProviders: [],
  20021. queries: [],
  20022. guards: {},
  20023. viewQueries: [],
  20024. componentViewType: hostViewType,
  20025. rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
  20026. entryComponents: [],
  20027. componentFactory: null
  20028. });
  20029. };
  20030. CompileMetadataResolver.prototype.loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
  20031. var _this = this;
  20032. if (this._directiveCache.has(directiveType)) {
  20033. return null;
  20034. }
  20035. directiveType = resolveForwardRef(directiveType);
  20036. var _a = this.getNonNormalizedDirectiveMetadata(directiveType), annotation = _a.annotation, metadata = _a.metadata;
  20037. var createDirectiveMetadata = function (templateMetadata) {
  20038. var normalizedDirMeta = new CompileDirectiveMetadata({
  20039. isHost: false,
  20040. type: metadata.type,
  20041. isComponent: metadata.isComponent,
  20042. selector: metadata.selector,
  20043. exportAs: metadata.exportAs,
  20044. changeDetection: metadata.changeDetection,
  20045. inputs: metadata.inputs,
  20046. outputs: metadata.outputs,
  20047. hostListeners: metadata.hostListeners,
  20048. hostProperties: metadata.hostProperties,
  20049. hostAttributes: metadata.hostAttributes,
  20050. providers: metadata.providers,
  20051. viewProviders: metadata.viewProviders,
  20052. queries: metadata.queries,
  20053. guards: metadata.guards,
  20054. viewQueries: metadata.viewQueries,
  20055. entryComponents: metadata.entryComponents,
  20056. componentViewType: metadata.componentViewType,
  20057. rendererType: metadata.rendererType,
  20058. componentFactory: metadata.componentFactory,
  20059. template: templateMetadata
  20060. });
  20061. if (templateMetadata) {
  20062. _this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
  20063. }
  20064. _this._directiveCache.set(directiveType, normalizedDirMeta);
  20065. _this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
  20066. return null;
  20067. };
  20068. if (metadata.isComponent) {
  20069. var template = metadata.template;
  20070. var templateMeta = this._directiveNormalizer.normalizeTemplate({
  20071. ngModuleType: ngModuleType,
  20072. componentType: directiveType,
  20073. moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
  20074. encapsulation: template.encapsulation,
  20075. template: template.template,
  20076. templateUrl: template.templateUrl,
  20077. styles: template.styles,
  20078. styleUrls: template.styleUrls,
  20079. animations: template.animations,
  20080. interpolation: template.interpolation,
  20081. preserveWhitespaces: template.preserveWhitespaces
  20082. });
  20083. if (isPromise(templateMeta) && isSync) {
  20084. this._reportError(componentStillLoadingError(directiveType), directiveType);
  20085. return null;
  20086. }
  20087. return SyncAsync.then(templateMeta, createDirectiveMetadata);
  20088. }
  20089. else {
  20090. // directive
  20091. createDirectiveMetadata(null);
  20092. return null;
  20093. }
  20094. };
  20095. CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
  20096. var _this = this;
  20097. directiveType = resolveForwardRef(directiveType);
  20098. if (!directiveType) {
  20099. return null;
  20100. }
  20101. var cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
  20102. if (cacheEntry) {
  20103. return cacheEntry;
  20104. }
  20105. var dirMeta = this._directiveResolver.resolve(directiveType, false);
  20106. if (!dirMeta) {
  20107. return null;
  20108. }
  20109. var nonNormalizedTemplateMetadata = undefined;
  20110. if (createComponent.isTypeOf(dirMeta)) {
  20111. // component
  20112. var compMeta = dirMeta;
  20113. assertArrayOfStrings('styles', compMeta.styles);
  20114. assertArrayOfStrings('styleUrls', compMeta.styleUrls);
  20115. assertInterpolationSymbols('interpolation', compMeta.interpolation);
  20116. var animations = compMeta.animations;
  20117. nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
  20118. encapsulation: noUndefined(compMeta.encapsulation),
  20119. template: noUndefined(compMeta.template),
  20120. templateUrl: noUndefined(compMeta.templateUrl),
  20121. htmlAst: null,
  20122. styles: compMeta.styles || [],
  20123. styleUrls: compMeta.styleUrls || [],
  20124. animations: animations || [],
  20125. interpolation: noUndefined(compMeta.interpolation),
  20126. isInline: !!compMeta.template,
  20127. externalStylesheets: [],
  20128. ngContentSelectors: [],
  20129. preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
  20130. });
  20131. }
  20132. var changeDetectionStrategy = null;
  20133. var viewProviders = [];
  20134. var entryComponentMetadata = [];
  20135. var selector = dirMeta.selector;
  20136. if (createComponent.isTypeOf(dirMeta)) {
  20137. // Component
  20138. var compMeta = dirMeta;
  20139. changeDetectionStrategy = compMeta.changeDetection;
  20140. if (compMeta.viewProviders) {
  20141. viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  20142. }
  20143. if (compMeta.entryComponents) {
  20144. entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
  20145. .map(function (type) { return _this._getEntryComponentMetadata(type); })
  20146. .concat(entryComponentMetadata);
  20147. }
  20148. if (!selector) {
  20149. selector = this._schemaRegistry.getDefaultComponentElementName();
  20150. }
  20151. }
  20152. else {
  20153. // Directive
  20154. if (!selector) {
  20155. this._reportError(syntaxError("Directive " + stringifyType(directiveType) + " has no selector, please add it!"), directiveType);
  20156. selector = 'error';
  20157. }
  20158. }
  20159. var providers = [];
  20160. if (dirMeta.providers != null) {
  20161. providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  20162. }
  20163. var queries = [];
  20164. var viewQueries = [];
  20165. if (dirMeta.queries != null) {
  20166. queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
  20167. viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
  20168. }
  20169. var metadata = CompileDirectiveMetadata.create({
  20170. isHost: false,
  20171. selector: selector,
  20172. exportAs: noUndefined(dirMeta.exportAs),
  20173. isComponent: !!nonNormalizedTemplateMetadata,
  20174. type: this._getTypeMetadata(directiveType),
  20175. template: nonNormalizedTemplateMetadata,
  20176. changeDetection: changeDetectionStrategy,
  20177. inputs: dirMeta.inputs || [],
  20178. outputs: dirMeta.outputs || [],
  20179. host: dirMeta.host || {},
  20180. providers: providers || [],
  20181. viewProviders: viewProviders || [],
  20182. queries: queries || [],
  20183. guards: dirMeta.guards || {},
  20184. viewQueries: viewQueries || [],
  20185. entryComponents: entryComponentMetadata,
  20186. componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
  20187. null,
  20188. rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
  20189. componentFactory: null
  20190. });
  20191. if (nonNormalizedTemplateMetadata) {
  20192. metadata.componentFactory =
  20193. this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
  20194. }
  20195. cacheEntry = { metadata: metadata, annotation: dirMeta };
  20196. this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
  20197. return cacheEntry;
  20198. };
  20199. /**
  20200. * Gets the metadata for the given directive.
  20201. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  20202. */
  20203. CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
  20204. var dirMeta = this._directiveCache.get(directiveType);
  20205. if (!dirMeta) {
  20206. this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
  20207. }
  20208. return dirMeta;
  20209. };
  20210. CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
  20211. var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
  20212. if (!dirSummary) {
  20213. this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
  20214. }
  20215. return dirSummary;
  20216. };
  20217. CompileMetadataResolver.prototype.isDirective = function (type) {
  20218. return !!this._loadSummary(type, CompileSummaryKind.Directive) ||
  20219. this._directiveResolver.isDirective(type);
  20220. };
  20221. CompileMetadataResolver.prototype.isPipe = function (type) {
  20222. return !!this._loadSummary(type, CompileSummaryKind.Pipe) ||
  20223. this._pipeResolver.isPipe(type);
  20224. };
  20225. CompileMetadataResolver.prototype.isNgModule = function (type) {
  20226. return !!this._loadSummary(type, CompileSummaryKind.NgModule) ||
  20227. this._ngModuleResolver.isNgModule(type);
  20228. };
  20229. CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType, alreadyCollecting) {
  20230. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  20231. var moduleSummary = this._loadSummary(moduleType, CompileSummaryKind.NgModule);
  20232. if (!moduleSummary) {
  20233. var moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
  20234. moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
  20235. if (moduleSummary) {
  20236. this._summaryCache.set(moduleType, moduleSummary);
  20237. }
  20238. }
  20239. return moduleSummary;
  20240. };
  20241. /**
  20242. * Loads the declared directives and pipes of an NgModule.
  20243. */
  20244. CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
  20245. var _this = this;
  20246. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20247. var ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
  20248. var loading = [];
  20249. if (ngModule) {
  20250. ngModule.declaredDirectives.forEach(function (id) {
  20251. var promise = _this.loadDirectiveMetadata(moduleType, id.reference, isSync);
  20252. if (promise) {
  20253. loading.push(promise);
  20254. }
  20255. });
  20256. ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
  20257. }
  20258. return Promise.all(loading);
  20259. };
  20260. CompileMetadataResolver.prototype.getShallowModuleMetadata = function (moduleType) {
  20261. var compileMeta = this._shallowModuleCache.get(moduleType);
  20262. if (compileMeta) {
  20263. return compileMeta;
  20264. }
  20265. var ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
  20266. compileMeta = {
  20267. type: this._getTypeMetadata(moduleType),
  20268. rawExports: ngModuleMeta.exports,
  20269. rawImports: ngModuleMeta.imports,
  20270. rawProviders: ngModuleMeta.providers,
  20271. };
  20272. this._shallowModuleCache.set(moduleType, compileMeta);
  20273. return compileMeta;
  20274. };
  20275. CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound, alreadyCollecting) {
  20276. var _this = this;
  20277. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20278. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  20279. moduleType = resolveForwardRef(moduleType);
  20280. var compileMeta = this._ngModuleCache.get(moduleType);
  20281. if (compileMeta) {
  20282. return compileMeta;
  20283. }
  20284. var meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
  20285. if (!meta) {
  20286. return null;
  20287. }
  20288. var declaredDirectives = [];
  20289. var exportedNonModuleIdentifiers = [];
  20290. var declaredPipes = [];
  20291. var importedModules = [];
  20292. var exportedModules = [];
  20293. var providers = [];
  20294. var entryComponents = [];
  20295. var bootstrapComponents = [];
  20296. var schemas = [];
  20297. if (meta.imports) {
  20298. flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
  20299. var importedModuleType = undefined;
  20300. if (isValidType(importedType)) {
  20301. importedModuleType = importedType;
  20302. }
  20303. else if (importedType && importedType.ngModule) {
  20304. var moduleWithProviders = importedType;
  20305. importedModuleType = moduleWithProviders.ngModule;
  20306. if (moduleWithProviders.providers) {
  20307. providers.push.apply(providers, __spread(_this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType)));
  20308. }
  20309. }
  20310. if (importedModuleType) {
  20311. if (_this._checkSelfImport(moduleType, importedModuleType))
  20312. return;
  20313. if (!alreadyCollecting)
  20314. alreadyCollecting = new Set();
  20315. if (alreadyCollecting.has(importedModuleType)) {
  20316. _this._reportError(syntaxError(_this._getTypeDescriptor(importedModuleType) + " '" + stringifyType(importedType) + "' is imported recursively by the module '" + stringifyType(moduleType) + "'."), moduleType);
  20317. return;
  20318. }
  20319. alreadyCollecting.add(importedModuleType);
  20320. var importedModuleSummary = _this.getNgModuleSummary(importedModuleType, alreadyCollecting);
  20321. alreadyCollecting.delete(importedModuleType);
  20322. if (!importedModuleSummary) {
  20323. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation."), moduleType);
  20324. return;
  20325. }
  20326. importedModules.push(importedModuleSummary);
  20327. }
  20328. else {
  20329. _this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20330. return;
  20331. }
  20332. });
  20333. }
  20334. if (meta.exports) {
  20335. flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
  20336. if (!isValidType(exportedType)) {
  20337. _this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20338. return;
  20339. }
  20340. if (!alreadyCollecting)
  20341. alreadyCollecting = new Set();
  20342. if (alreadyCollecting.has(exportedType)) {
  20343. _this._reportError(syntaxError(_this._getTypeDescriptor(exportedType) + " '" + stringify(exportedType) + "' is exported recursively by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20344. return;
  20345. }
  20346. alreadyCollecting.add(exportedType);
  20347. var exportedModuleSummary = _this.getNgModuleSummary(exportedType, alreadyCollecting);
  20348. alreadyCollecting.delete(exportedType);
  20349. if (exportedModuleSummary) {
  20350. exportedModules.push(exportedModuleSummary);
  20351. }
  20352. else {
  20353. exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
  20354. }
  20355. });
  20356. }
  20357. // Note: This will be modified later, so we rely on
  20358. // getting a new instance every time!
  20359. var transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
  20360. if (meta.declarations) {
  20361. flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
  20362. if (!isValidType(declaredType)) {
  20363. _this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20364. return;
  20365. }
  20366. var declaredIdentifier = _this._getIdentifierMetadata(declaredType);
  20367. if (_this.isDirective(declaredType)) {
  20368. transitiveModule.addDirective(declaredIdentifier);
  20369. declaredDirectives.push(declaredIdentifier);
  20370. _this._addTypeToModule(declaredType, moduleType);
  20371. }
  20372. else if (_this.isPipe(declaredType)) {
  20373. transitiveModule.addPipe(declaredIdentifier);
  20374. transitiveModule.pipes.push(declaredIdentifier);
  20375. declaredPipes.push(declaredIdentifier);
  20376. _this._addTypeToModule(declaredType, moduleType);
  20377. }
  20378. else {
  20379. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
  20380. return;
  20381. }
  20382. });
  20383. }
  20384. var exportedDirectives = [];
  20385. var exportedPipes = [];
  20386. exportedNonModuleIdentifiers.forEach(function (exportedId) {
  20387. if (transitiveModule.directivesSet.has(exportedId.reference)) {
  20388. exportedDirectives.push(exportedId);
  20389. transitiveModule.addExportedDirective(exportedId);
  20390. }
  20391. else if (transitiveModule.pipesSet.has(exportedId.reference)) {
  20392. exportedPipes.push(exportedId);
  20393. transitiveModule.addExportedPipe(exportedId);
  20394. }
  20395. else {
  20396. _this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
  20397. return;
  20398. }
  20399. });
  20400. // The providers of the module have to go last
  20401. // so that they overwrite any other provider we already added.
  20402. if (meta.providers) {
  20403. providers.push.apply(providers, __spread(this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType)));
  20404. }
  20405. if (meta.entryComponents) {
  20406. entryComponents.push.apply(entryComponents, __spread(flattenAndDedupeArray(meta.entryComponents)
  20407. .map(function (type) { return _this._getEntryComponentMetadata(type); })));
  20408. }
  20409. if (meta.bootstrap) {
  20410. flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
  20411. if (!isValidType(type)) {
  20412. _this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
  20413. return;
  20414. }
  20415. bootstrapComponents.push(_this._getIdentifierMetadata(type));
  20416. });
  20417. }
  20418. entryComponents.push.apply(entryComponents, __spread(bootstrapComponents.map(function (type) { return _this._getEntryComponentMetadata(type.reference); })));
  20419. if (meta.schemas) {
  20420. schemas.push.apply(schemas, __spread(flattenAndDedupeArray(meta.schemas)));
  20421. }
  20422. compileMeta = new CompileNgModuleMetadata({
  20423. type: this._getTypeMetadata(moduleType),
  20424. providers: providers,
  20425. entryComponents: entryComponents,
  20426. bootstrapComponents: bootstrapComponents,
  20427. schemas: schemas,
  20428. declaredDirectives: declaredDirectives,
  20429. exportedDirectives: exportedDirectives,
  20430. declaredPipes: declaredPipes,
  20431. exportedPipes: exportedPipes,
  20432. importedModules: importedModules,
  20433. exportedModules: exportedModules,
  20434. transitiveModule: transitiveModule,
  20435. id: meta.id || null,
  20436. });
  20437. entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
  20438. providers.forEach(function (provider) { return transitiveModule.addProvider(provider, compileMeta.type); });
  20439. transitiveModule.addModule(compileMeta.type);
  20440. this._ngModuleCache.set(moduleType, compileMeta);
  20441. return compileMeta;
  20442. };
  20443. CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
  20444. if (moduleType === importedModuleType) {
  20445. this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
  20446. return true;
  20447. }
  20448. return false;
  20449. };
  20450. CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
  20451. if (isValidType(type)) {
  20452. if (this.isDirective(type)) {
  20453. return 'directive';
  20454. }
  20455. if (this.isPipe(type)) {
  20456. return 'pipe';
  20457. }
  20458. if (this.isNgModule(type)) {
  20459. return 'module';
  20460. }
  20461. }
  20462. if (type.provide) {
  20463. return 'provider';
  20464. }
  20465. return 'value';
  20466. };
  20467. CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
  20468. var oldModule = this._ngModuleOfTypes.get(type);
  20469. if (oldModule && oldModule !== moduleType) {
  20470. this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
  20471. ("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
  20472. ("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
  20473. return;
  20474. }
  20475. this._ngModuleOfTypes.set(type, moduleType);
  20476. };
  20477. CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
  20478. // collect `providers` / `entryComponents` from all imported and all exported modules
  20479. var result = new TransitiveCompileNgModuleMetadata();
  20480. var modulesByToken = new Map();
  20481. importedModules.concat(exportedModules).forEach(function (modSummary) {
  20482. modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
  20483. modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
  20484. var addedTokens = new Set();
  20485. modSummary.providers.forEach(function (entry) {
  20486. var tokenRef = tokenReference(entry.provider.token);
  20487. var prevModules = modulesByToken.get(tokenRef);
  20488. if (!prevModules) {
  20489. prevModules = new Set();
  20490. modulesByToken.set(tokenRef, prevModules);
  20491. }
  20492. var moduleRef = entry.module.reference;
  20493. // Note: the providers of one module may still contain multiple providers
  20494. // per token (e.g. for multi providers), and we need to preserve these.
  20495. if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
  20496. prevModules.add(moduleRef);
  20497. addedTokens.add(tokenRef);
  20498. result.addProvider(entry.provider, entry.module);
  20499. }
  20500. });
  20501. });
  20502. exportedModules.forEach(function (modSummary) {
  20503. modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
  20504. modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
  20505. });
  20506. importedModules.forEach(function (modSummary) {
  20507. modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
  20508. modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
  20509. });
  20510. return result;
  20511. };
  20512. CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
  20513. type = resolveForwardRef(type);
  20514. return { reference: type };
  20515. };
  20516. CompileMetadataResolver.prototype.isInjectable = function (type) {
  20517. var annotations = this._reflector.tryAnnotations(type);
  20518. return annotations.some(function (ann) { return createInjectable.isTypeOf(ann); });
  20519. };
  20520. CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
  20521. return {
  20522. summaryKind: CompileSummaryKind.Injectable,
  20523. type: this._getTypeMetadata(type, null, false)
  20524. };
  20525. };
  20526. CompileMetadataResolver.prototype.getInjectableMetadata = function (type, dependencies, throwOnUnknownDeps) {
  20527. if (dependencies === void 0) { dependencies = null; }
  20528. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  20529. var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
  20530. var typeMetadata = typeSummary ?
  20531. typeSummary.type :
  20532. this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
  20533. var annotations = this._reflector.annotations(type).filter(function (ann) { return createInjectable.isTypeOf(ann); });
  20534. if (annotations.length === 0) {
  20535. return null;
  20536. }
  20537. var meta = annotations[annotations.length - 1];
  20538. return {
  20539. symbol: type,
  20540. type: typeMetadata,
  20541. providedIn: meta.providedIn,
  20542. useValue: meta.useValue,
  20543. useClass: meta.useClass,
  20544. useExisting: meta.useExisting,
  20545. useFactory: meta.useFactory,
  20546. deps: meta.deps,
  20547. };
  20548. };
  20549. CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
  20550. if (dependencies === void 0) { dependencies = null; }
  20551. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  20552. var identifier = this._getIdentifierMetadata(type);
  20553. return {
  20554. reference: identifier.reference,
  20555. diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
  20556. lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
  20557. };
  20558. };
  20559. CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
  20560. if (dependencies === void 0) { dependencies = null; }
  20561. factory = resolveForwardRef(factory);
  20562. return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
  20563. };
  20564. /**
  20565. * Gets the metadata for the given pipe.
  20566. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  20567. */
  20568. CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
  20569. var pipeMeta = this._pipeCache.get(pipeType);
  20570. if (!pipeMeta) {
  20571. this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
  20572. }
  20573. return pipeMeta || null;
  20574. };
  20575. CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
  20576. var pipeSummary = this._loadSummary(pipeType, CompileSummaryKind.Pipe);
  20577. if (!pipeSummary) {
  20578. this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
  20579. }
  20580. return pipeSummary;
  20581. };
  20582. CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
  20583. var pipeMeta = this._pipeCache.get(pipeType);
  20584. if (!pipeMeta) {
  20585. pipeMeta = this._loadPipeMetadata(pipeType);
  20586. }
  20587. return pipeMeta;
  20588. };
  20589. CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
  20590. pipeType = resolveForwardRef(pipeType);
  20591. var pipeAnnotation = this._pipeResolver.resolve(pipeType);
  20592. var pipeMeta = new CompilePipeMetadata({
  20593. type: this._getTypeMetadata(pipeType),
  20594. name: pipeAnnotation.name,
  20595. pure: !!pipeAnnotation.pure
  20596. });
  20597. this._pipeCache.set(pipeType, pipeMeta);
  20598. this._summaryCache.set(pipeType, pipeMeta.toSummary());
  20599. return pipeMeta;
  20600. };
  20601. CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
  20602. var _this = this;
  20603. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  20604. var hasUnknownDeps = false;
  20605. var params = dependencies || this._reflector.parameters(typeOrFunc) || [];
  20606. var dependenciesMetadata = params.map(function (param) {
  20607. var isAttribute = false;
  20608. var isHost = false;
  20609. var isSelf = false;
  20610. var isSkipSelf = false;
  20611. var isOptional = false;
  20612. var token = null;
  20613. if (Array.isArray(param)) {
  20614. param.forEach(function (paramEntry) {
  20615. if (createHost.isTypeOf(paramEntry)) {
  20616. isHost = true;
  20617. }
  20618. else if (createSelf.isTypeOf(paramEntry)) {
  20619. isSelf = true;
  20620. }
  20621. else if (createSkipSelf.isTypeOf(paramEntry)) {
  20622. isSkipSelf = true;
  20623. }
  20624. else if (createOptional.isTypeOf(paramEntry)) {
  20625. isOptional = true;
  20626. }
  20627. else if (createAttribute.isTypeOf(paramEntry)) {
  20628. isAttribute = true;
  20629. token = paramEntry.attributeName;
  20630. }
  20631. else if (createInject.isTypeOf(paramEntry)) {
  20632. token = paramEntry.token;
  20633. }
  20634. else if (createInjectionToken.isTypeOf(paramEntry) ||
  20635. paramEntry instanceof StaticSymbol) {
  20636. token = paramEntry;
  20637. }
  20638. else if (isValidType(paramEntry) && token == null) {
  20639. token = paramEntry;
  20640. }
  20641. });
  20642. }
  20643. else {
  20644. token = param;
  20645. }
  20646. if (token == null) {
  20647. hasUnknownDeps = true;
  20648. return {};
  20649. }
  20650. return {
  20651. isAttribute: isAttribute,
  20652. isHost: isHost,
  20653. isSelf: isSelf,
  20654. isSkipSelf: isSkipSelf,
  20655. isOptional: isOptional,
  20656. token: _this._getTokenMetadata(token)
  20657. };
  20658. });
  20659. if (hasUnknownDeps) {
  20660. var depsTokens = dependenciesMetadata.map(function (dep) { return dep.token ? stringifyType(dep.token) : '?'; }).join(', ');
  20661. var message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
  20662. if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
  20663. this._reportError(syntaxError(message), typeOrFunc);
  20664. }
  20665. else {
  20666. this._console.warn("Warning: " + message + " This will become an error in Angular v6.x");
  20667. }
  20668. }
  20669. return dependenciesMetadata;
  20670. };
  20671. CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
  20672. token = resolveForwardRef(token);
  20673. var compileToken;
  20674. if (typeof token === 'string') {
  20675. compileToken = { value: token };
  20676. }
  20677. else {
  20678. compileToken = { identifier: { reference: token } };
  20679. }
  20680. return compileToken;
  20681. };
  20682. CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
  20683. var _this = this;
  20684. if (compileProviders === void 0) { compileProviders = []; }
  20685. providers.forEach(function (provider, providerIdx) {
  20686. if (Array.isArray(provider)) {
  20687. _this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
  20688. }
  20689. else {
  20690. provider = resolveForwardRef(provider);
  20691. var providerMeta = undefined;
  20692. if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
  20693. _this._validateProvider(provider);
  20694. providerMeta = new ProviderMeta(provider.provide, provider);
  20695. }
  20696. else if (isValidType(provider)) {
  20697. providerMeta = new ProviderMeta(provider, { useClass: provider });
  20698. }
  20699. else if (provider === void 0) {
  20700. _this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."));
  20701. return;
  20702. }
  20703. else {
  20704. var providersInfo = providers.reduce(function (soFar, seenProvider, seenProviderIdx) {
  20705. if (seenProviderIdx < providerIdx) {
  20706. soFar.push("" + stringifyType(seenProvider));
  20707. }
  20708. else if (seenProviderIdx == providerIdx) {
  20709. soFar.push("?" + stringifyType(seenProvider) + "?");
  20710. }
  20711. else if (seenProviderIdx == providerIdx + 1) {
  20712. soFar.push('...');
  20713. }
  20714. return soFar;
  20715. }, [])
  20716. .join(', ');
  20717. _this._reportError(syntaxError("Invalid " + (debugInfo ? debugInfo : 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
  20718. return;
  20719. }
  20720. if (providerMeta.token ===
  20721. _this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
  20722. targetEntryComponents.push.apply(targetEntryComponents, __spread(_this._getEntryComponentsFromProvider(providerMeta, type)));
  20723. }
  20724. else {
  20725. compileProviders.push(_this.getProviderMetadata(providerMeta));
  20726. }
  20727. }
  20728. });
  20729. return compileProviders;
  20730. };
  20731. CompileMetadataResolver.prototype._validateProvider = function (provider) {
  20732. if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
  20733. this._reportError(syntaxError("Invalid provider for " + stringifyType(provider.provide) + ". useClass cannot be " + provider.useClass + ".\n Usually it happens when:\n 1. There's a circular dependency (might be caused by using index.ts (barrel) files).\n 2. Class was used before it was declared. Use forwardRef in this case."));
  20734. }
  20735. };
  20736. CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
  20737. var _this = this;
  20738. var components = [];
  20739. var collectedIdentifiers = [];
  20740. if (provider.useFactory || provider.useExisting || provider.useClass) {
  20741. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
  20742. return [];
  20743. }
  20744. if (!provider.multi) {
  20745. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
  20746. return [];
  20747. }
  20748. extractIdentifiers(provider.useValue, collectedIdentifiers);
  20749. collectedIdentifiers.forEach(function (identifier) {
  20750. var entry = _this._getEntryComponentMetadata(identifier.reference, false);
  20751. if (entry) {
  20752. components.push(entry);
  20753. }
  20754. });
  20755. return components;
  20756. };
  20757. CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
  20758. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20759. var dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
  20760. if (dirMeta && dirMeta.metadata.isComponent) {
  20761. return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
  20762. }
  20763. var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
  20764. if (dirSummary && dirSummary.isComponent) {
  20765. return { componentType: dirType, componentFactory: dirSummary.componentFactory };
  20766. }
  20767. if (throwIfNotFound) {
  20768. throw syntaxError(dirType.name + " cannot be used as an entry component.");
  20769. }
  20770. return null;
  20771. };
  20772. CompileMetadataResolver.prototype._getInjectableTypeMetadata = function (type, dependencies) {
  20773. if (dependencies === void 0) { dependencies = null; }
  20774. var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
  20775. if (typeSummary) {
  20776. return typeSummary.type;
  20777. }
  20778. return this._getTypeMetadata(type, dependencies);
  20779. };
  20780. CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
  20781. var compileDeps = undefined;
  20782. var compileTypeMetadata = null;
  20783. var compileFactoryMetadata = null;
  20784. var token = this._getTokenMetadata(provider.token);
  20785. if (provider.useClass) {
  20786. compileTypeMetadata =
  20787. this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
  20788. compileDeps = compileTypeMetadata.diDeps;
  20789. if (provider.token === provider.useClass) {
  20790. // use the compileTypeMetadata as it contains information about lifecycleHooks...
  20791. token = { identifier: compileTypeMetadata };
  20792. }
  20793. }
  20794. else if (provider.useFactory) {
  20795. compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
  20796. compileDeps = compileFactoryMetadata.diDeps;
  20797. }
  20798. return {
  20799. token: token,
  20800. useClass: compileTypeMetadata,
  20801. useValue: provider.useValue,
  20802. useFactory: compileFactoryMetadata,
  20803. useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
  20804. deps: compileDeps,
  20805. multi: provider.multi
  20806. };
  20807. };
  20808. CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
  20809. var _this = this;
  20810. var res = [];
  20811. Object.keys(queries).forEach(function (propertyName) {
  20812. var query = queries[propertyName];
  20813. if (query.isViewQuery === isViewQuery) {
  20814. res.push(_this._getQueryMetadata(query, propertyName, directiveType));
  20815. }
  20816. });
  20817. return res;
  20818. };
  20819. CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); };
  20820. CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
  20821. var _this = this;
  20822. var selectors;
  20823. if (typeof q.selector === 'string') {
  20824. selectors =
  20825. this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
  20826. }
  20827. else {
  20828. if (!q.selector) {
  20829. this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
  20830. selectors = [];
  20831. }
  20832. else {
  20833. selectors = [this._getTokenMetadata(q.selector)];
  20834. }
  20835. }
  20836. return {
  20837. selectors: selectors,
  20838. first: q.first,
  20839. descendants: q.descendants, propertyName: propertyName,
  20840. read: q.read ? this._getTokenMetadata(q.read) : null,
  20841. static: q.static
  20842. };
  20843. };
  20844. CompileMetadataResolver.prototype._reportError = function (error, type, otherType) {
  20845. if (this._errorCollector) {
  20846. this._errorCollector(error, type);
  20847. if (otherType) {
  20848. this._errorCollector(error, otherType);
  20849. }
  20850. }
  20851. else {
  20852. throw error;
  20853. }
  20854. };
  20855. return CompileMetadataResolver;
  20856. }());
  20857. function flattenArray(tree, out) {
  20858. if (out === void 0) { out = []; }
  20859. if (tree) {
  20860. for (var i = 0; i < tree.length; i++) {
  20861. var item = resolveForwardRef(tree[i]);
  20862. if (Array.isArray(item)) {
  20863. flattenArray(item, out);
  20864. }
  20865. else {
  20866. out.push(item);
  20867. }
  20868. }
  20869. }
  20870. return out;
  20871. }
  20872. function dedupeArray(array) {
  20873. if (array) {
  20874. return Array.from(new Set(array));
  20875. }
  20876. return [];
  20877. }
  20878. function flattenAndDedupeArray(tree) {
  20879. return dedupeArray(flattenArray(tree));
  20880. }
  20881. function isValidType(value) {
  20882. return (value instanceof StaticSymbol) || (value instanceof Type);
  20883. }
  20884. function extractIdentifiers(value, targetIdentifiers) {
  20885. visitValue(value, new _CompileValueConverter(), targetIdentifiers);
  20886. }
  20887. var _CompileValueConverter = /** @class */ (function (_super) {
  20888. __extends(_CompileValueConverter, _super);
  20889. function _CompileValueConverter() {
  20890. return _super !== null && _super.apply(this, arguments) || this;
  20891. }
  20892. _CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
  20893. targetIdentifiers.push({ reference: value });
  20894. };
  20895. return _CompileValueConverter;
  20896. }(ValueTransformer));
  20897. function stringifyType(type) {
  20898. if (type instanceof StaticSymbol) {
  20899. return type.name + " in " + type.filePath;
  20900. }
  20901. else {
  20902. return stringify(type);
  20903. }
  20904. }
  20905. /**
  20906. * Indicates that a component is still being loaded in a synchronous compile.
  20907. */
  20908. function componentStillLoadingError(compType) {
  20909. var error = Error("Can't compile synchronously as " + stringify(compType) + " is still being loaded!");
  20910. error[ERROR_COMPONENT_TYPE] = compType;
  20911. return error;
  20912. }
  20913. /**
  20914. * @license
  20915. * Copyright Google Inc. All Rights Reserved.
  20916. *
  20917. * Use of this source code is governed by an MIT-style license that can be
  20918. * found in the LICENSE file at https://angular.io/license
  20919. */
  20920. /**
  20921. * @license
  20922. * Copyright Google Inc. All Rights Reserved.
  20923. *
  20924. * Use of this source code is governed by an MIT-style license that can be
  20925. * found in the LICENSE file at https://angular.io/license
  20926. */
  20927. var LOG_VAR = variable('_l');
  20928. /**
  20929. * @license
  20930. * Copyright Google Inc. All Rights Reserved.
  20931. *
  20932. * Use of this source code is governed by an MIT-style license that can be
  20933. * found in the LICENSE file at https://angular.io/license
  20934. */
  20935. /**
  20936. * Resolves types to {@link NgModule}.
  20937. */
  20938. var NgModuleResolver = /** @class */ (function () {
  20939. function NgModuleResolver(_reflector) {
  20940. this._reflector = _reflector;
  20941. }
  20942. NgModuleResolver.prototype.isNgModule = function (type) { return this._reflector.annotations(type).some(createNgModule.isTypeOf); };
  20943. NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
  20944. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20945. var ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
  20946. if (ngModuleMeta) {
  20947. return ngModuleMeta;
  20948. }
  20949. else {
  20950. if (throwIfNotFound) {
  20951. throw new Error("No NgModule metadata found for '" + stringify(type) + "'.");
  20952. }
  20953. return null;
  20954. }
  20955. };
  20956. return NgModuleResolver;
  20957. }());
  20958. /**
  20959. * @license
  20960. * Copyright Google Inc. All Rights Reserved.
  20961. *
  20962. * Use of this source code is governed by an MIT-style license that can be
  20963. * found in the LICENSE file at https://angular.io/license
  20964. */
  20965. var _TsEmitterVisitor = /** @class */ (function (_super) {
  20966. __extends(_TsEmitterVisitor, _super);
  20967. function _TsEmitterVisitor(referenceFilter, importFilter) {
  20968. var _this = _super.call(this, false) || this;
  20969. _this.referenceFilter = referenceFilter;
  20970. _this.importFilter = importFilter;
  20971. _this.typeExpression = 0;
  20972. _this.importsWithPrefixes = new Map();
  20973. _this.reexports = new Map();
  20974. return _this;
  20975. }
  20976. _TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
  20977. if (defaultType === void 0) { defaultType = 'any'; }
  20978. if (t) {
  20979. this.typeExpression++;
  20980. t.visitType(this, ctx);
  20981. this.typeExpression--;
  20982. }
  20983. else {
  20984. ctx.print(null, defaultType);
  20985. }
  20986. };
  20987. _TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  20988. var value = ast.value;
  20989. if (value == null && ast.type != INFERRED_TYPE) {
  20990. ctx.print(ast, "(" + value + " as any)");
  20991. return null;
  20992. }
  20993. return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
  20994. };
  20995. // Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
  20996. // In SNC mode, [] have the type never[], so we cast here to any[].
  20997. // TODO: narrow the cast to a more explicit type, or use a pattern that does not
  20998. // start with [].concat. see https://github.com/angular/angular/pull/11846
  20999. _TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  21000. if (ast.entries.length === 0) {
  21001. ctx.print(ast, '(');
  21002. }
  21003. var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
  21004. if (ast.entries.length === 0) {
  21005. ctx.print(ast, ' as any[])');
  21006. }
  21007. return result;
  21008. };
  21009. _TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  21010. this._visitIdentifier(ast.value, ast.typeParams, ctx);
  21011. return null;
  21012. };
  21013. _TsEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  21014. var result = _super.prototype.visitAssertNotNullExpr.call(this, ast, ctx);
  21015. ctx.print(ast, '!');
  21016. return result;
  21017. };
  21018. _TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  21019. if (stmt.hasModifier(StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
  21020. !stmt.type) {
  21021. // check for a reexport
  21022. var _a = stmt.value.value, name_1 = _a.name, moduleName = _a.moduleName;
  21023. if (moduleName) {
  21024. var reexports = this.reexports.get(moduleName);
  21025. if (!reexports) {
  21026. reexports = [];
  21027. this.reexports.set(moduleName, reexports);
  21028. }
  21029. reexports.push({ name: name_1, as: stmt.name });
  21030. return null;
  21031. }
  21032. }
  21033. if (stmt.hasModifier(StmtModifier.Exported)) {
  21034. ctx.print(stmt, "export ");
  21035. }
  21036. if (stmt.hasModifier(StmtModifier.Final)) {
  21037. ctx.print(stmt, "const");
  21038. }
  21039. else {
  21040. ctx.print(stmt, "var");
  21041. }
  21042. ctx.print(stmt, " " + stmt.name);
  21043. this._printColonType(stmt.type, ctx);
  21044. if (stmt.value) {
  21045. ctx.print(stmt, " = ");
  21046. stmt.value.visitExpression(this, ctx);
  21047. }
  21048. ctx.println(stmt, ";");
  21049. return null;
  21050. };
  21051. _TsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  21052. throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
  21053. };
  21054. _TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  21055. ctx.print(ast, "(<");
  21056. ast.type.visitType(this, ctx);
  21057. ctx.print(ast, ">");
  21058. ast.value.visitExpression(this, ctx);
  21059. ctx.print(ast, ")");
  21060. return null;
  21061. };
  21062. _TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  21063. ctx.print(ast, "new ");
  21064. this.typeExpression++;
  21065. ast.classExpr.visitExpression(this, ctx);
  21066. this.typeExpression--;
  21067. ctx.print(ast, "(");
  21068. this.visitAllExpressions(ast.args, ctx, ',');
  21069. ctx.print(ast, ")");
  21070. return null;
  21071. };
  21072. _TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  21073. var _this = this;
  21074. ctx.pushClass(stmt);
  21075. if (stmt.hasModifier(StmtModifier.Exported)) {
  21076. ctx.print(stmt, "export ");
  21077. }
  21078. ctx.print(stmt, "class " + stmt.name);
  21079. if (stmt.parent != null) {
  21080. ctx.print(stmt, " extends ");
  21081. this.typeExpression++;
  21082. stmt.parent.visitExpression(this, ctx);
  21083. this.typeExpression--;
  21084. }
  21085. ctx.println(stmt, " {");
  21086. ctx.incIndent();
  21087. stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
  21088. if (stmt.constructorMethod != null) {
  21089. this._visitClassConstructor(stmt, ctx);
  21090. }
  21091. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
  21092. stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
  21093. ctx.decIndent();
  21094. ctx.println(stmt, "}");
  21095. ctx.popClass();
  21096. return null;
  21097. };
  21098. _TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
  21099. if (field.hasModifier(StmtModifier.Private)) {
  21100. // comment out as a workaround for #10967
  21101. ctx.print(null, "/*private*/ ");
  21102. }
  21103. if (field.hasModifier(StmtModifier.Static)) {
  21104. ctx.print(null, 'static ');
  21105. }
  21106. ctx.print(null, field.name);
  21107. this._printColonType(field.type, ctx);
  21108. if (field.initializer) {
  21109. ctx.print(null, ' = ');
  21110. field.initializer.visitExpression(this, ctx);
  21111. }
  21112. ctx.println(null, ";");
  21113. };
  21114. _TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
  21115. if (getter.hasModifier(StmtModifier.Private)) {
  21116. ctx.print(null, "private ");
  21117. }
  21118. ctx.print(null, "get " + getter.name + "()");
  21119. this._printColonType(getter.type, ctx);
  21120. ctx.println(null, " {");
  21121. ctx.incIndent();
  21122. this.visitAllStatements(getter.body, ctx);
  21123. ctx.decIndent();
  21124. ctx.println(null, "}");
  21125. };
  21126. _TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  21127. ctx.print(stmt, "constructor(");
  21128. this._visitParams(stmt.constructorMethod.params, ctx);
  21129. ctx.println(stmt, ") {");
  21130. ctx.incIndent();
  21131. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  21132. ctx.decIndent();
  21133. ctx.println(stmt, "}");
  21134. };
  21135. _TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
  21136. if (method.hasModifier(StmtModifier.Private)) {
  21137. ctx.print(null, "private ");
  21138. }
  21139. ctx.print(null, method.name + "(");
  21140. this._visitParams(method.params, ctx);
  21141. ctx.print(null, ")");
  21142. this._printColonType(method.type, ctx, 'void');
  21143. ctx.println(null, " {");
  21144. ctx.incIndent();
  21145. this.visitAllStatements(method.body, ctx);
  21146. ctx.decIndent();
  21147. ctx.println(null, "}");
  21148. };
  21149. _TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  21150. if (ast.name) {
  21151. ctx.print(ast, 'function ');
  21152. ctx.print(ast, ast.name);
  21153. }
  21154. ctx.print(ast, "(");
  21155. this._visitParams(ast.params, ctx);
  21156. ctx.print(ast, ")");
  21157. this._printColonType(ast.type, ctx, 'void');
  21158. if (!ast.name) {
  21159. ctx.print(ast, " => ");
  21160. }
  21161. ctx.println(ast, '{');
  21162. ctx.incIndent();
  21163. this.visitAllStatements(ast.statements, ctx);
  21164. ctx.decIndent();
  21165. ctx.print(ast, "}");
  21166. return null;
  21167. };
  21168. _TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  21169. if (stmt.hasModifier(StmtModifier.Exported)) {
  21170. ctx.print(stmt, "export ");
  21171. }
  21172. ctx.print(stmt, "function " + stmt.name + "(");
  21173. this._visitParams(stmt.params, ctx);
  21174. ctx.print(stmt, ")");
  21175. this._printColonType(stmt.type, ctx, 'void');
  21176. ctx.println(stmt, " {");
  21177. ctx.incIndent();
  21178. this.visitAllStatements(stmt.statements, ctx);
  21179. ctx.decIndent();
  21180. ctx.println(stmt, "}");
  21181. return null;
  21182. };
  21183. _TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  21184. ctx.println(stmt, "try {");
  21185. ctx.incIndent();
  21186. this.visitAllStatements(stmt.bodyStmts, ctx);
  21187. ctx.decIndent();
  21188. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  21189. ctx.incIndent();
  21190. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
  21191. StmtModifier.Final
  21192. ])].concat(stmt.catchStmts);
  21193. this.visitAllStatements(catchStmts, ctx);
  21194. ctx.decIndent();
  21195. ctx.println(stmt, "}");
  21196. return null;
  21197. };
  21198. _TsEmitterVisitor.prototype.visitBuiltinType = function (type, ctx) {
  21199. var typeStr;
  21200. switch (type.name) {
  21201. case BuiltinTypeName.Bool:
  21202. typeStr = 'boolean';
  21203. break;
  21204. case BuiltinTypeName.Dynamic:
  21205. typeStr = 'any';
  21206. break;
  21207. case BuiltinTypeName.Function:
  21208. typeStr = 'Function';
  21209. break;
  21210. case BuiltinTypeName.Number:
  21211. typeStr = 'number';
  21212. break;
  21213. case BuiltinTypeName.Int:
  21214. typeStr = 'number';
  21215. break;
  21216. case BuiltinTypeName.String:
  21217. typeStr = 'string';
  21218. break;
  21219. case BuiltinTypeName.None:
  21220. typeStr = 'never';
  21221. break;
  21222. default:
  21223. throw new Error("Unsupported builtin type " + type.name);
  21224. }
  21225. ctx.print(null, typeStr);
  21226. return null;
  21227. };
  21228. _TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
  21229. var _this = this;
  21230. ast.value.visitExpression(this, ctx);
  21231. if (ast.typeParams !== null) {
  21232. ctx.print(null, '<');
  21233. this.visitAllObjects(function (type) { return _this.visitType(type, ctx); }, ast.typeParams, ctx, ',');
  21234. ctx.print(null, '>');
  21235. }
  21236. return null;
  21237. };
  21238. _TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
  21239. this.visitType(type.of, ctx);
  21240. ctx.print(null, "[]");
  21241. return null;
  21242. };
  21243. _TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
  21244. ctx.print(null, "{[key: string]:");
  21245. this.visitType(type.valueType, ctx);
  21246. ctx.print(null, "}");
  21247. return null;
  21248. };
  21249. _TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  21250. var name;
  21251. switch (method) {
  21252. case BuiltinMethod.ConcatArray:
  21253. name = 'concat';
  21254. break;
  21255. case BuiltinMethod.SubscribeObservable:
  21256. name = 'subscribe';
  21257. break;
  21258. case BuiltinMethod.Bind:
  21259. name = 'bind';
  21260. break;
  21261. default:
  21262. throw new Error("Unknown builtin method: " + method);
  21263. }
  21264. return name;
  21265. };
  21266. _TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  21267. var _this = this;
  21268. this.visitAllObjects(function (param) {
  21269. ctx.print(null, param.name);
  21270. _this._printColonType(param.type, ctx);
  21271. }, params, ctx, ',');
  21272. };
  21273. _TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
  21274. var _this = this;
  21275. var name = value.name, moduleName = value.moduleName;
  21276. if (this.referenceFilter && this.referenceFilter(value)) {
  21277. ctx.print(null, '(null as any)');
  21278. return;
  21279. }
  21280. if (moduleName && (!this.importFilter || !this.importFilter(value))) {
  21281. var prefix = this.importsWithPrefixes.get(moduleName);
  21282. if (prefix == null) {
  21283. prefix = "i" + this.importsWithPrefixes.size;
  21284. this.importsWithPrefixes.set(moduleName, prefix);
  21285. }
  21286. ctx.print(null, prefix + ".");
  21287. }
  21288. ctx.print(null, name);
  21289. if (this.typeExpression > 0) {
  21290. // If we are in a type expression that refers to a generic type then supply
  21291. // the required type parameters. If there were not enough type parameters
  21292. // supplied, supply any as the type. Outside a type expression the reference
  21293. // should not supply type parameters and be treated as a simple value reference
  21294. // to the constructor function itself.
  21295. var suppliedParameters = typeParams || [];
  21296. if (suppliedParameters.length > 0) {
  21297. ctx.print(null, "<");
  21298. this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, typeParams, ctx, ',');
  21299. ctx.print(null, ">");
  21300. }
  21301. }
  21302. };
  21303. _TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
  21304. if (type !== INFERRED_TYPE) {
  21305. ctx.print(null, ':');
  21306. this.visitType(type, ctx, defaultType);
  21307. }
  21308. };
  21309. return _TsEmitterVisitor;
  21310. }(AbstractEmitterVisitor));
  21311. /**
  21312. * @license
  21313. * Copyright Google Inc. All Rights Reserved.
  21314. *
  21315. * Use of this source code is governed by an MIT-style license that can be
  21316. * found in the LICENSE file at https://angular.io/license
  21317. */
  21318. /**
  21319. * Resolve a `Type` for {@link Pipe}.
  21320. *
  21321. * This interface can be overridden by the application developer to create custom behavior.
  21322. *
  21323. * See {@link Compiler}
  21324. */
  21325. var PipeResolver = /** @class */ (function () {
  21326. function PipeResolver(_reflector) {
  21327. this._reflector = _reflector;
  21328. }
  21329. PipeResolver.prototype.isPipe = function (type) {
  21330. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  21331. return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
  21332. };
  21333. /**
  21334. * Return {@link Pipe} for a given `Type`.
  21335. */
  21336. PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
  21337. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  21338. var metas = this._reflector.annotations(resolveForwardRef(type));
  21339. if (metas) {
  21340. var annotation = findLast(metas, createPipe.isTypeOf);
  21341. if (annotation) {
  21342. return annotation;
  21343. }
  21344. }
  21345. if (throwIfNotFound) {
  21346. throw new Error("No Pipe decorator found on " + stringify(type));
  21347. }
  21348. return null;
  21349. };
  21350. return PipeResolver;
  21351. }());
  21352. /**
  21353. * @license
  21354. * Copyright Google Inc. All Rights Reserved.
  21355. *
  21356. * Use of this source code is governed by an MIT-style license that can be
  21357. * found in the LICENSE file at https://angular.io/license
  21358. */
  21359. /**
  21360. * @license
  21361. * Copyright Google Inc. All Rights Reserved.
  21362. *
  21363. * Use of this source code is governed by an MIT-style license that can be
  21364. * found in the LICENSE file at https://angular.io/license
  21365. */
  21366. var LOG_VAR$1 = variable('_l');
  21367. var VIEW_VAR = variable('_v');
  21368. var CHECK_VAR = variable('_ck');
  21369. var COMP_VAR = variable('_co');
  21370. var EVENT_NAME_VAR = variable('en');
  21371. var ALLOW_DEFAULT_VAR = variable("ad");
  21372. /**
  21373. * @license
  21374. * Copyright Google Inc. All Rights Reserved.
  21375. *
  21376. * Use of this source code is governed by an MIT-style license that can be
  21377. * found in the LICENSE file at https://angular.io/license
  21378. */
  21379. // Transform an i18n AST by renaming the placeholder nodes with the given mapper
  21380. var MapPlaceholderNames = /** @class */ (function (_super) {
  21381. __extends(MapPlaceholderNames, _super);
  21382. function MapPlaceholderNames() {
  21383. return _super !== null && _super.apply(this, arguments) || this;
  21384. }
  21385. MapPlaceholderNames.prototype.convert = function (nodes, mapper) {
  21386. var _this = this;
  21387. return mapper ? nodes.map(function (n) { return n.visit(_this, mapper); }) : nodes;
  21388. };
  21389. MapPlaceholderNames.prototype.visitTagPlaceholder = function (ph, mapper) {
  21390. var _this = this;
  21391. var startName = mapper.toPublicName(ph.startName);
  21392. var closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
  21393. var children = ph.children.map(function (n) { return n.visit(_this, mapper); });
  21394. return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan);
  21395. };
  21396. MapPlaceholderNames.prototype.visitPlaceholder = function (ph, mapper) {
  21397. return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  21398. };
  21399. MapPlaceholderNames.prototype.visitIcuPlaceholder = function (ph, mapper) {
  21400. return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  21401. };
  21402. return MapPlaceholderNames;
  21403. }(CloneVisitor));
  21404. /**
  21405. * @license
  21406. * Copyright Google Inc. All Rights Reserved.
  21407. *
  21408. * Use of this source code is governed by an MIT-style license that can be
  21409. * found in the LICENSE file at https://angular.io/license
  21410. */
  21411. /**
  21412. * @license
  21413. * Copyright Google Inc. All Rights Reserved.
  21414. *
  21415. * Use of this source code is governed by an MIT-style license that can be
  21416. * found in the LICENSE file at https://angular.io/license
  21417. */
  21418. /**
  21419. * @license
  21420. * Copyright Google Inc. All Rights Reserved.
  21421. *
  21422. * Use of this source code is governed by an MIT-style license that can be
  21423. * found in the LICENSE file at https://angular.io/license
  21424. */
  21425. var TS = /^(?!.*\.d\.ts$).*\.ts$/;
  21426. var ResolvedStaticSymbol = /** @class */ (function () {
  21427. function ResolvedStaticSymbol(symbol, metadata) {
  21428. this.symbol = symbol;
  21429. this.metadata = metadata;
  21430. }
  21431. return ResolvedStaticSymbol;
  21432. }());
  21433. var SUPPORTED_SCHEMA_VERSION = 4;
  21434. /**
  21435. * This class is responsible for loading metadata per symbol,
  21436. * and normalizing references between symbols.
  21437. *
  21438. * Internally, it only uses symbols without members,
  21439. * and deduces the values for symbols with members based
  21440. * on these symbols.
  21441. */
  21442. var StaticSymbolResolver = /** @class */ (function () {
  21443. function StaticSymbolResolver(host, staticSymbolCache, summaryResolver, errorRecorder) {
  21444. this.host = host;
  21445. this.staticSymbolCache = staticSymbolCache;
  21446. this.summaryResolver = summaryResolver;
  21447. this.errorRecorder = errorRecorder;
  21448. this.metadataCache = new Map();
  21449. // Note: this will only contain StaticSymbols without members!
  21450. this.resolvedSymbols = new Map();
  21451. this.resolvedFilePaths = new Set();
  21452. // Note: this will only contain StaticSymbols without members!
  21453. this.importAs = new Map();
  21454. this.symbolResourcePaths = new Map();
  21455. this.symbolFromFile = new Map();
  21456. this.knownFileNameToModuleNames = new Map();
  21457. }
  21458. StaticSymbolResolver.prototype.resolveSymbol = function (staticSymbol) {
  21459. if (staticSymbol.members.length > 0) {
  21460. return this._resolveSymbolMembers(staticSymbol);
  21461. }
  21462. // Note: always ask for a summary first,
  21463. // as we might have read shallow metadata via a .d.ts file
  21464. // for the symbol.
  21465. var resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
  21466. if (resultFromSummary) {
  21467. return resultFromSummary;
  21468. }
  21469. var resultFromCache = this.resolvedSymbols.get(staticSymbol);
  21470. if (resultFromCache) {
  21471. return resultFromCache;
  21472. }
  21473. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  21474. // have summaries, only .d.ts files. So we always need to check both, the summary
  21475. // and metadata.
  21476. this._createSymbolsOf(staticSymbol.filePath);
  21477. return this.resolvedSymbols.get(staticSymbol);
  21478. };
  21479. /**
  21480. * getImportAs produces a symbol that can be used to import the given symbol.
  21481. * The import might be different than the symbol if the symbol is exported from
  21482. * a library with a summary; in which case we want to import the symbol from the
  21483. * ngfactory re-export instead of directly to avoid introducing a direct dependency
  21484. * on an otherwise indirect dependency.
  21485. *
  21486. * @param staticSymbol the symbol for which to generate a import symbol
  21487. */
  21488. StaticSymbolResolver.prototype.getImportAs = function (staticSymbol, useSummaries) {
  21489. if (useSummaries === void 0) { useSummaries = true; }
  21490. if (staticSymbol.members.length) {
  21491. var baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
  21492. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  21493. return baseImportAs ?
  21494. this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
  21495. null;
  21496. }
  21497. var summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
  21498. if (summarizedFileName !== staticSymbol.filePath) {
  21499. var summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
  21500. var baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
  21501. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  21502. return baseImportAs ?
  21503. this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
  21504. null;
  21505. }
  21506. var result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
  21507. if (!result) {
  21508. result = this.importAs.get(staticSymbol);
  21509. }
  21510. return result;
  21511. };
  21512. /**
  21513. * getResourcePath produces the path to the original location of the symbol and should
  21514. * be used to determine the relative location of resource references recorded in
  21515. * symbol metadata.
  21516. */
  21517. StaticSymbolResolver.prototype.getResourcePath = function (staticSymbol) {
  21518. return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
  21519. };
  21520. /**
  21521. * getTypeArity returns the number of generic type parameters the given symbol
  21522. * has. If the symbol is not a type the result is null.
  21523. */
  21524. StaticSymbolResolver.prototype.getTypeArity = function (staticSymbol) {
  21525. // If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
  21526. // cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
  21527. // All references to generated classes must include the correct arity whenever
  21528. // generating code.
  21529. if (isGeneratedFile(staticSymbol.filePath)) {
  21530. return null;
  21531. }
  21532. var resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
  21533. while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
  21534. resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
  21535. }
  21536. return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
  21537. };
  21538. StaticSymbolResolver.prototype.getKnownModuleName = function (filePath) {
  21539. return this.knownFileNameToModuleNames.get(filePath) || null;
  21540. };
  21541. StaticSymbolResolver.prototype.recordImportAs = function (sourceSymbol, targetSymbol) {
  21542. sourceSymbol.assertNoMembers();
  21543. targetSymbol.assertNoMembers();
  21544. this.importAs.set(sourceSymbol, targetSymbol);
  21545. };
  21546. StaticSymbolResolver.prototype.recordModuleNameForFileName = function (fileName, moduleName) {
  21547. this.knownFileNameToModuleNames.set(fileName, moduleName);
  21548. };
  21549. /**
  21550. * Invalidate all information derived from the given file.
  21551. *
  21552. * @param fileName the file to invalidate
  21553. */
  21554. StaticSymbolResolver.prototype.invalidateFile = function (fileName) {
  21555. var e_1, _a;
  21556. this.metadataCache.delete(fileName);
  21557. this.resolvedFilePaths.delete(fileName);
  21558. var symbols = this.symbolFromFile.get(fileName);
  21559. if (symbols) {
  21560. this.symbolFromFile.delete(fileName);
  21561. try {
  21562. for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
  21563. var symbol = symbols_1_1.value;
  21564. this.resolvedSymbols.delete(symbol);
  21565. this.importAs.delete(symbol);
  21566. this.symbolResourcePaths.delete(symbol);
  21567. }
  21568. }
  21569. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  21570. finally {
  21571. try {
  21572. if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
  21573. }
  21574. finally { if (e_1) throw e_1.error; }
  21575. }
  21576. }
  21577. };
  21578. /** @internal */
  21579. StaticSymbolResolver.prototype.ignoreErrorsFor = function (cb) {
  21580. var recorder = this.errorRecorder;
  21581. this.errorRecorder = function () { };
  21582. try {
  21583. return cb();
  21584. }
  21585. finally {
  21586. this.errorRecorder = recorder;
  21587. }
  21588. };
  21589. StaticSymbolResolver.prototype._resolveSymbolMembers = function (staticSymbol) {
  21590. var members = staticSymbol.members;
  21591. var baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
  21592. if (!baseResolvedSymbol) {
  21593. return null;
  21594. }
  21595. var baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
  21596. if (baseMetadata instanceof StaticSymbol) {
  21597. return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
  21598. }
  21599. else if (baseMetadata && baseMetadata.__symbolic === 'class') {
  21600. if (baseMetadata.statics && members.length === 1) {
  21601. return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
  21602. }
  21603. }
  21604. else {
  21605. var value = baseMetadata;
  21606. for (var i = 0; i < members.length && value; i++) {
  21607. value = value[members[i]];
  21608. }
  21609. return new ResolvedStaticSymbol(staticSymbol, value);
  21610. }
  21611. return null;
  21612. };
  21613. StaticSymbolResolver.prototype._resolveSymbolFromSummary = function (staticSymbol) {
  21614. var summary = this.summaryResolver.resolveSummary(staticSymbol);
  21615. return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
  21616. };
  21617. /**
  21618. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  21619. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  21620. *
  21621. * @param declarationFile the absolute path of the file where the symbol is declared
  21622. * @param name the name of the type.
  21623. * @param members a symbol for a static member of the named type
  21624. */
  21625. StaticSymbolResolver.prototype.getStaticSymbol = function (declarationFile, name, members) {
  21626. return this.staticSymbolCache.get(declarationFile, name, members);
  21627. };
  21628. /**
  21629. * hasDecorators checks a file's metadata for the presence of decorators without evaluating the
  21630. * metadata.
  21631. *
  21632. * @param filePath the absolute path to examine for decorators.
  21633. * @returns true if any class in the file has a decorator.
  21634. */
  21635. StaticSymbolResolver.prototype.hasDecorators = function (filePath) {
  21636. var metadata = this.getModuleMetadata(filePath);
  21637. if (metadata['metadata']) {
  21638. return Object.keys(metadata['metadata']).some(function (metadataKey) {
  21639. var entry = metadata['metadata'][metadataKey];
  21640. return entry && entry.__symbolic === 'class' && entry.decorators;
  21641. });
  21642. }
  21643. return false;
  21644. };
  21645. StaticSymbolResolver.prototype.getSymbolsOf = function (filePath) {
  21646. var summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
  21647. if (summarySymbols) {
  21648. return summarySymbols;
  21649. }
  21650. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  21651. // have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
  21652. this._createSymbolsOf(filePath);
  21653. var metadataSymbols = [];
  21654. this.resolvedSymbols.forEach(function (resolvedSymbol) {
  21655. if (resolvedSymbol.symbol.filePath === filePath) {
  21656. metadataSymbols.push(resolvedSymbol.symbol);
  21657. }
  21658. });
  21659. return metadataSymbols;
  21660. };
  21661. StaticSymbolResolver.prototype._createSymbolsOf = function (filePath) {
  21662. var _this = this;
  21663. var e_2, _a;
  21664. if (this.resolvedFilePaths.has(filePath)) {
  21665. return;
  21666. }
  21667. this.resolvedFilePaths.add(filePath);
  21668. var resolvedSymbols = [];
  21669. var metadata = this.getModuleMetadata(filePath);
  21670. if (metadata['importAs']) {
  21671. // Index bundle indices should use the importAs module name defined
  21672. // in the bundle.
  21673. this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
  21674. }
  21675. // handle the symbols in one of the re-export location
  21676. if (metadata['exports']) {
  21677. var _loop_1 = function (moduleExport) {
  21678. // handle the symbols in the list of explicitly re-exported symbols.
  21679. if (moduleExport.export) {
  21680. moduleExport.export.forEach(function (exportSymbol) {
  21681. var symbolName;
  21682. if (typeof exportSymbol === 'string') {
  21683. symbolName = exportSymbol;
  21684. }
  21685. else {
  21686. symbolName = exportSymbol.as;
  21687. }
  21688. symbolName = unescapeIdentifier(symbolName);
  21689. var symName = symbolName;
  21690. if (typeof exportSymbol !== 'string') {
  21691. symName = unescapeIdentifier(exportSymbol.name);
  21692. }
  21693. var resolvedModule = _this.resolveModule(moduleExport.from, filePath);
  21694. if (resolvedModule) {
  21695. var targetSymbol = _this.getStaticSymbol(resolvedModule, symName);
  21696. var sourceSymbol = _this.getStaticSymbol(filePath, symbolName);
  21697. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  21698. }
  21699. });
  21700. }
  21701. else {
  21702. // handle the symbols via export * directives.
  21703. var resolvedModule = this_1.resolveModule(moduleExport.from, filePath);
  21704. if (resolvedModule) {
  21705. var nestedExports = this_1.getSymbolsOf(resolvedModule);
  21706. nestedExports.forEach(function (targetSymbol) {
  21707. var sourceSymbol = _this.getStaticSymbol(filePath, targetSymbol.name);
  21708. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  21709. });
  21710. }
  21711. }
  21712. };
  21713. var this_1 = this;
  21714. try {
  21715. for (var _b = __values(metadata['exports']), _c = _b.next(); !_c.done; _c = _b.next()) {
  21716. var moduleExport = _c.value;
  21717. _loop_1(moduleExport);
  21718. }
  21719. }
  21720. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  21721. finally {
  21722. try {
  21723. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  21724. }
  21725. finally { if (e_2) throw e_2.error; }
  21726. }
  21727. }
  21728. // handle the actual metadata. Has to be after the exports
  21729. // as there might be collisions in the names, and we want the symbols
  21730. // of the current module to win ofter reexports.
  21731. if (metadata['metadata']) {
  21732. // handle direct declarations of the symbol
  21733. var topLevelSymbolNames_1 = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
  21734. var origins_1 = metadata['origins'] || {};
  21735. Object.keys(metadata['metadata']).forEach(function (metadataKey) {
  21736. var symbolMeta = metadata['metadata'][metadataKey];
  21737. var name = unescapeIdentifier(metadataKey);
  21738. var symbol = _this.getStaticSymbol(filePath, name);
  21739. var origin = origins_1.hasOwnProperty(metadataKey) && origins_1[metadataKey];
  21740. if (origin) {
  21741. // If the symbol is from a bundled index, use the declaration location of the
  21742. // symbol so relative references (such as './my.html') will be calculated
  21743. // correctly.
  21744. var originFilePath = _this.resolveModule(origin, filePath);
  21745. if (!originFilePath) {
  21746. _this.reportError(new Error("Couldn't resolve original symbol for " + origin + " from " + _this.host.getOutputName(filePath)));
  21747. }
  21748. else {
  21749. _this.symbolResourcePaths.set(symbol, originFilePath);
  21750. }
  21751. }
  21752. resolvedSymbols.push(_this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames_1, symbolMeta));
  21753. });
  21754. }
  21755. resolvedSymbols.forEach(function (resolvedSymbol) { return _this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol); });
  21756. this.symbolFromFile.set(filePath, resolvedSymbols.map(function (resolvedSymbol) { return resolvedSymbol.symbol; }));
  21757. };
  21758. StaticSymbolResolver.prototype.createResolvedSymbol = function (sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
  21759. var _this = this;
  21760. // For classes that don't have Angular summaries / metadata,
  21761. // we only keep their arity, but nothing else
  21762. // (e.g. their constructor parameters).
  21763. // We do this to prevent introducing deep imports
  21764. // as we didn't generate .ngfactory.ts files with proper reexports.
  21765. var isTsFile = TS.test(sourceSymbol.filePath);
  21766. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
  21767. metadata['__symbolic'] === 'class') {
  21768. var transformedMeta_1 = { __symbolic: 'class', arity: metadata.arity };
  21769. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta_1);
  21770. }
  21771. var _originalFileMemo;
  21772. var getOriginalName = function () {
  21773. if (!_originalFileMemo) {
  21774. // Guess what the original file name is from the reference. If it has a `.d.ts` extension
  21775. // replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
  21776. // .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
  21777. // location as it is not important to finding the file.
  21778. _originalFileMemo =
  21779. _this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
  21780. .replace(/^.*node_modules[/\\]/, ''));
  21781. }
  21782. return _originalFileMemo;
  21783. };
  21784. var self = this;
  21785. var ReferenceTransformer = /** @class */ (function (_super) {
  21786. __extends(ReferenceTransformer, _super);
  21787. function ReferenceTransformer() {
  21788. return _super !== null && _super.apply(this, arguments) || this;
  21789. }
  21790. ReferenceTransformer.prototype.visitStringMap = function (map, functionParams) {
  21791. var symbolic = map['__symbolic'];
  21792. if (symbolic === 'function') {
  21793. var oldLen = functionParams.length;
  21794. functionParams.push.apply(functionParams, __spread((map['parameters'] || [])));
  21795. var result = _super.prototype.visitStringMap.call(this, map, functionParams);
  21796. functionParams.length = oldLen;
  21797. return result;
  21798. }
  21799. else if (symbolic === 'reference') {
  21800. var module = map['module'];
  21801. var name_1 = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
  21802. if (!name_1) {
  21803. return null;
  21804. }
  21805. var filePath = void 0;
  21806. if (module) {
  21807. filePath = self.resolveModule(module, sourceSymbol.filePath);
  21808. if (!filePath) {
  21809. return {
  21810. __symbolic: 'error',
  21811. message: "Could not resolve " + module + " relative to " + self.host.getMetadataFor(sourceSymbol.filePath) + ".",
  21812. line: map['line'],
  21813. character: map['character'],
  21814. fileName: getOriginalName()
  21815. };
  21816. }
  21817. return {
  21818. __symbolic: 'resolved',
  21819. symbol: self.getStaticSymbol(filePath, name_1),
  21820. line: map['line'],
  21821. character: map['character'],
  21822. fileName: getOriginalName()
  21823. };
  21824. }
  21825. else if (functionParams.indexOf(name_1) >= 0) {
  21826. // reference to a function parameter
  21827. return { __symbolic: 'reference', name: name_1 };
  21828. }
  21829. else {
  21830. if (topLevelSymbolNames.has(name_1)) {
  21831. return self.getStaticSymbol(topLevelPath, name_1);
  21832. }
  21833. }
  21834. }
  21835. else if (symbolic === 'error') {
  21836. return __assign({}, map, { fileName: getOriginalName() });
  21837. }
  21838. else {
  21839. return _super.prototype.visitStringMap.call(this, map, functionParams);
  21840. }
  21841. };
  21842. return ReferenceTransformer;
  21843. }(ValueTransformer));
  21844. var transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
  21845. var unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
  21846. if (unwrappedTransformedMeta instanceof StaticSymbol) {
  21847. return this.createExport(sourceSymbol, unwrappedTransformedMeta);
  21848. }
  21849. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
  21850. };
  21851. StaticSymbolResolver.prototype.createExport = function (sourceSymbol, targetSymbol) {
  21852. sourceSymbol.assertNoMembers();
  21853. targetSymbol.assertNoMembers();
  21854. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
  21855. this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
  21856. // This case is for an ng library importing symbols from a plain ts library
  21857. // transitively.
  21858. // Note: We rely on the fact that we discover symbols in the direction
  21859. // from source files to library files
  21860. this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
  21861. }
  21862. return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
  21863. };
  21864. StaticSymbolResolver.prototype.reportError = function (error, context, path) {
  21865. if (this.errorRecorder) {
  21866. this.errorRecorder(error, (context && context.filePath) || path);
  21867. }
  21868. else {
  21869. throw error;
  21870. }
  21871. };
  21872. /**
  21873. * @param module an absolute path to a module file.
  21874. */
  21875. StaticSymbolResolver.prototype.getModuleMetadata = function (module) {
  21876. var moduleMetadata = this.metadataCache.get(module);
  21877. if (!moduleMetadata) {
  21878. var moduleMetadatas = this.host.getMetadataFor(module);
  21879. if (moduleMetadatas) {
  21880. var maxVersion_1 = -1;
  21881. moduleMetadatas.forEach(function (md) {
  21882. if (md && md['version'] > maxVersion_1) {
  21883. maxVersion_1 = md['version'];
  21884. moduleMetadata = md;
  21885. }
  21886. });
  21887. }
  21888. if (!moduleMetadata) {
  21889. moduleMetadata =
  21890. { __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
  21891. }
  21892. if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
  21893. var errorMessage = moduleMetadata['version'] == 2 ?
  21894. "Unsupported metadata version " + moduleMetadata['version'] + " for module " + module + ". This module should be compiled with a newer version of ngc" :
  21895. "Metadata version mismatch for module " + this.host.getOutputName(module) + ", found version " + moduleMetadata['version'] + ", expected " + SUPPORTED_SCHEMA_VERSION;
  21896. this.reportError(new Error(errorMessage));
  21897. }
  21898. this.metadataCache.set(module, moduleMetadata);
  21899. }
  21900. return moduleMetadata;
  21901. };
  21902. StaticSymbolResolver.prototype.getSymbolByModule = function (module, symbolName, containingFile) {
  21903. var filePath = this.resolveModule(module, containingFile);
  21904. if (!filePath) {
  21905. this.reportError(new Error("Could not resolve module " + module + (containingFile ? ' relative to ' +
  21906. this.host.getOutputName(containingFile) : '')));
  21907. return this.getStaticSymbol("ERROR:" + module, symbolName);
  21908. }
  21909. return this.getStaticSymbol(filePath, symbolName);
  21910. };
  21911. StaticSymbolResolver.prototype.resolveModule = function (module, containingFile) {
  21912. try {
  21913. return this.host.moduleNameToFileName(module, containingFile);
  21914. }
  21915. catch (e) {
  21916. console.error("Could not resolve module '" + module + "' relative to file " + containingFile);
  21917. this.reportError(e, undefined, containingFile);
  21918. }
  21919. return null;
  21920. };
  21921. return StaticSymbolResolver;
  21922. }());
  21923. // Remove extra underscore from escaped identifier.
  21924. // See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
  21925. function unescapeIdentifier(identifier) {
  21926. return identifier.startsWith('___') ? identifier.substr(1) : identifier;
  21927. }
  21928. function unwrapResolvedMetadata(metadata) {
  21929. if (metadata && metadata.__symbolic === 'resolved') {
  21930. return metadata.symbol;
  21931. }
  21932. return metadata;
  21933. }
  21934. function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
  21935. var deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
  21936. return deserializer.deserialize(libraryFileName, json);
  21937. }
  21938. var ToJsonSerializer = /** @class */ (function (_super) {
  21939. __extends(ToJsonSerializer, _super);
  21940. function ToJsonSerializer(symbolResolver, summaryResolver, srcFileName) {
  21941. var _this = _super.call(this) || this;
  21942. _this.symbolResolver = symbolResolver;
  21943. _this.summaryResolver = summaryResolver;
  21944. _this.srcFileName = srcFileName;
  21945. // Note: This only contains symbols without members.
  21946. _this.symbols = [];
  21947. _this.indexBySymbol = new Map();
  21948. _this.reexportedBy = new Map();
  21949. // This now contains a `__symbol: number` in the place of
  21950. // StaticSymbols, but otherwise has the same shape as the original objects.
  21951. _this.processedSummaryBySymbol = new Map();
  21952. _this.processedSummaries = [];
  21953. _this.unprocessedSymbolSummariesBySymbol = new Map();
  21954. _this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
  21955. return _this;
  21956. }
  21957. ToJsonSerializer.prototype.addSummary = function (summary) {
  21958. var _this = this;
  21959. var unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
  21960. var processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
  21961. if (!unprocessedSummary) {
  21962. unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
  21963. this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
  21964. processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
  21965. this.processedSummaries.push(processedSummary);
  21966. this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
  21967. }
  21968. if (!unprocessedSummary.metadata && summary.metadata) {
  21969. var metadata_1 = summary.metadata || {};
  21970. if (metadata_1.__symbolic === 'class') {
  21971. // For classes, we keep everything except their class decorators.
  21972. // We need to keep e.g. the ctor args, method names, method decorators
  21973. // so that the class can be extended in another compilation unit.
  21974. // We don't keep the class decorators as
  21975. // 1) they refer to data
  21976. // that should not cause a rebuild of downstream compilation units
  21977. // (e.g. inline templates of @Component, or @NgModule.declarations)
  21978. // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
  21979. var clone_1 = {};
  21980. Object.keys(metadata_1).forEach(function (propName) {
  21981. if (propName !== 'decorators') {
  21982. clone_1[propName] = metadata_1[propName];
  21983. }
  21984. });
  21985. metadata_1 = clone_1;
  21986. }
  21987. else if (isCall(metadata_1)) {
  21988. if (!isFunctionCall(metadata_1) && !isMethodCallOnVariable(metadata_1)) {
  21989. // Don't store complex calls as we won't be able to simplify them anyways later on.
  21990. metadata_1 = {
  21991. __symbolic: 'error',
  21992. message: 'Complex function calls are not supported.',
  21993. };
  21994. }
  21995. }
  21996. // Note: We need to keep storing ctor calls for e.g.
  21997. // `export const x = new InjectionToken(...)`
  21998. unprocessedSummary.metadata = metadata_1;
  21999. processedSummary.metadata = this.processValue(metadata_1, 1 /* ResolveValue */);
  22000. if (metadata_1 instanceof StaticSymbol &&
  22001. this.summaryResolver.isLibraryFile(metadata_1.filePath)) {
  22002. var declarationSymbol = this.symbols[this.indexBySymbol.get(metadata_1)];
  22003. if (!isLoweredSymbol(declarationSymbol.name)) {
  22004. // Note: symbols that were introduced during codegen in the user file can have a reexport
  22005. // if a user used `export *`. However, we can't rely on this as tsickle will change
  22006. // `export *` into named exports, using only the information from the typechecker.
  22007. // As we introduce the new symbols after typecheck, Tsickle does not know about them,
  22008. // and omits them when expanding `export *`.
  22009. // So we have to keep reexporting these symbols manually via .ngfactory files.
  22010. this.reexportedBy.set(declarationSymbol, summary.symbol);
  22011. }
  22012. }
  22013. }
  22014. if (!unprocessedSummary.type && summary.type) {
  22015. unprocessedSummary.type = summary.type;
  22016. // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
  22017. // as the type summaries already contain the transitive data that they require
  22018. // (in a minimal way).
  22019. processedSummary.type = this.processValue(summary.type, 0 /* None */);
  22020. // except for reexported directives / pipes, so we need to store
  22021. // their summaries explicitly.
  22022. if (summary.type.summaryKind === CompileSummaryKind.NgModule) {
  22023. var ngModuleSummary = summary.type;
  22024. ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach(function (id) {
  22025. var symbol = id.reference;
  22026. if (_this.summaryResolver.isLibraryFile(symbol.filePath) &&
  22027. !_this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
  22028. var summary_1 = _this.summaryResolver.resolveSummary(symbol);
  22029. if (summary_1) {
  22030. _this.addSummary(summary_1);
  22031. }
  22032. }
  22033. });
  22034. }
  22035. }
  22036. };
  22037. /**
  22038. * @param createExternalSymbolReexports Whether external static symbols should be re-exported.
  22039. * This can be enabled if external symbols should be re-exported by the current module in
  22040. * order to avoid dynamically generated module dependencies which can break strict dependency
  22041. * enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
  22042. */
  22043. ToJsonSerializer.prototype.serialize = function (createExternalSymbolReexports) {
  22044. var _this = this;
  22045. var exportAs = [];
  22046. var json = JSON.stringify({
  22047. moduleName: this.moduleName,
  22048. summaries: this.processedSummaries,
  22049. symbols: this.symbols.map(function (symbol, index) {
  22050. symbol.assertNoMembers();
  22051. var importAs = undefined;
  22052. if (_this.summaryResolver.isLibraryFile(symbol.filePath)) {
  22053. var reexportSymbol = _this.reexportedBy.get(symbol);
  22054. if (reexportSymbol) {
  22055. // In case the given external static symbol is already manually exported by the
  22056. // user, we just proxy the external static symbol reference to the manual export.
  22057. // This ensures that the AOT compiler imports the external symbol through the
  22058. // user export and does not introduce another dependency which is not needed.
  22059. importAs = _this.indexBySymbol.get(reexportSymbol);
  22060. }
  22061. else if (createExternalSymbolReexports) {
  22062. // In this case, the given external static symbol is *not* manually exported by
  22063. // the user, and we manually create a re-export in the factory file so that we
  22064. // don't introduce another module dependency. This is useful when running within
  22065. // Bazel so that the AOT compiler does not introduce any module dependencies
  22066. // which can break the strict dependency enforcement. (e.g. as in Google3)
  22067. // Read more about this here: https://github.com/angular/angular/issues/25644
  22068. var summary = _this.unprocessedSymbolSummariesBySymbol.get(symbol);
  22069. if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
  22070. importAs = symbol.name + "_" + index;
  22071. exportAs.push({ symbol: symbol, exportAs: importAs });
  22072. }
  22073. }
  22074. }
  22075. return {
  22076. __symbol: index,
  22077. name: symbol.name,
  22078. filePath: _this.summaryResolver.toSummaryFileName(symbol.filePath, _this.srcFileName),
  22079. importAs: importAs
  22080. };
  22081. })
  22082. });
  22083. return { json: json, exportAs: exportAs };
  22084. };
  22085. ToJsonSerializer.prototype.processValue = function (value, flags) {
  22086. return visitValue(value, this, flags);
  22087. };
  22088. ToJsonSerializer.prototype.visitOther = function (value, context) {
  22089. if (value instanceof StaticSymbol) {
  22090. var baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
  22091. var index = this.visitStaticSymbol(baseSymbol, context);
  22092. return { __symbol: index, members: value.members };
  22093. }
  22094. };
  22095. /**
  22096. * Strip line and character numbers from ngsummaries.
  22097. * Emitting them causes white spaces changes to retrigger upstream
  22098. * recompilations in bazel.
  22099. * TODO: find out a way to have line and character numbers in errors without
  22100. * excessive recompilation in bazel.
  22101. */
  22102. ToJsonSerializer.prototype.visitStringMap = function (map, context) {
  22103. if (map['__symbolic'] === 'resolved') {
  22104. return visitValue(map['symbol'], this, context);
  22105. }
  22106. if (map['__symbolic'] === 'error') {
  22107. delete map['line'];
  22108. delete map['character'];
  22109. }
  22110. return _super.prototype.visitStringMap.call(this, map, context);
  22111. };
  22112. /**
  22113. * Returns null if the options.resolveValue is true, and the summary for the symbol
  22114. * resolved to a type or could not be resolved.
  22115. */
  22116. ToJsonSerializer.prototype.visitStaticSymbol = function (baseSymbol, flags) {
  22117. var index = this.indexBySymbol.get(baseSymbol);
  22118. var summary = null;
  22119. if (flags & 1 /* ResolveValue */ &&
  22120. this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
  22121. if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
  22122. // the summary for this symbol was already added
  22123. // -> nothing to do.
  22124. return index;
  22125. }
  22126. summary = this.loadSummary(baseSymbol);
  22127. if (summary && summary.metadata instanceof StaticSymbol) {
  22128. // The summary is a reexport
  22129. index = this.visitStaticSymbol(summary.metadata, flags);
  22130. // reset the summary as it is just a reexport, so we don't want to store it.
  22131. summary = null;
  22132. }
  22133. }
  22134. else if (index != null) {
  22135. // Note: == on purpose to compare with undefined!
  22136. // No summary and the symbol is already added -> nothing to do.
  22137. return index;
  22138. }
  22139. // Note: == on purpose to compare with undefined!
  22140. if (index == null) {
  22141. index = this.symbols.length;
  22142. this.symbols.push(baseSymbol);
  22143. }
  22144. this.indexBySymbol.set(baseSymbol, index);
  22145. if (summary) {
  22146. this.addSummary(summary);
  22147. }
  22148. return index;
  22149. };
  22150. ToJsonSerializer.prototype.loadSummary = function (symbol) {
  22151. var summary = this.summaryResolver.resolveSummary(symbol);
  22152. if (!summary) {
  22153. // some symbols might originate from a plain typescript library
  22154. // that just exported .d.ts and .metadata.json files, i.e. where no summary
  22155. // files were created.
  22156. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  22157. if (resolvedSymbol) {
  22158. summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
  22159. }
  22160. }
  22161. return summary;
  22162. };
  22163. return ToJsonSerializer;
  22164. }(ValueTransformer));
  22165. var FromJsonDeserializer = /** @class */ (function (_super) {
  22166. __extends(FromJsonDeserializer, _super);
  22167. function FromJsonDeserializer(symbolCache, summaryResolver) {
  22168. var _this = _super.call(this) || this;
  22169. _this.symbolCache = symbolCache;
  22170. _this.summaryResolver = summaryResolver;
  22171. return _this;
  22172. }
  22173. FromJsonDeserializer.prototype.deserialize = function (libraryFileName, json) {
  22174. var _this = this;
  22175. var data = JSON.parse(json);
  22176. var allImportAs = [];
  22177. this.symbols = data.symbols.map(function (serializedSymbol) { return _this.symbolCache.get(_this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name); });
  22178. data.symbols.forEach(function (serializedSymbol, index) {
  22179. var symbol = _this.symbols[index];
  22180. var importAs = serializedSymbol.importAs;
  22181. if (typeof importAs === 'number') {
  22182. allImportAs.push({ symbol: symbol, importAs: _this.symbols[importAs] });
  22183. }
  22184. else if (typeof importAs === 'string') {
  22185. allImportAs.push({ symbol: symbol, importAs: _this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
  22186. }
  22187. });
  22188. var summaries = visitValue(data.summaries, this, null);
  22189. return { moduleName: data.moduleName, summaries: summaries, importAs: allImportAs };
  22190. };
  22191. FromJsonDeserializer.prototype.visitStringMap = function (map, context) {
  22192. if ('__symbol' in map) {
  22193. var baseSymbol = this.symbols[map['__symbol']];
  22194. var members = map['members'];
  22195. return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
  22196. baseSymbol;
  22197. }
  22198. else {
  22199. return _super.prototype.visitStringMap.call(this, map, context);
  22200. }
  22201. };
  22202. return FromJsonDeserializer;
  22203. }(ValueTransformer));
  22204. function isCall(metadata) {
  22205. return metadata && metadata.__symbolic === 'call';
  22206. }
  22207. function isFunctionCall(metadata) {
  22208. return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
  22209. }
  22210. function isMethodCallOnVariable(metadata) {
  22211. return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
  22212. unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
  22213. }
  22214. /**
  22215. * @license
  22216. * Copyright Google Inc. All Rights Reserved.
  22217. *
  22218. * Use of this source code is governed by an MIT-style license that can be
  22219. * found in the LICENSE file at https://angular.io/license
  22220. */
  22221. function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  22222. var files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
  22223. return mergeAnalyzedFiles(files);
  22224. }
  22225. // Analyzes all of the program files,
  22226. // including files that are not part of the program
  22227. // but are referenced by an NgModule.
  22228. function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
  22229. var seenFiles = new Set();
  22230. var files = [];
  22231. var visitFile = function (fileName) {
  22232. if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
  22233. return false;
  22234. }
  22235. seenFiles.add(fileName);
  22236. var analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
  22237. files.push(analyzedFile);
  22238. analyzedFile.ngModules.forEach(function (ngModule) {
  22239. ngModule.transitiveModule.modules.forEach(function (modMeta) { return visitFile(modMeta.reference.filePath); });
  22240. });
  22241. };
  22242. fileNames.forEach(function (fileName) { return visitFile(fileName); });
  22243. return files;
  22244. }
  22245. function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
  22246. var directives = [];
  22247. var pipes = [];
  22248. var injectables = [];
  22249. var ngModules = [];
  22250. var hasDecorators = staticSymbolResolver.hasDecorators(fileName);
  22251. var exportsNonSourceFiles = false;
  22252. // Don't analyze .d.ts files that have no decorators as a shortcut
  22253. // to speed up the analysis. This prevents us from
  22254. // resolving the references in these files.
  22255. // Note: exportsNonSourceFiles is only needed when compiling with summaries,
  22256. // which is not the case when .d.ts files are treated as input files.
  22257. if (!fileName.endsWith('.d.ts') || hasDecorators) {
  22258. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  22259. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  22260. var symbolMeta = resolvedSymbol.metadata;
  22261. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  22262. return;
  22263. }
  22264. var isNgSymbol = false;
  22265. if (symbolMeta.__symbolic === 'class') {
  22266. if (metadataResolver.isDirective(symbol)) {
  22267. isNgSymbol = true;
  22268. directives.push(symbol);
  22269. }
  22270. else if (metadataResolver.isPipe(symbol)) {
  22271. isNgSymbol = true;
  22272. pipes.push(symbol);
  22273. }
  22274. else if (metadataResolver.isNgModule(symbol)) {
  22275. var ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
  22276. if (ngModule) {
  22277. isNgSymbol = true;
  22278. ngModules.push(ngModule);
  22279. }
  22280. }
  22281. else if (metadataResolver.isInjectable(symbol)) {
  22282. isNgSymbol = true;
  22283. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  22284. if (injectable) {
  22285. injectables.push(injectable);
  22286. }
  22287. }
  22288. }
  22289. if (!isNgSymbol) {
  22290. exportsNonSourceFiles =
  22291. exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
  22292. }
  22293. });
  22294. }
  22295. return {
  22296. fileName: fileName, directives: directives, pipes: pipes, ngModules: ngModules, injectables: injectables, exportsNonSourceFiles: exportsNonSourceFiles,
  22297. };
  22298. }
  22299. function isValueExportingNonSourceFile(host, metadata) {
  22300. var exportsNonSourceFiles = false;
  22301. var Visitor = /** @class */ (function () {
  22302. function Visitor() {
  22303. }
  22304. Visitor.prototype.visitArray = function (arr, context) {
  22305. var _this = this;
  22306. arr.forEach(function (v) { return visitValue(v, _this, context); });
  22307. };
  22308. Visitor.prototype.visitStringMap = function (map, context) {
  22309. var _this = this;
  22310. Object.keys(map).forEach(function (key) { return visitValue(map[key], _this, context); });
  22311. };
  22312. Visitor.prototype.visitPrimitive = function (value, context) { };
  22313. Visitor.prototype.visitOther = function (value, context) {
  22314. if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
  22315. exportsNonSourceFiles = true;
  22316. }
  22317. };
  22318. return Visitor;
  22319. }());
  22320. visitValue(metadata, new Visitor(), null);
  22321. return exportsNonSourceFiles;
  22322. }
  22323. function mergeAnalyzedFiles(analyzedFiles) {
  22324. var allNgModules = [];
  22325. var ngModuleByPipeOrDirective = new Map();
  22326. var allPipesAndDirectives = new Set();
  22327. analyzedFiles.forEach(function (af) {
  22328. af.ngModules.forEach(function (ngModule) {
  22329. allNgModules.push(ngModule);
  22330. ngModule.declaredDirectives.forEach(function (d) { return ngModuleByPipeOrDirective.set(d.reference, ngModule); });
  22331. ngModule.declaredPipes.forEach(function (p) { return ngModuleByPipeOrDirective.set(p.reference, ngModule); });
  22332. });
  22333. af.directives.forEach(function (d) { return allPipesAndDirectives.add(d); });
  22334. af.pipes.forEach(function (p) { return allPipesAndDirectives.add(p); });
  22335. });
  22336. var symbolsMissingModule = [];
  22337. allPipesAndDirectives.forEach(function (ref) {
  22338. if (!ngModuleByPipeOrDirective.has(ref)) {
  22339. symbolsMissingModule.push(ref);
  22340. }
  22341. });
  22342. return {
  22343. ngModules: allNgModules,
  22344. ngModuleByPipeOrDirective: ngModuleByPipeOrDirective,
  22345. symbolsMissingModule: symbolsMissingModule,
  22346. files: analyzedFiles
  22347. };
  22348. }
  22349. /**
  22350. * @license
  22351. * Copyright Google Inc. All Rights Reserved.
  22352. *
  22353. * Use of this source code is governed by an MIT-style license that can be
  22354. * found in the LICENSE file at https://angular.io/license
  22355. */
  22356. var FORMATTED_MESSAGE = 'ngFormattedMessage';
  22357. function indentStr(level) {
  22358. if (level <= 0)
  22359. return '';
  22360. if (level < 6)
  22361. return ['', ' ', ' ', ' ', ' ', ' '][level];
  22362. var half = indentStr(Math.floor(level / 2));
  22363. return half + half + (level % 2 === 1 ? ' ' : '');
  22364. }
  22365. function formatChain(chain, indent) {
  22366. if (indent === void 0) { indent = 0; }
  22367. if (!chain)
  22368. return '';
  22369. var position = chain.position ?
  22370. chain.position.fileName + "(" + (chain.position.line + 1) + "," + (chain.position.column + 1) + ")" :
  22371. '';
  22372. var prefix = position && indent === 0 ? position + ": " : '';
  22373. var postfix = position && indent !== 0 ? " at " + position : '';
  22374. var message = "" + prefix + chain.message + postfix;
  22375. return "" + indentStr(indent) + message + ((chain.next && ('\n' + formatChain(chain.next, indent + 2))) || '');
  22376. }
  22377. function formattedError(chain) {
  22378. var message = formatChain(chain) + '.';
  22379. var error = syntaxError(message);
  22380. error[FORMATTED_MESSAGE] = true;
  22381. error.chain = chain;
  22382. error.position = chain.position;
  22383. return error;
  22384. }
  22385. function isFormattedError(error) {
  22386. return !!error[FORMATTED_MESSAGE];
  22387. }
  22388. /**
  22389. * @license
  22390. * Copyright Google Inc. All Rights Reserved.
  22391. *
  22392. * Use of this source code is governed by an MIT-style license that can be
  22393. * found in the LICENSE file at https://angular.io/license
  22394. */
  22395. var ANGULAR_CORE = '@angular/core';
  22396. var ANGULAR_ROUTER = '@angular/router';
  22397. var HIDDEN_KEY = /^\$.*\$$/;
  22398. var IGNORE = {
  22399. __symbolic: 'ignore'
  22400. };
  22401. var USE_VALUE$1 = 'useValue';
  22402. var PROVIDE = 'provide';
  22403. var REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
  22404. var TYPEGUARD_POSTFIX = 'TypeGuard';
  22405. var USE_IF = 'UseIf';
  22406. function shouldIgnore(value) {
  22407. return value && value.__symbolic == 'ignore';
  22408. }
  22409. /**
  22410. * A static reflector implements enough of the Reflector API that is necessary to compile
  22411. * templates statically.
  22412. */
  22413. var StaticReflector = /** @class */ (function () {
  22414. function StaticReflector(summaryResolver, symbolResolver, knownMetadataClasses, knownMetadataFunctions, errorRecorder) {
  22415. var _this = this;
  22416. if (knownMetadataClasses === void 0) { knownMetadataClasses = []; }
  22417. if (knownMetadataFunctions === void 0) { knownMetadataFunctions = []; }
  22418. this.summaryResolver = summaryResolver;
  22419. this.symbolResolver = symbolResolver;
  22420. this.errorRecorder = errorRecorder;
  22421. this.annotationCache = new Map();
  22422. this.shallowAnnotationCache = new Map();
  22423. this.propertyCache = new Map();
  22424. this.parameterCache = new Map();
  22425. this.methodCache = new Map();
  22426. this.staticCache = new Map();
  22427. this.conversionMap = new Map();
  22428. this.resolvedExternalReferences = new Map();
  22429. this.annotationForParentClassWithSummaryKind = new Map();
  22430. this.initializeConversionMap();
  22431. knownMetadataClasses.forEach(function (kc) { return _this._registerDecoratorOrConstructor(_this.getStaticSymbol(kc.filePath, kc.name), kc.ctor); });
  22432. knownMetadataFunctions.forEach(function (kf) { return _this._registerFunction(_this.getStaticSymbol(kf.filePath, kf.name), kf.fn); });
  22433. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Directive, [createDirective, createComponent]);
  22434. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Pipe, [createPipe]);
  22435. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.NgModule, [createNgModule]);
  22436. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
  22437. }
  22438. StaticReflector.prototype.componentModuleUrl = function (typeOrFunc) {
  22439. var staticSymbol = this.findSymbolDeclaration(typeOrFunc);
  22440. return this.symbolResolver.getResourcePath(staticSymbol);
  22441. };
  22442. StaticReflector.prototype.resolveExternalReference = function (ref, containingFile) {
  22443. var key = undefined;
  22444. if (!containingFile) {
  22445. key = ref.moduleName + ":" + ref.name;
  22446. var declarationSymbol_1 = this.resolvedExternalReferences.get(key);
  22447. if (declarationSymbol_1)
  22448. return declarationSymbol_1;
  22449. }
  22450. var refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
  22451. var declarationSymbol = this.findSymbolDeclaration(refSymbol);
  22452. if (!containingFile) {
  22453. this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
  22454. this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
  22455. }
  22456. if (key) {
  22457. this.resolvedExternalReferences.set(key, declarationSymbol);
  22458. }
  22459. return declarationSymbol;
  22460. };
  22461. StaticReflector.prototype.findDeclaration = function (moduleUrl, name, containingFile) {
  22462. return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
  22463. };
  22464. StaticReflector.prototype.tryFindDeclaration = function (moduleUrl, name, containingFile) {
  22465. var _this = this;
  22466. return this.symbolResolver.ignoreErrorsFor(function () { return _this.findDeclaration(moduleUrl, name, containingFile); });
  22467. };
  22468. StaticReflector.prototype.findSymbolDeclaration = function (symbol) {
  22469. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  22470. if (resolvedSymbol) {
  22471. var resolvedMetadata = resolvedSymbol.metadata;
  22472. if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
  22473. resolvedMetadata = resolvedMetadata.symbol;
  22474. }
  22475. if (resolvedMetadata instanceof StaticSymbol) {
  22476. return this.findSymbolDeclaration(resolvedSymbol.metadata);
  22477. }
  22478. }
  22479. return symbol;
  22480. };
  22481. StaticReflector.prototype.tryAnnotations = function (type) {
  22482. var originalRecorder = this.errorRecorder;
  22483. this.errorRecorder = function (error, fileName) { };
  22484. try {
  22485. return this.annotations(type);
  22486. }
  22487. finally {
  22488. this.errorRecorder = originalRecorder;
  22489. }
  22490. };
  22491. StaticReflector.prototype.annotations = function (type) {
  22492. var _this = this;
  22493. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators); }, this.annotationCache);
  22494. };
  22495. StaticReflector.prototype.shallowAnnotations = function (type) {
  22496. var _this = this;
  22497. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators, true); }, this.shallowAnnotationCache);
  22498. };
  22499. StaticReflector.prototype._annotations = function (type, simplify, annotationCache) {
  22500. var annotations = annotationCache.get(type);
  22501. if (!annotations) {
  22502. annotations = [];
  22503. var classMetadata = this.getTypeMetadata(type);
  22504. var parentType = this.findParentType(type, classMetadata);
  22505. if (parentType) {
  22506. var parentAnnotations = this.annotations(parentType);
  22507. annotations.push.apply(annotations, __spread(parentAnnotations));
  22508. }
  22509. var ownAnnotations_1 = [];
  22510. if (classMetadata['decorators']) {
  22511. ownAnnotations_1 = simplify(type, classMetadata['decorators']);
  22512. if (ownAnnotations_1) {
  22513. annotations.push.apply(annotations, __spread(ownAnnotations_1));
  22514. }
  22515. }
  22516. if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
  22517. this.summaryResolver.isLibraryFile(parentType.filePath)) {
  22518. var summary = this.summaryResolver.resolveSummary(parentType);
  22519. if (summary && summary.type) {
  22520. var requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
  22521. var typeHasRequiredAnnotation = requiredAnnotationTypes.some(function (requiredType) { return ownAnnotations_1.some(function (ann) { return requiredType.isTypeOf(ann); }); });
  22522. if (!typeHasRequiredAnnotation) {
  22523. this.reportError(formatMetadataError(metadataError("Class " + type.name + " in " + type.filePath + " extends from a " + CompileSummaryKind[summary.type.summaryKind] + " in another compilation unit without duplicating the decorator",
  22524. /* summary */ undefined, "Please add a " + requiredAnnotationTypes.map(function (type) { return type.ngMetadataName; }).join(' or ') + " decorator to the class"), type), type);
  22525. }
  22526. }
  22527. }
  22528. annotationCache.set(type, annotations.filter(function (ann) { return !!ann; }));
  22529. }
  22530. return annotations;
  22531. };
  22532. StaticReflector.prototype.propMetadata = function (type) {
  22533. var _this = this;
  22534. var propMetadata = this.propertyCache.get(type);
  22535. if (!propMetadata) {
  22536. var classMetadata = this.getTypeMetadata(type);
  22537. propMetadata = {};
  22538. var parentType = this.findParentType(type, classMetadata);
  22539. if (parentType) {
  22540. var parentPropMetadata_1 = this.propMetadata(parentType);
  22541. Object.keys(parentPropMetadata_1).forEach(function (parentProp) {
  22542. propMetadata[parentProp] = parentPropMetadata_1[parentProp];
  22543. });
  22544. }
  22545. var members_1 = classMetadata['members'] || {};
  22546. Object.keys(members_1).forEach(function (propName) {
  22547. var propData = members_1[propName];
  22548. var prop = propData
  22549. .find(function (a) { return a['__symbolic'] == 'property' || a['__symbolic'] == 'method'; });
  22550. var decorators = [];
  22551. if (propMetadata[propName]) {
  22552. decorators.push.apply(decorators, __spread(propMetadata[propName]));
  22553. }
  22554. propMetadata[propName] = decorators;
  22555. if (prop && prop['decorators']) {
  22556. decorators.push.apply(decorators, __spread(_this.simplify(type, prop['decorators'])));
  22557. }
  22558. });
  22559. this.propertyCache.set(type, propMetadata);
  22560. }
  22561. return propMetadata;
  22562. };
  22563. StaticReflector.prototype.parameters = function (type) {
  22564. var _this = this;
  22565. if (!(type instanceof StaticSymbol)) {
  22566. this.reportError(new Error("parameters received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  22567. return [];
  22568. }
  22569. try {
  22570. var parameters_1 = this.parameterCache.get(type);
  22571. if (!parameters_1) {
  22572. var classMetadata = this.getTypeMetadata(type);
  22573. var parentType = this.findParentType(type, classMetadata);
  22574. var members = classMetadata ? classMetadata['members'] : null;
  22575. var ctorData = members ? members['__ctor__'] : null;
  22576. if (ctorData) {
  22577. var ctor = ctorData.find(function (a) { return a['__symbolic'] == 'constructor'; });
  22578. var rawParameterTypes = ctor['parameters'] || [];
  22579. var parameterDecorators_1 = this.simplify(type, ctor['parameterDecorators'] || []);
  22580. parameters_1 = [];
  22581. rawParameterTypes.forEach(function (rawParamType, index) {
  22582. var nestedResult = [];
  22583. var paramType = _this.trySimplify(type, rawParamType);
  22584. if (paramType)
  22585. nestedResult.push(paramType);
  22586. var decorators = parameterDecorators_1 ? parameterDecorators_1[index] : null;
  22587. if (decorators) {
  22588. nestedResult.push.apply(nestedResult, __spread(decorators));
  22589. }
  22590. parameters_1.push(nestedResult);
  22591. });
  22592. }
  22593. else if (parentType) {
  22594. parameters_1 = this.parameters(parentType);
  22595. }
  22596. if (!parameters_1) {
  22597. parameters_1 = [];
  22598. }
  22599. this.parameterCache.set(type, parameters_1);
  22600. }
  22601. return parameters_1;
  22602. }
  22603. catch (e) {
  22604. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  22605. throw e;
  22606. }
  22607. };
  22608. StaticReflector.prototype._methodNames = function (type) {
  22609. var methodNames = this.methodCache.get(type);
  22610. if (!methodNames) {
  22611. var classMetadata = this.getTypeMetadata(type);
  22612. methodNames = {};
  22613. var parentType = this.findParentType(type, classMetadata);
  22614. if (parentType) {
  22615. var parentMethodNames_1 = this._methodNames(parentType);
  22616. Object.keys(parentMethodNames_1).forEach(function (parentProp) {
  22617. methodNames[parentProp] = parentMethodNames_1[parentProp];
  22618. });
  22619. }
  22620. var members_2 = classMetadata['members'] || {};
  22621. Object.keys(members_2).forEach(function (propName) {
  22622. var propData = members_2[propName];
  22623. var isMethod = propData.some(function (a) { return a['__symbolic'] == 'method'; });
  22624. methodNames[propName] = methodNames[propName] || isMethod;
  22625. });
  22626. this.methodCache.set(type, methodNames);
  22627. }
  22628. return methodNames;
  22629. };
  22630. StaticReflector.prototype._staticMembers = function (type) {
  22631. var staticMembers = this.staticCache.get(type);
  22632. if (!staticMembers) {
  22633. var classMetadata = this.getTypeMetadata(type);
  22634. var staticMemberData = classMetadata['statics'] || {};
  22635. staticMembers = Object.keys(staticMemberData);
  22636. this.staticCache.set(type, staticMembers);
  22637. }
  22638. return staticMembers;
  22639. };
  22640. StaticReflector.prototype.findParentType = function (type, classMetadata) {
  22641. var parentType = this.trySimplify(type, classMetadata['extends']);
  22642. if (parentType instanceof StaticSymbol) {
  22643. return parentType;
  22644. }
  22645. };
  22646. StaticReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
  22647. if (!(type instanceof StaticSymbol)) {
  22648. this.reportError(new Error("hasLifecycleHook received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  22649. }
  22650. try {
  22651. return !!this._methodNames(type)[lcProperty];
  22652. }
  22653. catch (e) {
  22654. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  22655. throw e;
  22656. }
  22657. };
  22658. StaticReflector.prototype.guards = function (type) {
  22659. var e_1, _a;
  22660. if (!(type instanceof StaticSymbol)) {
  22661. this.reportError(new Error("guards received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  22662. return {};
  22663. }
  22664. var staticMembers = this._staticMembers(type);
  22665. var result = {};
  22666. try {
  22667. for (var staticMembers_1 = __values(staticMembers), staticMembers_1_1 = staticMembers_1.next(); !staticMembers_1_1.done; staticMembers_1_1 = staticMembers_1.next()) {
  22668. var name_1 = staticMembers_1_1.value;
  22669. if (name_1.endsWith(TYPEGUARD_POSTFIX)) {
  22670. var property = name_1.substr(0, name_1.length - TYPEGUARD_POSTFIX.length);
  22671. var value = void 0;
  22672. if (property.endsWith(USE_IF)) {
  22673. property = name_1.substr(0, property.length - USE_IF.length);
  22674. value = USE_IF;
  22675. }
  22676. else {
  22677. value = this.getStaticSymbol(type.filePath, type.name, [name_1]);
  22678. }
  22679. result[property] = value;
  22680. }
  22681. }
  22682. }
  22683. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  22684. finally {
  22685. try {
  22686. if (staticMembers_1_1 && !staticMembers_1_1.done && (_a = staticMembers_1.return)) _a.call(staticMembers_1);
  22687. }
  22688. finally { if (e_1) throw e_1.error; }
  22689. }
  22690. return result;
  22691. };
  22692. StaticReflector.prototype._registerDecoratorOrConstructor = function (type, ctor) {
  22693. this.conversionMap.set(type, function (context, args) { return new (ctor.bind.apply(ctor, __spread([void 0], args)))(); });
  22694. };
  22695. StaticReflector.prototype._registerFunction = function (type, fn) {
  22696. this.conversionMap.set(type, function (context, args) { return fn.apply(undefined, args); });
  22697. };
  22698. StaticReflector.prototype.initializeConversionMap = function () {
  22699. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
  22700. this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
  22701. this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
  22702. this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
  22703. this.ANALYZE_FOR_ENTRY_COMPONENTS =
  22704. this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
  22705. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  22706. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  22707. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  22708. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
  22709. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  22710. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
  22711. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
  22712. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
  22713. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
  22714. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
  22715. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
  22716. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
  22717. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
  22718. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
  22719. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
  22720. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
  22721. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
  22722. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
  22723. // Note: Some metadata classes can be used directly with Provider.deps.
  22724. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  22725. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  22726. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  22727. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  22728. };
  22729. /**
  22730. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  22731. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  22732. *
  22733. * @param declarationFile the absolute path of the file where the symbol is declared
  22734. * @param name the name of the type.
  22735. */
  22736. StaticReflector.prototype.getStaticSymbol = function (declarationFile, name, members) {
  22737. return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
  22738. };
  22739. /**
  22740. * Simplify but discard any errors
  22741. */
  22742. StaticReflector.prototype.trySimplify = function (context, value) {
  22743. var originalRecorder = this.errorRecorder;
  22744. this.errorRecorder = function (error, fileName) { };
  22745. var result = this.simplify(context, value);
  22746. this.errorRecorder = originalRecorder;
  22747. return result;
  22748. };
  22749. /** @internal */
  22750. StaticReflector.prototype.simplify = function (context, value, lazy) {
  22751. if (lazy === void 0) { lazy = false; }
  22752. var self = this;
  22753. var scope = BindingScope$1.empty;
  22754. var calling = new Map();
  22755. function simplifyInContext(context, value, depth, references) {
  22756. function resolveReferenceValue(staticSymbol) {
  22757. var resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
  22758. return resolvedSymbol ? resolvedSymbol.metadata : null;
  22759. }
  22760. function simplifyEagerly(value) {
  22761. return simplifyInContext(context, value, depth, 0);
  22762. }
  22763. function simplifyLazily(value) {
  22764. return simplifyInContext(context, value, depth, references + 1);
  22765. }
  22766. function simplifyNested(nestedContext, value) {
  22767. if (nestedContext === context) {
  22768. // If the context hasn't changed let the exception propagate unmodified.
  22769. return simplifyInContext(nestedContext, value, depth + 1, references);
  22770. }
  22771. try {
  22772. return simplifyInContext(nestedContext, value, depth + 1, references);
  22773. }
  22774. catch (e) {
  22775. if (isMetadataError(e)) {
  22776. // Propagate the message text up but add a message to the chain that explains how we got
  22777. // here.
  22778. // e.chain implies e.symbol
  22779. var summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
  22780. var summary = "'" + nestedContext.name + "' " + summaryMsg;
  22781. var chain = { message: summary, position: e.position, next: e.chain };
  22782. // TODO(chuckj): retrieve the position information indirectly from the collectors node
  22783. // map if the metadata is from a .ts file.
  22784. self.error({
  22785. message: e.message,
  22786. advise: e.advise,
  22787. context: e.context, chain: chain,
  22788. symbol: nestedContext
  22789. }, context);
  22790. }
  22791. else {
  22792. // It is probably an internal error.
  22793. throw e;
  22794. }
  22795. }
  22796. }
  22797. function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
  22798. if (targetFunction && targetFunction['__symbolic'] == 'function') {
  22799. if (calling.get(functionSymbol)) {
  22800. self.error({
  22801. message: 'Recursion is not supported',
  22802. summary: "called '" + functionSymbol.name + "' recursively",
  22803. value: targetFunction
  22804. }, functionSymbol);
  22805. }
  22806. try {
  22807. var value_1 = targetFunction['value'];
  22808. if (value_1 && (depth != 0 || value_1.__symbolic != 'error')) {
  22809. var parameters = targetFunction['parameters'];
  22810. var defaults = targetFunction.defaults;
  22811. args = args.map(function (arg) { return simplifyNested(context, arg); })
  22812. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  22813. if (defaults && defaults.length > args.length) {
  22814. args.push.apply(args, __spread(defaults.slice(args.length).map(function (value) { return simplify(value); })));
  22815. }
  22816. calling.set(functionSymbol, true);
  22817. var functionScope = BindingScope$1.build();
  22818. for (var i = 0; i < parameters.length; i++) {
  22819. functionScope.define(parameters[i], args[i]);
  22820. }
  22821. var oldScope = scope;
  22822. var result_1;
  22823. try {
  22824. scope = functionScope.done();
  22825. result_1 = simplifyNested(functionSymbol, value_1);
  22826. }
  22827. finally {
  22828. scope = oldScope;
  22829. }
  22830. return result_1;
  22831. }
  22832. }
  22833. finally {
  22834. calling.delete(functionSymbol);
  22835. }
  22836. }
  22837. if (depth === 0) {
  22838. // If depth is 0 we are evaluating the top level expression that is describing element
  22839. // decorator. In this case, it is a decorator we don't understand, such as a custom
  22840. // non-angular decorator, and we should just ignore it.
  22841. return IGNORE;
  22842. }
  22843. var position = undefined;
  22844. if (targetExpression && targetExpression.__symbolic == 'resolved') {
  22845. var line = targetExpression.line;
  22846. var character = targetExpression.character;
  22847. var fileName = targetExpression.fileName;
  22848. if (fileName != null && line != null && character != null) {
  22849. position = { fileName: fileName, line: line, column: character };
  22850. }
  22851. }
  22852. self.error({
  22853. message: FUNCTION_CALL_NOT_SUPPORTED,
  22854. context: functionSymbol,
  22855. value: targetFunction, position: position
  22856. }, context);
  22857. }
  22858. function simplify(expression) {
  22859. var e_2, _a, e_3, _b;
  22860. if (isPrimitive(expression)) {
  22861. return expression;
  22862. }
  22863. if (expression instanceof Array) {
  22864. var result_2 = [];
  22865. try {
  22866. for (var _c = __values(expression), _d = _c.next(); !_d.done; _d = _c.next()) {
  22867. var item = _d.value;
  22868. // Check for a spread expression
  22869. if (item && item.__symbolic === 'spread') {
  22870. // We call with references as 0 because we require the actual value and cannot
  22871. // tolerate a reference here.
  22872. var spreadArray = simplifyEagerly(item.expression);
  22873. if (Array.isArray(spreadArray)) {
  22874. try {
  22875. for (var spreadArray_1 = __values(spreadArray), spreadArray_1_1 = spreadArray_1.next(); !spreadArray_1_1.done; spreadArray_1_1 = spreadArray_1.next()) {
  22876. var spreadItem = spreadArray_1_1.value;
  22877. result_2.push(spreadItem);
  22878. }
  22879. }
  22880. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  22881. finally {
  22882. try {
  22883. if (spreadArray_1_1 && !spreadArray_1_1.done && (_b = spreadArray_1.return)) _b.call(spreadArray_1);
  22884. }
  22885. finally { if (e_3) throw e_3.error; }
  22886. }
  22887. continue;
  22888. }
  22889. }
  22890. var value_2 = simplify(item);
  22891. if (shouldIgnore(value_2)) {
  22892. continue;
  22893. }
  22894. result_2.push(value_2);
  22895. }
  22896. }
  22897. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  22898. finally {
  22899. try {
  22900. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  22901. }
  22902. finally { if (e_2) throw e_2.error; }
  22903. }
  22904. return result_2;
  22905. }
  22906. if (expression instanceof StaticSymbol) {
  22907. // Stop simplification at builtin symbols or if we are in a reference context and
  22908. // the symbol doesn't have members.
  22909. if (expression === self.injectionToken || self.conversionMap.has(expression) ||
  22910. (references > 0 && !expression.members.length)) {
  22911. return expression;
  22912. }
  22913. else {
  22914. var staticSymbol = expression;
  22915. var declarationValue = resolveReferenceValue(staticSymbol);
  22916. if (declarationValue != null) {
  22917. return simplifyNested(staticSymbol, declarationValue);
  22918. }
  22919. else {
  22920. return staticSymbol;
  22921. }
  22922. }
  22923. }
  22924. if (expression) {
  22925. if (expression['__symbolic']) {
  22926. var staticSymbol = void 0;
  22927. switch (expression['__symbolic']) {
  22928. case 'binop':
  22929. var left = simplify(expression['left']);
  22930. if (shouldIgnore(left))
  22931. return left;
  22932. var right = simplify(expression['right']);
  22933. if (shouldIgnore(right))
  22934. return right;
  22935. switch (expression['operator']) {
  22936. case '&&':
  22937. return left && right;
  22938. case '||':
  22939. return left || right;
  22940. case '|':
  22941. return left | right;
  22942. case '^':
  22943. return left ^ right;
  22944. case '&':
  22945. return left & right;
  22946. case '==':
  22947. return left == right;
  22948. case '!=':
  22949. return left != right;
  22950. case '===':
  22951. return left === right;
  22952. case '!==':
  22953. return left !== right;
  22954. case '<':
  22955. return left < right;
  22956. case '>':
  22957. return left > right;
  22958. case '<=':
  22959. return left <= right;
  22960. case '>=':
  22961. return left >= right;
  22962. case '<<':
  22963. return left << right;
  22964. case '>>':
  22965. return left >> right;
  22966. case '+':
  22967. return left + right;
  22968. case '-':
  22969. return left - right;
  22970. case '*':
  22971. return left * right;
  22972. case '/':
  22973. return left / right;
  22974. case '%':
  22975. return left % right;
  22976. }
  22977. return null;
  22978. case 'if':
  22979. var condition = simplify(expression['condition']);
  22980. return condition ? simplify(expression['thenExpression']) :
  22981. simplify(expression['elseExpression']);
  22982. case 'pre':
  22983. var operand = simplify(expression['operand']);
  22984. if (shouldIgnore(operand))
  22985. return operand;
  22986. switch (expression['operator']) {
  22987. case '+':
  22988. return operand;
  22989. case '-':
  22990. return -operand;
  22991. case '!':
  22992. return !operand;
  22993. case '~':
  22994. return ~operand;
  22995. }
  22996. return null;
  22997. case 'index':
  22998. var indexTarget = simplifyEagerly(expression['expression']);
  22999. var index = simplifyEagerly(expression['index']);
  23000. if (indexTarget && isPrimitive(index))
  23001. return indexTarget[index];
  23002. return null;
  23003. case 'select':
  23004. var member = expression['member'];
  23005. var selectContext = context;
  23006. var selectTarget = simplify(expression['expression']);
  23007. if (selectTarget instanceof StaticSymbol) {
  23008. var members = selectTarget.members.concat(member);
  23009. selectContext =
  23010. self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
  23011. var declarationValue = resolveReferenceValue(selectContext);
  23012. if (declarationValue != null) {
  23013. return simplifyNested(selectContext, declarationValue);
  23014. }
  23015. else {
  23016. return selectContext;
  23017. }
  23018. }
  23019. if (selectTarget && isPrimitive(member))
  23020. return simplifyNested(selectContext, selectTarget[member]);
  23021. return null;
  23022. case 'reference':
  23023. // Note: This only has to deal with variable references, as symbol references have
  23024. // been converted into 'resolved'
  23025. // in the StaticSymbolResolver.
  23026. var name_2 = expression['name'];
  23027. var localValue = scope.resolve(name_2);
  23028. if (localValue != BindingScope$1.missing) {
  23029. return localValue;
  23030. }
  23031. break;
  23032. case 'resolved':
  23033. try {
  23034. return simplify(expression.symbol);
  23035. }
  23036. catch (e) {
  23037. // If an error is reported evaluating the symbol record the position of the
  23038. // reference in the error so it can
  23039. // be reported in the error message generated from the exception.
  23040. if (isMetadataError(e) && expression.fileName != null &&
  23041. expression.line != null && expression.character != null) {
  23042. e.position = {
  23043. fileName: expression.fileName,
  23044. line: expression.line,
  23045. column: expression.character
  23046. };
  23047. }
  23048. throw e;
  23049. }
  23050. case 'class':
  23051. return context;
  23052. case 'function':
  23053. return context;
  23054. case 'new':
  23055. case 'call':
  23056. // Determine if the function is a built-in conversion
  23057. staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
  23058. if (staticSymbol instanceof StaticSymbol) {
  23059. if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
  23060. // if somebody calls new InjectionToken, don't create an InjectionToken,
  23061. // but rather return the symbol to which the InjectionToken is assigned to.
  23062. // OpaqueToken is supported too as it is required by the language service to
  23063. // support v4 and prior versions of Angular.
  23064. return context;
  23065. }
  23066. var argExpressions = expression['arguments'] || [];
  23067. var converter = self.conversionMap.get(staticSymbol);
  23068. if (converter) {
  23069. var args = argExpressions.map(function (arg) { return simplifyNested(context, arg); })
  23070. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  23071. return converter(context, args);
  23072. }
  23073. else {
  23074. // Determine if the function is one we can simplify.
  23075. var targetFunction = resolveReferenceValue(staticSymbol);
  23076. return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
  23077. }
  23078. }
  23079. return IGNORE;
  23080. case 'error':
  23081. var message = expression.message;
  23082. if (expression['line'] != null) {
  23083. self.error({
  23084. message: message,
  23085. context: expression.context,
  23086. value: expression,
  23087. position: {
  23088. fileName: expression['fileName'],
  23089. line: expression['line'],
  23090. column: expression['character']
  23091. }
  23092. }, context);
  23093. }
  23094. else {
  23095. self.error({ message: message, context: expression.context }, context);
  23096. }
  23097. return IGNORE;
  23098. case 'ignore':
  23099. return expression;
  23100. }
  23101. return null;
  23102. }
  23103. return mapStringMap(expression, function (value, name) {
  23104. if (REFERENCE_SET.has(name)) {
  23105. if (name === USE_VALUE$1 && PROVIDE in expression) {
  23106. // If this is a provider expression, check for special tokens that need the value
  23107. // during analysis.
  23108. var provide = simplify(expression.provide);
  23109. if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
  23110. return simplify(value);
  23111. }
  23112. }
  23113. return simplifyLazily(value);
  23114. }
  23115. return simplify(value);
  23116. });
  23117. }
  23118. return IGNORE;
  23119. }
  23120. return simplify(value);
  23121. }
  23122. var result;
  23123. try {
  23124. result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
  23125. }
  23126. catch (e) {
  23127. if (this.errorRecorder) {
  23128. this.reportError(e, context);
  23129. }
  23130. else {
  23131. throw formatMetadataError(e, context);
  23132. }
  23133. }
  23134. if (shouldIgnore(result)) {
  23135. return undefined;
  23136. }
  23137. return result;
  23138. };
  23139. StaticReflector.prototype.getTypeMetadata = function (type) {
  23140. var resolvedSymbol = this.symbolResolver.resolveSymbol(type);
  23141. return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
  23142. { __symbolic: 'class' };
  23143. };
  23144. StaticReflector.prototype.reportError = function (error, context, path) {
  23145. if (this.errorRecorder) {
  23146. this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
  23147. }
  23148. else {
  23149. throw error;
  23150. }
  23151. };
  23152. StaticReflector.prototype.error = function (_a, reportingContext) {
  23153. var message = _a.message, summary = _a.summary, advise = _a.advise, position = _a.position, context = _a.context, value = _a.value, symbol = _a.symbol, chain = _a.chain;
  23154. this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
  23155. };
  23156. return StaticReflector;
  23157. }());
  23158. var METADATA_ERROR = 'ngMetadataError';
  23159. function metadataError(message, summary, advise, position, symbol, context, chain) {
  23160. var error = syntaxError(message);
  23161. error[METADATA_ERROR] = true;
  23162. if (advise)
  23163. error.advise = advise;
  23164. if (position)
  23165. error.position = position;
  23166. if (summary)
  23167. error.summary = summary;
  23168. if (context)
  23169. error.context = context;
  23170. if (chain)
  23171. error.chain = chain;
  23172. if (symbol)
  23173. error.symbol = symbol;
  23174. return error;
  23175. }
  23176. function isMetadataError(error) {
  23177. return !!error[METADATA_ERROR];
  23178. }
  23179. var REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
  23180. var VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
  23181. var DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
  23182. var COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
  23183. var FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
  23184. var REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
  23185. var LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
  23186. function expandedMessage(message, context) {
  23187. switch (message) {
  23188. case REFERENCE_TO_NONEXPORTED_CLASS:
  23189. if (context && context.className) {
  23190. return "References to a non-exported class are not supported in decorators but " + context.className + " was referenced.";
  23191. }
  23192. break;
  23193. case VARIABLE_NOT_INITIALIZED:
  23194. return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
  23195. case DESTRUCTURE_NOT_SUPPORTED:
  23196. return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
  23197. case COULD_NOT_RESOLVE_TYPE:
  23198. if (context && context.typeName) {
  23199. return "Could not resolve type " + context.typeName;
  23200. }
  23201. break;
  23202. case FUNCTION_CALL_NOT_SUPPORTED:
  23203. if (context && context.name) {
  23204. return "Function calls are not supported in decorators but '" + context.name + "' was called";
  23205. }
  23206. return 'Function calls are not supported in decorators';
  23207. case REFERENCE_TO_LOCAL_SYMBOL:
  23208. if (context && context.name) {
  23209. return "Reference to a local (non-exported) symbols are not supported in decorators but '" + context.name + "' was referenced";
  23210. }
  23211. break;
  23212. case LAMBDA_NOT_SUPPORTED:
  23213. return "Function expressions are not supported in decorators";
  23214. }
  23215. return message;
  23216. }
  23217. function messageAdvise(message, context) {
  23218. switch (message) {
  23219. case REFERENCE_TO_NONEXPORTED_CLASS:
  23220. if (context && context.className) {
  23221. return "Consider exporting '" + context.className + "'";
  23222. }
  23223. break;
  23224. case DESTRUCTURE_NOT_SUPPORTED:
  23225. return 'Consider simplifying to avoid destructuring';
  23226. case REFERENCE_TO_LOCAL_SYMBOL:
  23227. if (context && context.name) {
  23228. return "Consider exporting '" + context.name + "'";
  23229. }
  23230. break;
  23231. case LAMBDA_NOT_SUPPORTED:
  23232. return "Consider changing the function expression into an exported function";
  23233. }
  23234. return undefined;
  23235. }
  23236. function errorSummary(error) {
  23237. if (error.summary) {
  23238. return error.summary;
  23239. }
  23240. switch (error.message) {
  23241. case REFERENCE_TO_NONEXPORTED_CLASS:
  23242. if (error.context && error.context.className) {
  23243. return "references non-exported class " + error.context.className;
  23244. }
  23245. break;
  23246. case VARIABLE_NOT_INITIALIZED:
  23247. return 'is not initialized';
  23248. case DESTRUCTURE_NOT_SUPPORTED:
  23249. return 'is a destructured variable';
  23250. case COULD_NOT_RESOLVE_TYPE:
  23251. return 'could not be resolved';
  23252. case FUNCTION_CALL_NOT_SUPPORTED:
  23253. if (error.context && error.context.name) {
  23254. return "calls '" + error.context.name + "'";
  23255. }
  23256. return "calls a function";
  23257. case REFERENCE_TO_LOCAL_SYMBOL:
  23258. if (error.context && error.context.name) {
  23259. return "references local variable " + error.context.name;
  23260. }
  23261. return "references a local variable";
  23262. }
  23263. return 'contains the error';
  23264. }
  23265. function mapStringMap(input, transform) {
  23266. if (!input)
  23267. return {};
  23268. var result = {};
  23269. Object.keys(input).forEach(function (key) {
  23270. var value = transform(input[key], key);
  23271. if (!shouldIgnore(value)) {
  23272. if (HIDDEN_KEY.test(key)) {
  23273. Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
  23274. }
  23275. else {
  23276. result[key] = value;
  23277. }
  23278. }
  23279. });
  23280. return result;
  23281. }
  23282. function isPrimitive(o) {
  23283. return o === null || (typeof o !== 'function' && typeof o !== 'object');
  23284. }
  23285. var BindingScope$1 = /** @class */ (function () {
  23286. function BindingScope() {
  23287. }
  23288. BindingScope.build = function () {
  23289. var current = new Map();
  23290. return {
  23291. define: function (name, value) {
  23292. current.set(name, value);
  23293. return this;
  23294. },
  23295. done: function () {
  23296. return current.size > 0 ? new PopulatedScope(current) : BindingScope.empty;
  23297. }
  23298. };
  23299. };
  23300. BindingScope.missing = {};
  23301. BindingScope.empty = { resolve: function (name) { return BindingScope.missing; } };
  23302. return BindingScope;
  23303. }());
  23304. var PopulatedScope = /** @class */ (function (_super) {
  23305. __extends(PopulatedScope, _super);
  23306. function PopulatedScope(bindings) {
  23307. var _this = _super.call(this) || this;
  23308. _this.bindings = bindings;
  23309. return _this;
  23310. }
  23311. PopulatedScope.prototype.resolve = function (name) {
  23312. return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
  23313. };
  23314. return PopulatedScope;
  23315. }(BindingScope$1));
  23316. function formatMetadataMessageChain(chain, advise) {
  23317. var expanded = expandedMessage(chain.message, chain.context);
  23318. var nesting = chain.symbol ? " in '" + chain.symbol.name + "'" : '';
  23319. var message = "" + expanded + nesting;
  23320. var position = chain.position;
  23321. var next = chain.next ?
  23322. formatMetadataMessageChain(chain.next, advise) :
  23323. advise ? { message: advise } : undefined;
  23324. return { message: message, position: position, next: next };
  23325. }
  23326. function formatMetadataError(e, context) {
  23327. if (isMetadataError(e)) {
  23328. // Produce a formatted version of the and leaving enough information in the original error
  23329. // to recover the formatting information to eventually produce a diagnostic error message.
  23330. var position = e.position;
  23331. var chain = {
  23332. message: "Error during template compile of '" + context.name + "'",
  23333. position: position,
  23334. next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
  23335. };
  23336. var advise = e.advise || messageAdvise(e.message, e.context);
  23337. return formattedError(formatMetadataMessageChain(chain, advise));
  23338. }
  23339. return e;
  23340. }
  23341. /**
  23342. * @license
  23343. * Copyright Google Inc. All Rights Reserved.
  23344. *
  23345. * Use of this source code is governed by an MIT-style license that can be
  23346. * found in the LICENSE file at https://angular.io/license
  23347. */
  23348. var AotSummaryResolver = /** @class */ (function () {
  23349. function AotSummaryResolver(host, staticSymbolCache) {
  23350. this.host = host;
  23351. this.staticSymbolCache = staticSymbolCache;
  23352. // Note: this will only contain StaticSymbols without members!
  23353. this.summaryCache = new Map();
  23354. this.loadedFilePaths = new Map();
  23355. // Note: this will only contain StaticSymbols without members!
  23356. this.importAs = new Map();
  23357. this.knownFileNameToModuleNames = new Map();
  23358. }
  23359. AotSummaryResolver.prototype.isLibraryFile = function (filePath) {
  23360. // Note: We need to strip the .ngfactory. file path,
  23361. // so this method also works for generated files
  23362. // (for which host.isSourceFile will always return false).
  23363. return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
  23364. };
  23365. AotSummaryResolver.prototype.toSummaryFileName = function (filePath, referringSrcFileName) {
  23366. return this.host.toSummaryFileName(filePath, referringSrcFileName);
  23367. };
  23368. AotSummaryResolver.prototype.fromSummaryFileName = function (fileName, referringLibFileName) {
  23369. return this.host.fromSummaryFileName(fileName, referringLibFileName);
  23370. };
  23371. AotSummaryResolver.prototype.resolveSummary = function (staticSymbol) {
  23372. var rootSymbol = staticSymbol.members.length ?
  23373. this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
  23374. staticSymbol;
  23375. var summary = this.summaryCache.get(rootSymbol);
  23376. if (!summary) {
  23377. this._loadSummaryFile(staticSymbol.filePath);
  23378. summary = this.summaryCache.get(staticSymbol);
  23379. }
  23380. return (rootSymbol === staticSymbol && summary) || null;
  23381. };
  23382. AotSummaryResolver.prototype.getSymbolsOf = function (filePath) {
  23383. if (this._loadSummaryFile(filePath)) {
  23384. return Array.from(this.summaryCache.keys()).filter(function (symbol) { return symbol.filePath === filePath; });
  23385. }
  23386. return null;
  23387. };
  23388. AotSummaryResolver.prototype.getImportAs = function (staticSymbol) {
  23389. staticSymbol.assertNoMembers();
  23390. return this.importAs.get(staticSymbol);
  23391. };
  23392. /**
  23393. * Converts a file path to a module name that can be used as an `import`.
  23394. */
  23395. AotSummaryResolver.prototype.getKnownModuleName = function (importedFilePath) {
  23396. return this.knownFileNameToModuleNames.get(importedFilePath) || null;
  23397. };
  23398. AotSummaryResolver.prototype.addSummary = function (summary) { this.summaryCache.set(summary.symbol, summary); };
  23399. AotSummaryResolver.prototype._loadSummaryFile = function (filePath) {
  23400. var _this = this;
  23401. var hasSummary = this.loadedFilePaths.get(filePath);
  23402. if (hasSummary != null) {
  23403. return hasSummary;
  23404. }
  23405. var json = null;
  23406. if (this.isLibraryFile(filePath)) {
  23407. var summaryFilePath = summaryFileName(filePath);
  23408. try {
  23409. json = this.host.loadSummary(summaryFilePath);
  23410. }
  23411. catch (e) {
  23412. console.error("Error loading summary file " + summaryFilePath);
  23413. throw e;
  23414. }
  23415. }
  23416. hasSummary = json != null;
  23417. this.loadedFilePaths.set(filePath, hasSummary);
  23418. if (json) {
  23419. var _a = deserializeSummaries(this.staticSymbolCache, this, filePath, json), moduleName = _a.moduleName, summaries = _a.summaries, importAs = _a.importAs;
  23420. summaries.forEach(function (summary) { return _this.summaryCache.set(summary.symbol, summary); });
  23421. if (moduleName) {
  23422. this.knownFileNameToModuleNames.set(filePath, moduleName);
  23423. }
  23424. importAs.forEach(function (importAs) { _this.importAs.set(importAs.symbol, importAs.importAs); });
  23425. }
  23426. return hasSummary;
  23427. };
  23428. return AotSummaryResolver;
  23429. }());
  23430. /**
  23431. * @license
  23432. * Copyright Google Inc. All Rights Reserved.
  23433. *
  23434. * Use of this source code is governed by an MIT-style license that can be
  23435. * found in the LICENSE file at https://angular.io/license
  23436. */
  23437. var JitSummaryResolver = /** @class */ (function () {
  23438. function JitSummaryResolver() {
  23439. this._summaries = new Map();
  23440. }
  23441. JitSummaryResolver.prototype.isLibraryFile = function () { return false; };
  23442. JitSummaryResolver.prototype.toSummaryFileName = function (fileName) { return fileName; };
  23443. JitSummaryResolver.prototype.fromSummaryFileName = function (fileName) { return fileName; };
  23444. JitSummaryResolver.prototype.resolveSummary = function (reference) {
  23445. return this._summaries.get(reference) || null;
  23446. };
  23447. JitSummaryResolver.prototype.getSymbolsOf = function () { return []; };
  23448. JitSummaryResolver.prototype.getImportAs = function (reference) { return reference; };
  23449. JitSummaryResolver.prototype.getKnownModuleName = function (fileName) { return null; };
  23450. JitSummaryResolver.prototype.addSummary = function (summary) { this._summaries.set(summary.symbol, summary); };
  23451. return JitSummaryResolver;
  23452. }());
  23453. /**
  23454. * @license
  23455. * Copyright Google Inc. All Rights Reserved.
  23456. *
  23457. * Use of this source code is governed by an MIT-style license that can be
  23458. * found in the LICENSE file at https://angular.io/license
  23459. */
  23460. /**
  23461. * @license
  23462. * Copyright Google Inc. All Rights Reserved.
  23463. *
  23464. * Use of this source code is governed by an MIT-style license that can be
  23465. * found in the LICENSE file at https://angular.io/license
  23466. */
  23467. /**
  23468. * @license
  23469. * Copyright Google Inc. All Rights Reserved.
  23470. *
  23471. * Use of this source code is governed by an MIT-style license that can be
  23472. * found in the LICENSE file at https://angular.io/license
  23473. */
  23474. /**
  23475. * @license
  23476. * Copyright Google Inc. All Rights Reserved.
  23477. *
  23478. * Use of this source code is governed by an MIT-style license that can be
  23479. * found in the LICENSE file at https://angular.io/license
  23480. */
  23481. function createOfflineCompileUrlResolver() {
  23482. return new UrlResolver('.');
  23483. }
  23484. var UrlResolver = /** @class */ (function () {
  23485. function UrlResolverImpl(_packagePrefix) {
  23486. if (_packagePrefix === void 0) { _packagePrefix = null; }
  23487. this._packagePrefix = _packagePrefix;
  23488. }
  23489. /**
  23490. * Resolves the `url` given the `baseUrl`:
  23491. * - when the `url` is null, the `baseUrl` is returned,
  23492. * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
  23493. * `baseUrl` and `url`,
  23494. * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
  23495. * returned as is (ignoring the `baseUrl`)
  23496. */
  23497. UrlResolverImpl.prototype.resolve = function (baseUrl, url) {
  23498. var resolvedUrl = url;
  23499. if (baseUrl != null && baseUrl.length > 0) {
  23500. resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
  23501. }
  23502. var resolvedParts = _split(resolvedUrl);
  23503. var prefix = this._packagePrefix;
  23504. if (prefix != null && resolvedParts != null &&
  23505. resolvedParts[_ComponentIndex.Scheme] == 'package') {
  23506. var path = resolvedParts[_ComponentIndex.Path];
  23507. prefix = prefix.replace(/\/+$/, '');
  23508. path = path.replace(/^\/+/, '');
  23509. return prefix + "/" + path;
  23510. }
  23511. return resolvedUrl;
  23512. };
  23513. return UrlResolverImpl;
  23514. }());
  23515. // The code below is adapted from Traceur:
  23516. // https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
  23517. /**
  23518. * Builds a URI string from already-encoded parts.
  23519. *
  23520. * No encoding is performed. Any component may be omitted as either null or
  23521. * undefined.
  23522. *
  23523. * @param opt_scheme The scheme such as 'http'.
  23524. * @param opt_userInfo The user name before the '@'.
  23525. * @param opt_domain The domain such as 'www.google.com', already
  23526. * URI-encoded.
  23527. * @param opt_port The port number.
  23528. * @param opt_path The path, already URI-encoded. If it is not
  23529. * empty, it must begin with a slash.
  23530. * @param opt_queryData The URI-encoded query data.
  23531. * @param opt_fragment The URI-encoded fragment identifier.
  23532. * @return The fully combined URI.
  23533. */
  23534. function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
  23535. var out = [];
  23536. if (opt_scheme != null) {
  23537. out.push(opt_scheme + ':');
  23538. }
  23539. if (opt_domain != null) {
  23540. out.push('//');
  23541. if (opt_userInfo != null) {
  23542. out.push(opt_userInfo + '@');
  23543. }
  23544. out.push(opt_domain);
  23545. if (opt_port != null) {
  23546. out.push(':' + opt_port);
  23547. }
  23548. }
  23549. if (opt_path != null) {
  23550. out.push(opt_path);
  23551. }
  23552. if (opt_queryData != null) {
  23553. out.push('?' + opt_queryData);
  23554. }
  23555. if (opt_fragment != null) {
  23556. out.push('#' + opt_fragment);
  23557. }
  23558. return out.join('');
  23559. }
  23560. /**
  23561. * A regular expression for breaking a URI into its component parts.
  23562. *
  23563. * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
  23564. * As the "first-match-wins" algorithm is identical to the "greedy"
  23565. * disambiguation method used by POSIX regular expressions, it is natural and
  23566. * commonplace to use a regular expression for parsing the potential five
  23567. * components of a URI reference.
  23568. *
  23569. * The following line is the regular expression for breaking-down a
  23570. * well-formed URI reference into its components.
  23571. *
  23572. * <pre>
  23573. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  23574. * 12 3 4 5 6 7 8 9
  23575. * </pre>
  23576. *
  23577. * The numbers in the second line above are only to assist readability; they
  23578. * indicate the reference points for each subexpression (i.e., each paired
  23579. * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
  23580. * For example, matching the above expression to
  23581. * <pre>
  23582. * http://www.ics.uci.edu/pub/ietf/uri/#Related
  23583. * </pre>
  23584. * results in the following subexpression matches:
  23585. * <pre>
  23586. * $1 = http:
  23587. * $2 = http
  23588. * $3 = //www.ics.uci.edu
  23589. * $4 = www.ics.uci.edu
  23590. * $5 = /pub/ietf/uri/
  23591. * $6 = <undefined>
  23592. * $7 = <undefined>
  23593. * $8 = #Related
  23594. * $9 = Related
  23595. * </pre>
  23596. * where <undefined> indicates that the component is not present, as is the
  23597. * case for the query component in the above example. Therefore, we can
  23598. * determine the value of the five components as
  23599. * <pre>
  23600. * scheme = $2
  23601. * authority = $4
  23602. * path = $5
  23603. * query = $7
  23604. * fragment = $9
  23605. * </pre>
  23606. *
  23607. * The regular expression has been modified slightly to expose the
  23608. * userInfo, domain, and port separately from the authority.
  23609. * The modified version yields
  23610. * <pre>
  23611. * $1 = http scheme
  23612. * $2 = <undefined> userInfo -\
  23613. * $3 = www.ics.uci.edu domain | authority
  23614. * $4 = <undefined> port -/
  23615. * $5 = /pub/ietf/uri/ path
  23616. * $6 = <undefined> query without ?
  23617. * $7 = Related fragment without #
  23618. * </pre>
  23619. * @internal
  23620. */
  23621. var _splitRe = new RegExp('^' +
  23622. '(?:' +
  23623. '([^:/?#.]+)' + // scheme - ignore special characters
  23624. // used by other URL parts such as :,
  23625. // ?, /, #, and .
  23626. ':)?' +
  23627. '(?://' +
  23628. '(?:([^/?#]*)@)?' + // userInfo
  23629. '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
  23630. // digits, dashes, dots, percent
  23631. // escapes, and unicode characters.
  23632. '(?::([0-9]+))?' + // port
  23633. ')?' +
  23634. '([^?#]+)?' + // path
  23635. '(?:\\?([^#]*))?' + // query
  23636. '(?:#(.*))?' + // fragment
  23637. '$');
  23638. /**
  23639. * The index of each URI component in the return value of goog.uri.utils.split.
  23640. * @enum {number}
  23641. */
  23642. var _ComponentIndex;
  23643. (function (_ComponentIndex) {
  23644. _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
  23645. _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
  23646. _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
  23647. _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
  23648. _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
  23649. _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
  23650. _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
  23651. })(_ComponentIndex || (_ComponentIndex = {}));
  23652. /**
  23653. * Splits a URI into its component parts.
  23654. *
  23655. * Each component can be accessed via the component indices; for example:
  23656. * <pre>
  23657. * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
  23658. * </pre>
  23659. *
  23660. * @param uri The URI string to examine.
  23661. * @return Each component still URI-encoded.
  23662. * Each component that is present will contain the encoded value, whereas
  23663. * components that are not present will be undefined or empty, depending
  23664. * on the browser's regular expression implementation. Never null, since
  23665. * arbitrary strings may still look like path names.
  23666. */
  23667. function _split(uri) {
  23668. return uri.match(_splitRe);
  23669. }
  23670. /**
  23671. * Removes dot segments in given path component, as described in
  23672. * RFC 3986, section 5.2.4.
  23673. *
  23674. * @param path A non-empty path component.
  23675. * @return Path component with removed dot segments.
  23676. */
  23677. function _removeDotSegments(path) {
  23678. if (path == '/')
  23679. return '/';
  23680. var leadingSlash = path[0] == '/' ? '/' : '';
  23681. var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
  23682. var segments = path.split('/');
  23683. var out = [];
  23684. var up = 0;
  23685. for (var pos = 0; pos < segments.length; pos++) {
  23686. var segment = segments[pos];
  23687. switch (segment) {
  23688. case '':
  23689. case '.':
  23690. break;
  23691. case '..':
  23692. if (out.length > 0) {
  23693. out.pop();
  23694. }
  23695. else {
  23696. up++;
  23697. }
  23698. break;
  23699. default:
  23700. out.push(segment);
  23701. }
  23702. }
  23703. if (leadingSlash == '') {
  23704. while (up-- > 0) {
  23705. out.unshift('..');
  23706. }
  23707. if (out.length === 0)
  23708. out.push('.');
  23709. }
  23710. return leadingSlash + out.join('/') + trailingSlash;
  23711. }
  23712. /**
  23713. * Takes an array of the parts from split and canonicalizes the path part
  23714. * and then joins all the parts.
  23715. */
  23716. function _joinAndCanonicalizePath(parts) {
  23717. var path = parts[_ComponentIndex.Path];
  23718. path = path == null ? '' : _removeDotSegments(path);
  23719. parts[_ComponentIndex.Path] = path;
  23720. return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
  23721. }
  23722. /**
  23723. * Resolves a URL.
  23724. * @param base The URL acting as the base URL.
  23725. * @param to The URL to resolve.
  23726. */
  23727. function _resolveUrl(base, url) {
  23728. var parts = _split(encodeURI(url));
  23729. var baseParts = _split(base);
  23730. if (parts[_ComponentIndex.Scheme] != null) {
  23731. return _joinAndCanonicalizePath(parts);
  23732. }
  23733. else {
  23734. parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
  23735. }
  23736. for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
  23737. if (parts[i] == null) {
  23738. parts[i] = baseParts[i];
  23739. }
  23740. }
  23741. if (parts[_ComponentIndex.Path][0] == '/') {
  23742. return _joinAndCanonicalizePath(parts);
  23743. }
  23744. var path = baseParts[_ComponentIndex.Path];
  23745. if (path == null)
  23746. path = '/';
  23747. var index = path.lastIndexOf('/');
  23748. path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
  23749. parts[_ComponentIndex.Path] = path;
  23750. return _joinAndCanonicalizePath(parts);
  23751. }
  23752. /**
  23753. * @license
  23754. * Copyright Google Inc. All Rights Reserved.
  23755. *
  23756. * Use of this source code is governed by an MIT-style license that can be
  23757. * found in the LICENSE file at https://angular.io/license
  23758. */
  23759. /**
  23760. * @license
  23761. * Copyright Google Inc. All Rights Reserved.
  23762. *
  23763. * Use of this source code is governed by an MIT-style license that can be
  23764. * found in the LICENSE file at https://angular.io/license
  23765. */
  23766. /**
  23767. * @license
  23768. * Copyright Google Inc. All Rights Reserved.
  23769. *
  23770. * Use of this source code is governed by an MIT-style license that can be
  23771. * found in the LICENSE file at https://angular.io/license
  23772. */
  23773. /**
  23774. * Processes a template and extract metadata about expressions and symbols within.
  23775. *
  23776. * This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
  23777. * within the template in order to operate.
  23778. *
  23779. * Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
  23780. * by overridden methods from that visitor.
  23781. */
  23782. var TemplateBinder = /** @class */ (function (_super) {
  23783. __extends(TemplateBinder, _super);
  23784. function TemplateBinder(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
  23785. var _this = _super.call(this) || this;
  23786. _this.bindings = bindings;
  23787. _this.symbols = symbols;
  23788. _this.usedPipes = usedPipes;
  23789. _this.nestingLevel = nestingLevel;
  23790. _this.scope = scope;
  23791. _this.template = template;
  23792. _this.level = level;
  23793. _this.pipesUsed = [];
  23794. // Save a bit of processing time by constructing this closure in advance.
  23795. _this.visitNode = function (node) { return node.visit(_this); };
  23796. return _this;
  23797. }
  23798. /**
  23799. * Process a template and extract metadata about expressions and symbols within.
  23800. *
  23801. * @param template the nodes of the template to process
  23802. * @param scope the `Scope` of the template being processed.
  23803. * @returns three maps which contain metadata about the template: `expressions` which interprets
  23804. * special `AST` nodes in expressions as pointing to references or variables declared within the
  23805. * template, `symbols` which maps those variables and references to the nested `Template` which
  23806. * declares them, if any, and `nestingLevel` which associates each `Template` with a integer
  23807. * nesting level (how many levels deep within the template structure the `Template` is), starting
  23808. * at 1.
  23809. */
  23810. TemplateBinder.apply = function (template, scope) {
  23811. var expressions = new Map();
  23812. var symbols = new Map();
  23813. var nestingLevel = new Map();
  23814. var usedPipes = new Set();
  23815. // The top-level template has nesting level 0.
  23816. var binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
  23817. binder.ingest(template);
  23818. return { expressions: expressions, symbols: symbols, nestingLevel: nestingLevel, usedPipes: usedPipes };
  23819. };
  23820. TemplateBinder.prototype.ingest = function (template) {
  23821. if (template instanceof Template) {
  23822. // For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
  23823. // and references were all processed in the scope of the containing template.
  23824. template.variables.forEach(this.visitNode);
  23825. template.children.forEach(this.visitNode);
  23826. // Set the nesting level.
  23827. this.nestingLevel.set(template, this.level);
  23828. }
  23829. else {
  23830. // Visit each node from the top-level template.
  23831. template.forEach(this.visitNode);
  23832. }
  23833. };
  23834. TemplateBinder.prototype.visitElement = function (element) {
  23835. // Visit the inputs, outputs, and children of the element.
  23836. element.inputs.forEach(this.visitNode);
  23837. element.outputs.forEach(this.visitNode);
  23838. element.children.forEach(this.visitNode);
  23839. };
  23840. TemplateBinder.prototype.visitTemplate = function (template) {
  23841. // First, visit inputs, outputs and template attributes of the template node.
  23842. template.inputs.forEach(this.visitNode);
  23843. template.outputs.forEach(this.visitNode);
  23844. template.templateAttrs.forEach(this.visitNode);
  23845. // References are also evaluated in the outer context.
  23846. template.references.forEach(this.visitNode);
  23847. // Next, recurse into the template using its scope, and bumping the nesting level up by one.
  23848. var childScope = this.scope.getChildScope(template);
  23849. var binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
  23850. binder.ingest(template);
  23851. };
  23852. TemplateBinder.prototype.visitVariable = function (variable) {
  23853. // Register the `Variable` as a symbol in the current `Template`.
  23854. if (this.template !== null) {
  23855. this.symbols.set(variable, this.template);
  23856. }
  23857. };
  23858. TemplateBinder.prototype.visitReference = function (reference) {
  23859. // Register the `Reference` as a symbol in the current `Template`.
  23860. if (this.template !== null) {
  23861. this.symbols.set(reference, this.template);
  23862. }
  23863. };
  23864. // Unused template visitors
  23865. TemplateBinder.prototype.visitText = function (text) { };
  23866. TemplateBinder.prototype.visitContent = function (content) { };
  23867. TemplateBinder.prototype.visitTextAttribute = function (attribute) { };
  23868. TemplateBinder.prototype.visitIcu = function (icu) { };
  23869. // The remaining visitors are concerned with processing AST expressions within template bindings
  23870. TemplateBinder.prototype.visitBoundAttribute = function (attribute) { attribute.value.visit(this); };
  23871. TemplateBinder.prototype.visitBoundEvent = function (event) { event.handler.visit(this); };
  23872. TemplateBinder.prototype.visitBoundText = function (text) { text.value.visit(this); };
  23873. TemplateBinder.prototype.visitPipe = function (ast, context) {
  23874. this.usedPipes.add(ast.name);
  23875. return _super.prototype.visitPipe.call(this, ast, context);
  23876. };
  23877. // These five types of AST expressions can refer to expression roots, which could be variables
  23878. // or references in the current scope.
  23879. TemplateBinder.prototype.visitPropertyRead = function (ast, context) {
  23880. this.maybeMap(context, ast, ast.name);
  23881. return _super.prototype.visitPropertyRead.call(this, ast, context);
  23882. };
  23883. TemplateBinder.prototype.visitSafePropertyRead = function (ast, context) {
  23884. this.maybeMap(context, ast, ast.name);
  23885. return _super.prototype.visitSafePropertyRead.call(this, ast, context);
  23886. };
  23887. TemplateBinder.prototype.visitPropertyWrite = function (ast, context) {
  23888. this.maybeMap(context, ast, ast.name);
  23889. return _super.prototype.visitPropertyWrite.call(this, ast, context);
  23890. };
  23891. TemplateBinder.prototype.visitMethodCall = function (ast, context) {
  23892. this.maybeMap(context, ast, ast.name);
  23893. return _super.prototype.visitMethodCall.call(this, ast, context);
  23894. };
  23895. TemplateBinder.prototype.visitSafeMethodCall = function (ast, context) {
  23896. this.maybeMap(context, ast, ast.name);
  23897. return _super.prototype.visitSafeMethodCall.call(this, ast, context);
  23898. };
  23899. TemplateBinder.prototype.maybeMap = function (scope, ast, name) {
  23900. // If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
  23901. // `AST` expression that maps to a `Variable` or `Reference`.
  23902. if (!(ast.receiver instanceof ImplicitReceiver)) {
  23903. return;
  23904. }
  23905. // Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
  23906. // probably a property on the top-level component context.
  23907. var target = this.scope.lookup(name);
  23908. if (target !== null) {
  23909. this.bindings.set(ast, target);
  23910. }
  23911. };
  23912. return TemplateBinder;
  23913. }(RecursiveAstVisitor$1));
  23914. /**
  23915. * @license
  23916. * Copyright Google Inc. All Rights Reserved.
  23917. *
  23918. * Use of this source code is governed by an MIT-style license that can be
  23919. * found in the LICENSE file at https://angular.io/license
  23920. */
  23921. // This file only reexports content of the `src` folder. Keep it that way.
  23922. // This function call has a global side effects and publishes the compiler into global namespace for
  23923. // the late binding of the Compiler to the @angular/core for jit compilation.
  23924. publishFacade(_global);
  23925. /**
  23926. * @license
  23927. * Copyright Google Inc. All Rights Reserved.
  23928. *
  23929. * Use of this source code is governed by an MIT-style license that can be
  23930. * found in the LICENSE file at https://angular.io/license
  23931. */
  23932. // This file only reexports content of the `src` folder. Keep it that way.
  23933. /**
  23934. * @license
  23935. * Copyright Google Inc. All Rights Reserved.
  23936. *
  23937. * Use of this source code is governed by an MIT-style license that can be
  23938. * found in the LICENSE file at https://angular.io/license
  23939. */
  23940. /**
  23941. * @license
  23942. * Copyright Google Inc. All Rights Reserved.
  23943. *
  23944. * Use of this source code is governed by an MIT-style license that can be
  23945. * found in the LICENSE file at https://angular.io/license
  23946. */
  23947. /**
  23948. * @license
  23949. * Copyright Google Inc. All Rights Reserved.
  23950. *
  23951. * Use of this source code is governed by an MIT-style license that can be
  23952. * found in the LICENSE file at https://angular.io/license
  23953. */
  23954. /**
  23955. * An enumeration of basic types.
  23956. *
  23957. * @publicApi
  23958. */
  23959. var BuiltinType$1;
  23960. (function (BuiltinType) {
  23961. /**
  23962. * The type is a type that can hold any other type.
  23963. */
  23964. BuiltinType[BuiltinType["Any"] = 0] = "Any";
  23965. /**
  23966. * The type of a string literal.
  23967. */
  23968. BuiltinType[BuiltinType["String"] = 1] = "String";
  23969. /**
  23970. * The type of a numeric literal.
  23971. */
  23972. BuiltinType[BuiltinType["Number"] = 2] = "Number";
  23973. /**
  23974. * The type of the `true` and `false` literals.
  23975. */
  23976. BuiltinType[BuiltinType["Boolean"] = 3] = "Boolean";
  23977. /**
  23978. * The type of the `undefined` literal.
  23979. */
  23980. BuiltinType[BuiltinType["Undefined"] = 4] = "Undefined";
  23981. /**
  23982. * the type of the `null` literal.
  23983. */
  23984. BuiltinType[BuiltinType["Null"] = 5] = "Null";
  23985. /**
  23986. * the type is an unbound type parameter.
  23987. */
  23988. BuiltinType[BuiltinType["Unbound"] = 6] = "Unbound";
  23989. /**
  23990. * Not a built-in type.
  23991. */
  23992. BuiltinType[BuiltinType["Other"] = 7] = "Other";
  23993. })(BuiltinType$1 || (BuiltinType$1 = {}));
  23994. /**
  23995. * @license
  23996. * Copyright Google Inc. All Rights Reserved.
  23997. *
  23998. * Use of this source code is governed by an MIT-style license that can be
  23999. * found in the LICENSE file at https://angular.io/license
  24000. */
  24001. var DiagnosticKind;
  24002. (function (DiagnosticKind) {
  24003. DiagnosticKind[DiagnosticKind["Error"] = 0] = "Error";
  24004. DiagnosticKind[DiagnosticKind["Warning"] = 1] = "Warning";
  24005. })(DiagnosticKind || (DiagnosticKind = {}));
  24006. var TypeDiagnostic = /** @class */ (function () {
  24007. function TypeDiagnostic(kind, message, ast) {
  24008. this.kind = kind;
  24009. this.message = message;
  24010. this.ast = ast;
  24011. }
  24012. return TypeDiagnostic;
  24013. }());
  24014. // AstType calculatetype of the ast given AST element.
  24015. var AstType = /** @class */ (function () {
  24016. function AstType(scope, query, context) {
  24017. this.scope = scope;
  24018. this.query = query;
  24019. this.context = context;
  24020. }
  24021. AstType.prototype.getType = function (ast) { return ast.visit(this); };
  24022. AstType.prototype.getDiagnostics = function (ast) {
  24023. this.diagnostics = [];
  24024. var type = ast.visit(this);
  24025. if (this.context.event && type.callable) {
  24026. this.reportWarning('Unexpected callable expression. Expected a method call', ast);
  24027. }
  24028. return this.diagnostics;
  24029. };
  24030. AstType.prototype.visitBinary = function (ast) {
  24031. var _this_1 = this;
  24032. // Treat undefined and null as other.
  24033. function normalize(kind, other) {
  24034. switch (kind) {
  24035. case BuiltinType$1.Undefined:
  24036. case BuiltinType$1.Null:
  24037. return normalize(other, BuiltinType$1.Other);
  24038. }
  24039. return kind;
  24040. }
  24041. var getType = function (ast, operation) {
  24042. var type = _this_1.getType(ast);
  24043. if (type.nullable) {
  24044. switch (operation) {
  24045. case '&&':
  24046. case '||':
  24047. case '==':
  24048. case '!=':
  24049. case '===':
  24050. case '!==':
  24051. // Nullable allowed.
  24052. break;
  24053. default:
  24054. _this_1.reportError("The expression might be null", ast);
  24055. break;
  24056. }
  24057. return _this_1.query.getNonNullableType(type);
  24058. }
  24059. return type;
  24060. };
  24061. var leftType = getType(ast.left, ast.operation);
  24062. var rightType = getType(ast.right, ast.operation);
  24063. var leftRawKind = this.query.getTypeKind(leftType);
  24064. var rightRawKind = this.query.getTypeKind(rightType);
  24065. var leftKind = normalize(leftRawKind, rightRawKind);
  24066. var rightKind = normalize(rightRawKind, leftRawKind);
  24067. // The following swtich implements operator typing similar to the
  24068. // type production tables in the TypeScript specification.
  24069. // https://github.com/Microsoft/TypeScript/blob/v1.8.10/doc/spec.md#4.19
  24070. var operKind = leftKind << 8 | rightKind;
  24071. switch (ast.operation) {
  24072. case '*':
  24073. case '/':
  24074. case '%':
  24075. case '-':
  24076. case '<<':
  24077. case '>>':
  24078. case '>>>':
  24079. case '&':
  24080. case '^':
  24081. case '|':
  24082. switch (operKind) {
  24083. case BuiltinType$1.Any << 8 | BuiltinType$1.Any:
  24084. case BuiltinType$1.Number << 8 | BuiltinType$1.Any:
  24085. case BuiltinType$1.Any << 8 | BuiltinType$1.Number:
  24086. case BuiltinType$1.Number << 8 | BuiltinType$1.Number:
  24087. return this.query.getBuiltinType(BuiltinType$1.Number);
  24088. default:
  24089. var errorAst = ast.left;
  24090. switch (leftKind) {
  24091. case BuiltinType$1.Any:
  24092. case BuiltinType$1.Number:
  24093. errorAst = ast.right;
  24094. break;
  24095. }
  24096. return this.reportError('Expected a numeric type', errorAst);
  24097. }
  24098. case '+':
  24099. switch (operKind) {
  24100. case BuiltinType$1.Any << 8 | BuiltinType$1.Any:
  24101. case BuiltinType$1.Any << 8 | BuiltinType$1.Boolean:
  24102. case BuiltinType$1.Any << 8 | BuiltinType$1.Number:
  24103. case BuiltinType$1.Any << 8 | BuiltinType$1.Other:
  24104. case BuiltinType$1.Boolean << 8 | BuiltinType$1.Any:
  24105. case BuiltinType$1.Number << 8 | BuiltinType$1.Any:
  24106. case BuiltinType$1.Other << 8 | BuiltinType$1.Any:
  24107. return this.anyType;
  24108. case BuiltinType$1.Any << 8 | BuiltinType$1.String:
  24109. case BuiltinType$1.Boolean << 8 | BuiltinType$1.String:
  24110. case BuiltinType$1.Number << 8 | BuiltinType$1.String:
  24111. case BuiltinType$1.String << 8 | BuiltinType$1.Any:
  24112. case BuiltinType$1.String << 8 | BuiltinType$1.Boolean:
  24113. case BuiltinType$1.String << 8 | BuiltinType$1.Number:
  24114. case BuiltinType$1.String << 8 | BuiltinType$1.String:
  24115. case BuiltinType$1.String << 8 | BuiltinType$1.Other:
  24116. case BuiltinType$1.Other << 8 | BuiltinType$1.String:
  24117. return this.query.getBuiltinType(BuiltinType$1.String);
  24118. case BuiltinType$1.Number << 8 | BuiltinType$1.Number:
  24119. return this.query.getBuiltinType(BuiltinType$1.Number);
  24120. case BuiltinType$1.Boolean << 8 | BuiltinType$1.Number:
  24121. case BuiltinType$1.Other << 8 | BuiltinType$1.Number:
  24122. return this.reportError('Expected a number type', ast.left);
  24123. case BuiltinType$1.Number << 8 | BuiltinType$1.Boolean:
  24124. case BuiltinType$1.Number << 8 | BuiltinType$1.Other:
  24125. return this.reportError('Expected a number type', ast.right);
  24126. default:
  24127. return this.reportError('Expected operands to be a string or number type', ast);
  24128. }
  24129. case '>':
  24130. case '<':
  24131. case '<=':
  24132. case '>=':
  24133. case '==':
  24134. case '!=':
  24135. case '===':
  24136. case '!==':
  24137. switch (operKind) {
  24138. case BuiltinType$1.Any << 8 | BuiltinType$1.Any:
  24139. case BuiltinType$1.Any << 8 | BuiltinType$1.Boolean:
  24140. case BuiltinType$1.Any << 8 | BuiltinType$1.Number:
  24141. case BuiltinType$1.Any << 8 | BuiltinType$1.String:
  24142. case BuiltinType$1.Any << 8 | BuiltinType$1.Other:
  24143. case BuiltinType$1.Boolean << 8 | BuiltinType$1.Any:
  24144. case BuiltinType$1.Boolean << 8 | BuiltinType$1.Boolean:
  24145. case BuiltinType$1.Number << 8 | BuiltinType$1.Any:
  24146. case BuiltinType$1.Number << 8 | BuiltinType$1.Number:
  24147. case BuiltinType$1.String << 8 | BuiltinType$1.Any:
  24148. case BuiltinType$1.String << 8 | BuiltinType$1.String:
  24149. case BuiltinType$1.Other << 8 | BuiltinType$1.Any:
  24150. case BuiltinType$1.Other << 8 | BuiltinType$1.Other:
  24151. return this.query.getBuiltinType(BuiltinType$1.Boolean);
  24152. default:
  24153. return this.reportError('Expected the operants to be of similar type or any', ast);
  24154. }
  24155. case '&&':
  24156. return rightType;
  24157. case '||':
  24158. return this.query.getTypeUnion(leftType, rightType);
  24159. }
  24160. return this.reportError("Unrecognized operator " + ast.operation, ast);
  24161. };
  24162. AstType.prototype.visitChain = function (ast) {
  24163. if (this.diagnostics) {
  24164. // If we are producing diagnostics, visit the children
  24165. visitAstChildren(ast, this);
  24166. }
  24167. // The type of a chain is always undefined.
  24168. return this.query.getBuiltinType(BuiltinType$1.Undefined);
  24169. };
  24170. AstType.prototype.visitConditional = function (ast) {
  24171. // The type of a conditional is the union of the true and false conditions.
  24172. if (this.diagnostics) {
  24173. visitAstChildren(ast, this);
  24174. }
  24175. return this.query.getTypeUnion(this.getType(ast.trueExp), this.getType(ast.falseExp));
  24176. };
  24177. AstType.prototype.visitFunctionCall = function (ast) {
  24178. var _this_1 = this;
  24179. // The type of a function call is the return type of the selected signature.
  24180. // The signature is selected based on the types of the arguments. Angular doesn't
  24181. // support contextual typing of arguments so this is simpler than TypeScript's
  24182. // version.
  24183. var args = ast.args.map(function (arg) { return _this_1.getType(arg); });
  24184. var target = this.getType(ast.target);
  24185. if (!target || !target.callable)
  24186. return this.reportError('Call target is not callable', ast);
  24187. var signature = target.selectSignature(args);
  24188. if (signature)
  24189. return signature.result;
  24190. // TODO: Consider a better error message here.
  24191. return this.reportError('Unable no compatible signature found for call', ast);
  24192. };
  24193. AstType.prototype.visitImplicitReceiver = function (ast) {
  24194. var _this = this;
  24195. // Return a pseudo-symbol for the implicit receiver.
  24196. // The members of the implicit receiver are what is defined by the
  24197. // scope passed into this class.
  24198. return {
  24199. name: '$implict',
  24200. kind: 'component',
  24201. language: 'ng-template',
  24202. type: undefined,
  24203. container: undefined,
  24204. callable: false,
  24205. nullable: false,
  24206. public: true,
  24207. definition: undefined,
  24208. members: function () { return _this.scope; },
  24209. signatures: function () { return []; },
  24210. selectSignature: function (types) { return undefined; },
  24211. indexed: function (argument) { return undefined; }
  24212. };
  24213. };
  24214. AstType.prototype.visitInterpolation = function (ast) {
  24215. // If we are producing diagnostics, visit the children.
  24216. if (this.diagnostics) {
  24217. visitAstChildren(ast, this);
  24218. }
  24219. return this.undefinedType;
  24220. };
  24221. AstType.prototype.visitKeyedRead = function (ast) {
  24222. var targetType = this.getType(ast.obj);
  24223. var keyType = this.getType(ast.key);
  24224. var result = targetType.indexed(keyType);
  24225. return result || this.anyType;
  24226. };
  24227. AstType.prototype.visitKeyedWrite = function (ast) {
  24228. // The write of a type is the type of the value being written.
  24229. return this.getType(ast.value);
  24230. };
  24231. AstType.prototype.visitLiteralArray = function (ast) {
  24232. var _this_1 = this;
  24233. var _a;
  24234. // A type literal is an array type of the union of the elements
  24235. return this.query.getArrayType((_a = this.query).getTypeUnion.apply(_a, __spread(ast.expressions.map(function (element) { return _this_1.getType(element); }))));
  24236. };
  24237. AstType.prototype.visitLiteralMap = function (ast) {
  24238. // If we are producing diagnostics, visit the children
  24239. if (this.diagnostics) {
  24240. visitAstChildren(ast, this);
  24241. }
  24242. // TODO: Return a composite type.
  24243. return this.anyType;
  24244. };
  24245. AstType.prototype.visitLiteralPrimitive = function (ast) {
  24246. // The type of a literal primitive depends on the value of the literal.
  24247. switch (ast.value) {
  24248. case true:
  24249. case false:
  24250. return this.query.getBuiltinType(BuiltinType$1.Boolean);
  24251. case null:
  24252. return this.query.getBuiltinType(BuiltinType$1.Null);
  24253. case undefined:
  24254. return this.query.getBuiltinType(BuiltinType$1.Undefined);
  24255. default:
  24256. switch (typeof ast.value) {
  24257. case 'string':
  24258. return this.query.getBuiltinType(BuiltinType$1.String);
  24259. case 'number':
  24260. return this.query.getBuiltinType(BuiltinType$1.Number);
  24261. default:
  24262. return this.reportError('Unrecognized primitive', ast);
  24263. }
  24264. }
  24265. };
  24266. AstType.prototype.visitMethodCall = function (ast) {
  24267. return this.resolveMethodCall(this.getType(ast.receiver), ast);
  24268. };
  24269. AstType.prototype.visitPipe = function (ast) {
  24270. var _this_1 = this;
  24271. // The type of a pipe node is the return type of the pipe's transform method. The table returned
  24272. // by getPipes() is expected to contain symbols with the corresponding transform method type.
  24273. var pipe = this.query.getPipes().get(ast.name);
  24274. if (!pipe)
  24275. return this.reportError("No pipe by the name " + ast.name + " found", ast);
  24276. var expType = this.getType(ast.exp);
  24277. var signature = pipe.selectSignature([expType].concat(ast.args.map(function (arg) { return _this_1.getType(arg); })));
  24278. if (!signature)
  24279. return this.reportError('Unable to resolve signature for pipe invocation', ast);
  24280. return signature.result;
  24281. };
  24282. AstType.prototype.visitPrefixNot = function (ast) {
  24283. // The type of a prefix ! is always boolean.
  24284. return this.query.getBuiltinType(BuiltinType$1.Boolean);
  24285. };
  24286. AstType.prototype.visitNonNullAssert = function (ast) {
  24287. var expressionType = this.getType(ast.expression);
  24288. return this.query.getNonNullableType(expressionType);
  24289. };
  24290. AstType.prototype.visitPropertyRead = function (ast) {
  24291. return this.resolvePropertyRead(this.getType(ast.receiver), ast);
  24292. };
  24293. AstType.prototype.visitPropertyWrite = function (ast) {
  24294. // The type of a write is the type of the value being written.
  24295. return this.getType(ast.value);
  24296. };
  24297. AstType.prototype.visitQuote = function (ast) {
  24298. // The type of a quoted expression is any.
  24299. return this.query.getBuiltinType(BuiltinType$1.Any);
  24300. };
  24301. AstType.prototype.visitSafeMethodCall = function (ast) {
  24302. return this.resolveMethodCall(this.query.getNonNullableType(this.getType(ast.receiver)), ast);
  24303. };
  24304. AstType.prototype.visitSafePropertyRead = function (ast) {
  24305. return this.resolvePropertyRead(this.query.getNonNullableType(this.getType(ast.receiver)), ast);
  24306. };
  24307. Object.defineProperty(AstType.prototype, "anyType", {
  24308. get: function () {
  24309. var result = this._anyType;
  24310. if (!result) {
  24311. result = this._anyType = this.query.getBuiltinType(BuiltinType$1.Any);
  24312. }
  24313. return result;
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. Object.defineProperty(AstType.prototype, "undefinedType", {
  24319. get: function () {
  24320. var result = this._undefinedType;
  24321. if (!result) {
  24322. result = this._undefinedType = this.query.getBuiltinType(BuiltinType$1.Undefined);
  24323. }
  24324. return result;
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. AstType.prototype.resolveMethodCall = function (receiverType, ast) {
  24330. var _this_1 = this;
  24331. if (this.isAny(receiverType)) {
  24332. return this.anyType;
  24333. }
  24334. // The type of a method is the selected methods result type.
  24335. var method = receiverType.members().get(ast.name);
  24336. if (!method)
  24337. return this.reportError("Unknown method '" + ast.name + "'", ast);
  24338. if (!method.type)
  24339. return this.reportError("Could not find a type for '" + ast.name + "'", ast);
  24340. if (!method.type.callable)
  24341. return this.reportError("Member '" + ast.name + "' is not callable", ast);
  24342. var signature = method.type.selectSignature(ast.args.map(function (arg) { return _this_1.getType(arg); }));
  24343. if (!signature)
  24344. return this.reportError("Unable to resolve signature for call of method " + ast.name, ast);
  24345. return signature.result;
  24346. };
  24347. AstType.prototype.resolvePropertyRead = function (receiverType, ast) {
  24348. if (this.isAny(receiverType)) {
  24349. return this.anyType;
  24350. }
  24351. // The type of a property read is the seelcted member's type.
  24352. var member = receiverType.members().get(ast.name);
  24353. if (!member) {
  24354. var receiverInfo = receiverType.name;
  24355. if (receiverInfo == '$implict') {
  24356. receiverInfo =
  24357. 'The component declaration, template variable declarations, and element references do';
  24358. }
  24359. else if (receiverType.nullable) {
  24360. return this.reportError("The expression might be null", ast.receiver);
  24361. }
  24362. else {
  24363. receiverInfo = "'" + receiverInfo + "' does";
  24364. }
  24365. return this.reportError("Identifier '" + ast.name + "' is not defined. " + receiverInfo + " not contain such a member", ast);
  24366. }
  24367. if (!member.public) {
  24368. var receiverInfo = receiverType.name;
  24369. if (receiverInfo == '$implict') {
  24370. receiverInfo = 'the component';
  24371. }
  24372. else {
  24373. receiverInfo = "'" + receiverInfo + "'";
  24374. }
  24375. this.reportWarning("Identifier '" + ast.name + "' refers to a private member of " + receiverInfo, ast);
  24376. }
  24377. return member.type;
  24378. };
  24379. AstType.prototype.reportError = function (message, ast) {
  24380. if (this.diagnostics) {
  24381. this.diagnostics.push(new TypeDiagnostic(DiagnosticKind.Error, message, ast));
  24382. }
  24383. return this.anyType;
  24384. };
  24385. AstType.prototype.reportWarning = function (message, ast) {
  24386. if (this.diagnostics) {
  24387. this.diagnostics.push(new TypeDiagnostic(DiagnosticKind.Warning, message, ast));
  24388. }
  24389. return this.anyType;
  24390. };
  24391. AstType.prototype.isAny = function (symbol) {
  24392. return !symbol || this.query.getTypeKind(symbol) == BuiltinType$1.Any ||
  24393. (!!symbol.type && this.isAny(symbol.type));
  24394. };
  24395. return AstType;
  24396. }());
  24397. /**
  24398. * @license
  24399. * Copyright Google Inc. All Rights Reserved.
  24400. *
  24401. * Use of this source code is governed by an MIT-style license that can be
  24402. * found in the LICENSE file at https://angular.io/license
  24403. */
  24404. function getTemplateExpressionDiagnostics(info) {
  24405. var visitor = new ExpressionDiagnosticsVisitor(info, function (path, includeEvent) {
  24406. return getExpressionScope(info, path, includeEvent);
  24407. });
  24408. templateVisitAll(visitor, info.templateAst);
  24409. return visitor.diagnostics;
  24410. }
  24411. function getExpressionDiagnostics(scope, ast, query, context) {
  24412. if (context === void 0) { context = {}; }
  24413. var analyzer = new AstType(scope, query, context);
  24414. analyzer.getDiagnostics(ast);
  24415. return analyzer.diagnostics;
  24416. }
  24417. function getReferences(info) {
  24418. var result = [];
  24419. function processReferences(references) {
  24420. var e_1, _a;
  24421. var _loop_1 = function (reference) {
  24422. var type = undefined;
  24423. if (reference.value) {
  24424. type = info.query.getTypeSymbol(tokenReference(reference.value));
  24425. }
  24426. result.push({
  24427. name: reference.name,
  24428. kind: 'reference',
  24429. type: type || info.query.getBuiltinType(BuiltinType$1.Any),
  24430. get definition() { return getDefinitionOf(info, reference); }
  24431. });
  24432. };
  24433. try {
  24434. for (var references_1 = __values(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
  24435. var reference = references_1_1.value;
  24436. _loop_1(reference);
  24437. }
  24438. }
  24439. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  24440. finally {
  24441. try {
  24442. if (references_1_1 && !references_1_1.done && (_a = references_1.return)) _a.call(references_1);
  24443. }
  24444. finally { if (e_1) throw e_1.error; }
  24445. }
  24446. }
  24447. var visitor = new /** @class */ (function (_super) {
  24448. __extends(class_1, _super);
  24449. function class_1() {
  24450. return _super !== null && _super.apply(this, arguments) || this;
  24451. }
  24452. class_1.prototype.visitEmbeddedTemplate = function (ast, context) {
  24453. _super.prototype.visitEmbeddedTemplate.call(this, ast, context);
  24454. processReferences(ast.references);
  24455. };
  24456. class_1.prototype.visitElement = function (ast, context) {
  24457. _super.prototype.visitElement.call(this, ast, context);
  24458. processReferences(ast.references);
  24459. };
  24460. return class_1;
  24461. }(RecursiveTemplateAstVisitor));
  24462. templateVisitAll(visitor, info.templateAst);
  24463. return result;
  24464. }
  24465. function getDefinitionOf(info, ast) {
  24466. if (info.fileName) {
  24467. var templateOffset = info.offset;
  24468. return [{
  24469. fileName: info.fileName,
  24470. span: {
  24471. start: ast.sourceSpan.start.offset + templateOffset,
  24472. end: ast.sourceSpan.end.offset + templateOffset
  24473. }
  24474. }];
  24475. }
  24476. }
  24477. function getVarDeclarations(info, path) {
  24478. var e_2, _a;
  24479. var result = [];
  24480. var current = path.tail;
  24481. while (current) {
  24482. if (current instanceof EmbeddedTemplateAst) {
  24483. var _loop_2 = function (variable) {
  24484. var name = variable.name;
  24485. // Find the first directive with a context.
  24486. var context = current.directives.map(function (d) { return info.query.getTemplateContext(d.directive.type.reference); })
  24487. .find(function (c) { return !!c; });
  24488. // Determine the type of the context field referenced by variable.value.
  24489. var type = undefined;
  24490. if (context) {
  24491. var value = context.get(variable.value);
  24492. if (value) {
  24493. type = value.type;
  24494. var kind = info.query.getTypeKind(type);
  24495. if (kind === BuiltinType$1.Any || kind == BuiltinType$1.Unbound) {
  24496. // The any type is not very useful here. For special cases, such as ngFor, we can do
  24497. // better.
  24498. type = refinedVariableType(type, info, current);
  24499. }
  24500. }
  24501. }
  24502. if (!type) {
  24503. type = info.query.getBuiltinType(BuiltinType$1.Any);
  24504. }
  24505. result.push({
  24506. name: name,
  24507. kind: 'variable', type: type, get definition() { return getDefinitionOf(info, variable); }
  24508. });
  24509. };
  24510. try {
  24511. for (var _b = __values(current.variables), _c = _b.next(); !_c.done; _c = _b.next()) {
  24512. var variable = _c.value;
  24513. _loop_2(variable);
  24514. }
  24515. }
  24516. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  24517. finally {
  24518. try {
  24519. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  24520. }
  24521. finally { if (e_2) throw e_2.error; }
  24522. }
  24523. }
  24524. current = path.parentOf(current);
  24525. }
  24526. return result;
  24527. }
  24528. function refinedVariableType(type, info, templateElement) {
  24529. // Special case the ngFor directive
  24530. var ngForDirective = templateElement.directives.find(function (d) {
  24531. var name = identifierName(d.directive.type);
  24532. return name == 'NgFor' || name == 'NgForOf';
  24533. });
  24534. if (ngForDirective) {
  24535. var ngForOfBinding = ngForDirective.inputs.find(function (i) { return i.directiveName == 'ngForOf'; });
  24536. if (ngForOfBinding) {
  24537. var bindingType = new AstType(info.members, info.query, {}).getType(ngForOfBinding.value);
  24538. if (bindingType) {
  24539. var result = info.query.getElementType(bindingType);
  24540. if (result) {
  24541. return result;
  24542. }
  24543. }
  24544. }
  24545. }
  24546. // We can't do better, return any
  24547. return info.query.getBuiltinType(BuiltinType$1.Any);
  24548. }
  24549. function getEventDeclaration(info, includeEvent) {
  24550. var result = [];
  24551. if (includeEvent) {
  24552. // TODO: Determine the type of the event parameter based on the Observable<T> or EventEmitter<T>
  24553. // of the event.
  24554. result = [{ name: '$event', kind: 'variable', type: info.query.getBuiltinType(BuiltinType$1.Any) }];
  24555. }
  24556. return result;
  24557. }
  24558. function getExpressionScope(info, path, includeEvent) {
  24559. var result = info.members;
  24560. var references = getReferences(info);
  24561. var variables = getVarDeclarations(info, path);
  24562. var events = getEventDeclaration(info, includeEvent);
  24563. if (references.length || variables.length || events.length) {
  24564. var referenceTable = info.query.createSymbolTable(references);
  24565. var variableTable = info.query.createSymbolTable(variables);
  24566. var eventsTable = info.query.createSymbolTable(events);
  24567. result = info.query.mergeSymbolTable([result, referenceTable, variableTable, eventsTable]);
  24568. }
  24569. return result;
  24570. }
  24571. var ExpressionDiagnosticsVisitor = /** @class */ (function (_super) {
  24572. __extends(ExpressionDiagnosticsVisitor, _super);
  24573. function ExpressionDiagnosticsVisitor(info, getExpressionScope) {
  24574. var _this = _super.call(this) || this;
  24575. _this.info = info;
  24576. _this.getExpressionScope = getExpressionScope;
  24577. _this.diagnostics = [];
  24578. _this.path = new AstPath([]);
  24579. return _this;
  24580. }
  24581. ExpressionDiagnosticsVisitor.prototype.visitDirective = function (ast, context) {
  24582. // Override the default child visitor to ignore the host properties of a directive.
  24583. if (ast.inputs && ast.inputs.length) {
  24584. templateVisitAll(this, ast.inputs, context);
  24585. }
  24586. };
  24587. ExpressionDiagnosticsVisitor.prototype.visitBoundText = function (ast) {
  24588. this.push(ast);
  24589. this.diagnoseExpression(ast.value, ast.sourceSpan.start.offset, false);
  24590. this.pop();
  24591. };
  24592. ExpressionDiagnosticsVisitor.prototype.visitDirectiveProperty = function (ast) {
  24593. this.push(ast);
  24594. this.diagnoseExpression(ast.value, this.attributeValueLocation(ast), false);
  24595. this.pop();
  24596. };
  24597. ExpressionDiagnosticsVisitor.prototype.visitElementProperty = function (ast) {
  24598. this.push(ast);
  24599. this.diagnoseExpression(ast.value, this.attributeValueLocation(ast), false);
  24600. this.pop();
  24601. };
  24602. ExpressionDiagnosticsVisitor.prototype.visitEvent = function (ast) {
  24603. this.push(ast);
  24604. this.diagnoseExpression(ast.handler, this.attributeValueLocation(ast), true);
  24605. this.pop();
  24606. };
  24607. ExpressionDiagnosticsVisitor.prototype.visitVariable = function (ast) {
  24608. var directive = this.directiveSummary;
  24609. if (directive && ast.value) {
  24610. var context = this.info.query.getTemplateContext(directive.type.reference);
  24611. if (context && !context.has(ast.value)) {
  24612. if (ast.value === '$implicit') {
  24613. this.reportError('The template context does not have an implicit value', spanOf$1(ast.sourceSpan));
  24614. }
  24615. else {
  24616. this.reportError("The template context does not defined a member called '" + ast.value + "'", spanOf$1(ast.sourceSpan));
  24617. }
  24618. }
  24619. }
  24620. };
  24621. ExpressionDiagnosticsVisitor.prototype.visitElement = function (ast, context) {
  24622. this.push(ast);
  24623. _super.prototype.visitElement.call(this, ast, context);
  24624. this.pop();
  24625. };
  24626. ExpressionDiagnosticsVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
  24627. var previousDirectiveSummary = this.directiveSummary;
  24628. this.push(ast);
  24629. // Find directive that references this template
  24630. this.directiveSummary =
  24631. ast.directives.map(function (d) { return d.directive; }).find(function (d) { return hasTemplateReference(d.type); });
  24632. // Process children
  24633. _super.prototype.visitEmbeddedTemplate.call(this, ast, context);
  24634. this.pop();
  24635. this.directiveSummary = previousDirectiveSummary;
  24636. };
  24637. ExpressionDiagnosticsVisitor.prototype.attributeValueLocation = function (ast) {
  24638. var path = findNode(this.info.htmlAst, ast.sourceSpan.start.offset);
  24639. var last = path.tail;
  24640. if (last instanceof Attribute && last.valueSpan) {
  24641. return last.valueSpan.start.offset;
  24642. }
  24643. return ast.sourceSpan.start.offset;
  24644. };
  24645. ExpressionDiagnosticsVisitor.prototype.diagnoseExpression = function (ast, offset, includeEvent) {
  24646. var _this = this;
  24647. var _a;
  24648. var scope = this.getExpressionScope(this.path, includeEvent);
  24649. (_a = this.diagnostics).push.apply(_a, __spread(getExpressionDiagnostics(scope, ast, this.info.query, {
  24650. event: includeEvent
  24651. }).map(function (d) { return ({
  24652. span: offsetSpan(d.ast.span, offset + _this.info.offset),
  24653. kind: d.kind,
  24654. message: d.message
  24655. }); })));
  24656. };
  24657. ExpressionDiagnosticsVisitor.prototype.push = function (ast) { this.path.push(ast); };
  24658. ExpressionDiagnosticsVisitor.prototype.pop = function () { this.path.pop(); };
  24659. ExpressionDiagnosticsVisitor.prototype.reportError = function (message, span) {
  24660. if (span) {
  24661. this.diagnostics.push({ span: offsetSpan(span, this.info.offset), kind: DiagnosticKind.Error, message: message });
  24662. }
  24663. };
  24664. ExpressionDiagnosticsVisitor.prototype.reportWarning = function (message, span) {
  24665. this.diagnostics.push({ span: offsetSpan(span, this.info.offset), kind: DiagnosticKind.Warning, message: message });
  24666. };
  24667. return ExpressionDiagnosticsVisitor;
  24668. }(RecursiveTemplateAstVisitor));
  24669. function hasTemplateReference(type) {
  24670. var e_3, _a;
  24671. if (type.diDeps) {
  24672. try {
  24673. for (var _b = __values(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {
  24674. var diDep = _c.value;
  24675. if (diDep.token && diDep.token.identifier &&
  24676. identifierName(diDep.token.identifier) == 'TemplateRef')
  24677. return true;
  24678. }
  24679. }
  24680. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  24681. finally {
  24682. try {
  24683. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  24684. }
  24685. finally { if (e_3) throw e_3.error; }
  24686. }
  24687. }
  24688. return false;
  24689. }
  24690. function offsetSpan(span, amount) {
  24691. return { start: span.start + amount, end: span.end + amount };
  24692. }
  24693. function spanOf$1(sourceSpan) {
  24694. return { start: sourceSpan.start.offset, end: sourceSpan.end.offset };
  24695. }
  24696. /**
  24697. * @license
  24698. * Copyright Google Inc. All Rights Reserved.
  24699. *
  24700. * Use of this source code is governed by an MIT-style license that can be
  24701. * found in the LICENSE file at https://angular.io/license
  24702. */
  24703. /**
  24704. * Converts a `string` version into an array of numbers
  24705. * @example
  24706. * toNumbers('2.0.1'); // returns [2, 0, 1]
  24707. */
  24708. function toNumbers(value) {
  24709. return value.split('.').map(Number);
  24710. }
  24711. /**
  24712. * Compares two arrays of positive numbers with lexicographical order in mind.
  24713. *
  24714. * However - unlike lexicographical order - for arrays of different length we consider:
  24715. * [1, 2, 3] = [1, 2, 3, 0] instead of [1, 2, 3] < [1, 2, 3, 0]
  24716. *
  24717. * @param a The 'left hand' array in the comparison test
  24718. * @param b The 'right hand' in the comparison test
  24719. * @returns {-1|0|1} The comparison result: 1 if a is greater, -1 if b is greater, 0 is the two
  24720. * arrays are equals
  24721. */
  24722. function compareNumbers(a, b) {
  24723. var max = Math.max(a.length, b.length);
  24724. var min = Math.min(a.length, b.length);
  24725. for (var i = 0; i < min; i++) {
  24726. if (a[i] > b[i])
  24727. return 1;
  24728. if (a[i] < b[i])
  24729. return -1;
  24730. }
  24731. if (min !== max) {
  24732. var longestArray = a.length === max ? a : b;
  24733. // The result to return in case the to arrays are considered different (1 if a is greater,
  24734. // -1 if b is greater)
  24735. var comparisonResult = a.length === max ? 1 : -1;
  24736. // Check that at least one of the remaining elements is greater than 0 to consider that the two
  24737. // arrays are different (e.g. [1, 0] and [1] are considered the same but not [1, 0, 1] and [1])
  24738. for (var i = min; i < max; i++) {
  24739. if (longestArray[i] > 0) {
  24740. return comparisonResult;
  24741. }
  24742. }
  24743. }
  24744. return 0;
  24745. }
  24746. /**
  24747. * Checks if a TypeScript version is:
  24748. * - greater or equal than the provided `low` version,
  24749. * - lower or equal than an optional `high` version.
  24750. *
  24751. * @param version The TypeScript version
  24752. * @param low The minimum version
  24753. * @param high The maximum version
  24754. */
  24755. function isVersionBetween(version, low, high) {
  24756. var tsNumbers = toNumbers(version);
  24757. if (high !== undefined) {
  24758. return compareNumbers(toNumbers(low), tsNumbers) <= 0 &&
  24759. compareNumbers(toNumbers(high), tsNumbers) >= 0;
  24760. }
  24761. return compareNumbers(toNumbers(low), tsNumbers) <= 0;
  24762. }
  24763. /**
  24764. * @license
  24765. * Copyright Google Inc. All Rights Reserved.
  24766. *
  24767. * Use of this source code is governed by an MIT-style license that can be
  24768. * found in the LICENSE file at https://angular.io/license
  24769. */
  24770. // In TypeScript 2.1 these flags moved
  24771. // These helpers work for both 2.0 and 2.1.
  24772. var isPrivate = ts.ModifierFlags ?
  24773. (function (node) {
  24774. return !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Private);
  24775. }) :
  24776. (function (node) { return !!(node.flags & ts.NodeFlags.Private); });
  24777. var isReferenceType = ts.ObjectFlags ?
  24778. (function (type) {
  24779. return !!(type.flags & ts.TypeFlags.Object &&
  24780. type.objectFlags & ts.ObjectFlags.Reference);
  24781. }) :
  24782. (function (type) { return !!(type.flags & ts.TypeFlags.Reference); });
  24783. function getSymbolQuery(program, checker, source, fetchPipes) {
  24784. return new TypeScriptSymbolQuery(program, checker, source, fetchPipes);
  24785. }
  24786. function getClassMembersFromDeclaration(program, checker, source, declaration) {
  24787. var type = checker.getTypeAtLocation(declaration);
  24788. return new TypeWrapper(type, { node: source, program: program, checker: checker }).members();
  24789. }
  24790. function getPipesTable(source, program, checker, pipes) {
  24791. return new PipesTable(pipes, { program: program, checker: checker, node: source });
  24792. }
  24793. var TypeScriptSymbolQuery = /** @class */ (function () {
  24794. function TypeScriptSymbolQuery(program, checker, source, fetchPipes) {
  24795. this.program = program;
  24796. this.checker = checker;
  24797. this.source = source;
  24798. this.fetchPipes = fetchPipes;
  24799. this.typeCache = new Map();
  24800. }
  24801. TypeScriptSymbolQuery.prototype.getTypeKind = function (symbol) { return typeKindOf(this.getTsTypeOf(symbol)); };
  24802. TypeScriptSymbolQuery.prototype.getBuiltinType = function (kind) {
  24803. var result = this.typeCache.get(kind);
  24804. if (!result) {
  24805. var type = getBuiltinTypeFromTs(kind, { checker: this.checker, node: this.source, program: this.program });
  24806. result =
  24807. new TypeWrapper(type, { program: this.program, checker: this.checker, node: this.source });
  24808. this.typeCache.set(kind, result);
  24809. }
  24810. return result;
  24811. };
  24812. TypeScriptSymbolQuery.prototype.getTypeUnion = function () {
  24813. var types = [];
  24814. for (var _i = 0; _i < arguments.length; _i++) {
  24815. types[_i] = arguments[_i];
  24816. }
  24817. // No API exists so return any if the types are not all the same type.
  24818. var result = undefined;
  24819. if (types.length) {
  24820. result = types[0];
  24821. for (var i = 1; i < types.length; i++) {
  24822. if (types[i] != result) {
  24823. result = undefined;
  24824. break;
  24825. }
  24826. }
  24827. }
  24828. return result || this.getBuiltinType(BuiltinType$1.Any);
  24829. };
  24830. TypeScriptSymbolQuery.prototype.getArrayType = function (type) { return this.getBuiltinType(BuiltinType$1.Any); };
  24831. TypeScriptSymbolQuery.prototype.getElementType = function (type) {
  24832. if (type instanceof TypeWrapper) {
  24833. var elementType = getTypeParameterOf(type.tsType, 'Array');
  24834. if (elementType) {
  24835. return new TypeWrapper(elementType, type.context);
  24836. }
  24837. }
  24838. };
  24839. TypeScriptSymbolQuery.prototype.getNonNullableType = function (symbol) {
  24840. if (symbol instanceof TypeWrapper && (typeof this.checker.getNonNullableType == 'function')) {
  24841. var tsType = symbol.tsType;
  24842. var nonNullableType = this.checker.getNonNullableType(tsType);
  24843. if (nonNullableType != tsType) {
  24844. return new TypeWrapper(nonNullableType, symbol.context);
  24845. }
  24846. else if (nonNullableType == tsType) {
  24847. return symbol;
  24848. }
  24849. }
  24850. return this.getBuiltinType(BuiltinType$1.Any);
  24851. };
  24852. TypeScriptSymbolQuery.prototype.getPipes = function () {
  24853. var result = this.pipesCache;
  24854. if (!result) {
  24855. result = this.pipesCache = this.fetchPipes();
  24856. }
  24857. return result;
  24858. };
  24859. TypeScriptSymbolQuery.prototype.getTemplateContext = function (type) {
  24860. var context = { node: this.source, program: this.program, checker: this.checker };
  24861. var typeSymbol = findClassSymbolInContext(type, context);
  24862. if (typeSymbol) {
  24863. var contextType = this.getTemplateRefContextType(typeSymbol);
  24864. if (contextType)
  24865. return new SymbolWrapper(contextType, context).members();
  24866. }
  24867. };
  24868. TypeScriptSymbolQuery.prototype.getTypeSymbol = function (type) {
  24869. var context = { node: this.source, program: this.program, checker: this.checker };
  24870. var typeSymbol = findClassSymbolInContext(type, context);
  24871. return typeSymbol && new SymbolWrapper(typeSymbol, context);
  24872. };
  24873. TypeScriptSymbolQuery.prototype.createSymbolTable = function (symbols) {
  24874. var result = new MapSymbolTable();
  24875. result.addAll(symbols.map(function (s) { return new DeclaredSymbol(s); }));
  24876. return result;
  24877. };
  24878. TypeScriptSymbolQuery.prototype.mergeSymbolTable = function (symbolTables) {
  24879. var e_1, _a;
  24880. var result = new MapSymbolTable();
  24881. try {
  24882. for (var symbolTables_1 = __values(symbolTables), symbolTables_1_1 = symbolTables_1.next(); !symbolTables_1_1.done; symbolTables_1_1 = symbolTables_1.next()) {
  24883. var symbolTable = symbolTables_1_1.value;
  24884. result.addAll(symbolTable.values());
  24885. }
  24886. }
  24887. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  24888. finally {
  24889. try {
  24890. if (symbolTables_1_1 && !symbolTables_1_1.done && (_a = symbolTables_1.return)) _a.call(symbolTables_1);
  24891. }
  24892. finally { if (e_1) throw e_1.error; }
  24893. }
  24894. return result;
  24895. };
  24896. TypeScriptSymbolQuery.prototype.getSpanAt = function (line, column) {
  24897. return spanAt(this.source, line, column);
  24898. };
  24899. TypeScriptSymbolQuery.prototype.getTemplateRefContextType = function (typeSymbol) {
  24900. var e_2, _a;
  24901. var type = this.checker.getTypeOfSymbolAtLocation(typeSymbol, this.source);
  24902. var constructor = type.symbol && type.symbol.members &&
  24903. getFromSymbolTable(type.symbol.members, '__constructor');
  24904. if (constructor) {
  24905. var constructorDeclaration = constructor.declarations[0];
  24906. try {
  24907. for (var _b = __values(constructorDeclaration.parameters), _c = _b.next(); !_c.done; _c = _b.next()) {
  24908. var parameter = _c.value;
  24909. var type_1 = this.checker.getTypeAtLocation(parameter.type);
  24910. if (type_1.symbol.name == 'TemplateRef' && isReferenceType(type_1)) {
  24911. var typeReference = type_1;
  24912. if (typeReference.typeArguments && typeReference.typeArguments.length === 1) {
  24913. return typeReference.typeArguments[0].symbol;
  24914. }
  24915. }
  24916. }
  24917. }
  24918. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  24919. finally {
  24920. try {
  24921. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  24922. }
  24923. finally { if (e_2) throw e_2.error; }
  24924. }
  24925. }
  24926. };
  24927. TypeScriptSymbolQuery.prototype.getTsTypeOf = function (symbol) {
  24928. var type = this.getTypeWrapper(symbol);
  24929. return type && type.tsType;
  24930. };
  24931. TypeScriptSymbolQuery.prototype.getTypeWrapper = function (symbol) {
  24932. var type = undefined;
  24933. if (symbol instanceof TypeWrapper) {
  24934. type = symbol;
  24935. }
  24936. else if (symbol.type instanceof TypeWrapper) {
  24937. type = symbol.type;
  24938. }
  24939. return type;
  24940. };
  24941. return TypeScriptSymbolQuery;
  24942. }());
  24943. function typeCallable(type) {
  24944. var signatures = type.getCallSignatures();
  24945. return signatures && signatures.length != 0;
  24946. }
  24947. function signaturesOf(type, context) {
  24948. return type.getCallSignatures().map(function (s) { return new SignatureWrapper(s, context); });
  24949. }
  24950. function selectSignature(type, context, types) {
  24951. // TODO: Do a better job of selecting the right signature.
  24952. var signatures = type.getCallSignatures();
  24953. return signatures.length ? new SignatureWrapper(signatures[0], context) : undefined;
  24954. }
  24955. var TypeWrapper = /** @class */ (function () {
  24956. function TypeWrapper(tsType, context) {
  24957. this.tsType = tsType;
  24958. this.context = context;
  24959. this.kind = 'type';
  24960. this.language = 'typescript';
  24961. this.type = undefined;
  24962. this.container = undefined;
  24963. this.public = true;
  24964. if (!tsType) {
  24965. throw Error('Internal: null type');
  24966. }
  24967. }
  24968. Object.defineProperty(TypeWrapper.prototype, "name", {
  24969. get: function () {
  24970. var symbol = this.tsType.symbol;
  24971. return (symbol && symbol.name) || '<anonymous>';
  24972. },
  24973. enumerable: true,
  24974. configurable: true
  24975. });
  24976. Object.defineProperty(TypeWrapper.prototype, "callable", {
  24977. get: function () { return typeCallable(this.tsType); },
  24978. enumerable: true,
  24979. configurable: true
  24980. });
  24981. Object.defineProperty(TypeWrapper.prototype, "nullable", {
  24982. get: function () {
  24983. return this.context.checker.getNonNullableType(this.tsType) != this.tsType;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. Object.defineProperty(TypeWrapper.prototype, "definition", {
  24989. get: function () {
  24990. var symbol = this.tsType.getSymbol();
  24991. return symbol ? definitionFromTsSymbol(symbol) : undefined;
  24992. },
  24993. enumerable: true,
  24994. configurable: true
  24995. });
  24996. TypeWrapper.prototype.members = function () {
  24997. return new SymbolTableWrapper(this.tsType.getProperties(), this.context);
  24998. };
  24999. TypeWrapper.prototype.signatures = function () { return signaturesOf(this.tsType, this.context); };
  25000. TypeWrapper.prototype.selectSignature = function (types) {
  25001. return selectSignature(this.tsType, this.context, types);
  25002. };
  25003. TypeWrapper.prototype.indexed = function (argument) { return undefined; };
  25004. return TypeWrapper;
  25005. }());
  25006. var SymbolWrapper = /** @class */ (function () {
  25007. function SymbolWrapper(symbol, context) {
  25008. this.context = context;
  25009. this.nullable = false;
  25010. this.language = 'typescript';
  25011. this.symbol = symbol && context && (symbol.flags & ts.SymbolFlags.Alias) ?
  25012. context.checker.getAliasedSymbol(symbol) :
  25013. symbol;
  25014. }
  25015. Object.defineProperty(SymbolWrapper.prototype, "name", {
  25016. get: function () { return this.symbol.name; },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. Object.defineProperty(SymbolWrapper.prototype, "kind", {
  25021. get: function () { return this.callable ? 'method' : 'property'; },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. Object.defineProperty(SymbolWrapper.prototype, "type", {
  25026. get: function () { return new TypeWrapper(this.tsType, this.context); },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. Object.defineProperty(SymbolWrapper.prototype, "container", {
  25031. get: function () { return getContainerOf(this.symbol, this.context); },
  25032. enumerable: true,
  25033. configurable: true
  25034. });
  25035. Object.defineProperty(SymbolWrapper.prototype, "public", {
  25036. get: function () {
  25037. // Symbols that are not explicitly made private are public.
  25038. return !isSymbolPrivate(this.symbol);
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. Object.defineProperty(SymbolWrapper.prototype, "callable", {
  25044. get: function () { return typeCallable(this.tsType); },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. Object.defineProperty(SymbolWrapper.prototype, "definition", {
  25049. get: function () { return definitionFromTsSymbol(this.symbol); },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. SymbolWrapper.prototype.members = function () {
  25054. if (!this._members) {
  25055. if ((this.symbol.flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface)) != 0) {
  25056. var declaredType = this.context.checker.getDeclaredTypeOfSymbol(this.symbol);
  25057. var typeWrapper = new TypeWrapper(declaredType, this.context);
  25058. this._members = typeWrapper.members();
  25059. }
  25060. else {
  25061. this._members = new SymbolTableWrapper(this.symbol.members, this.context);
  25062. }
  25063. }
  25064. return this._members;
  25065. };
  25066. SymbolWrapper.prototype.signatures = function () { return signaturesOf(this.tsType, this.context); };
  25067. SymbolWrapper.prototype.selectSignature = function (types) {
  25068. return selectSignature(this.tsType, this.context, types);
  25069. };
  25070. SymbolWrapper.prototype.indexed = function (argument) { return undefined; };
  25071. Object.defineProperty(SymbolWrapper.prototype, "tsType", {
  25072. get: function () {
  25073. var type = this._tsType;
  25074. if (!type) {
  25075. type = this._tsType =
  25076. this.context.checker.getTypeOfSymbolAtLocation(this.symbol, this.context.node);
  25077. }
  25078. return type;
  25079. },
  25080. enumerable: true,
  25081. configurable: true
  25082. });
  25083. return SymbolWrapper;
  25084. }());
  25085. var DeclaredSymbol = /** @class */ (function () {
  25086. function DeclaredSymbol(declaration) {
  25087. this.declaration = declaration;
  25088. this.language = 'ng-template';
  25089. this.nullable = false;
  25090. this.public = true;
  25091. }
  25092. Object.defineProperty(DeclaredSymbol.prototype, "name", {
  25093. get: function () { return this.declaration.name; },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. Object.defineProperty(DeclaredSymbol.prototype, "kind", {
  25098. get: function () { return this.declaration.kind; },
  25099. enumerable: true,
  25100. configurable: true
  25101. });
  25102. Object.defineProperty(DeclaredSymbol.prototype, "container", {
  25103. get: function () { return undefined; },
  25104. enumerable: true,
  25105. configurable: true
  25106. });
  25107. Object.defineProperty(DeclaredSymbol.prototype, "type", {
  25108. get: function () { return this.declaration.type; },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. Object.defineProperty(DeclaredSymbol.prototype, "callable", {
  25113. get: function () { return this.declaration.type.callable; },
  25114. enumerable: true,
  25115. configurable: true
  25116. });
  25117. Object.defineProperty(DeclaredSymbol.prototype, "definition", {
  25118. get: function () { return this.declaration.definition; },
  25119. enumerable: true,
  25120. configurable: true
  25121. });
  25122. DeclaredSymbol.prototype.members = function () { return this.declaration.type.members(); };
  25123. DeclaredSymbol.prototype.signatures = function () { return this.declaration.type.signatures(); };
  25124. DeclaredSymbol.prototype.selectSignature = function (types) {
  25125. return this.declaration.type.selectSignature(types);
  25126. };
  25127. DeclaredSymbol.prototype.indexed = function (argument) { return undefined; };
  25128. return DeclaredSymbol;
  25129. }());
  25130. var SignatureWrapper = /** @class */ (function () {
  25131. function SignatureWrapper(signature, context) {
  25132. this.signature = signature;
  25133. this.context = context;
  25134. }
  25135. Object.defineProperty(SignatureWrapper.prototype, "arguments", {
  25136. get: function () {
  25137. return new SymbolTableWrapper(this.signature.getParameters(), this.context);
  25138. },
  25139. enumerable: true,
  25140. configurable: true
  25141. });
  25142. Object.defineProperty(SignatureWrapper.prototype, "result", {
  25143. get: function () { return new TypeWrapper(this.signature.getReturnType(), this.context); },
  25144. enumerable: true,
  25145. configurable: true
  25146. });
  25147. return SignatureWrapper;
  25148. }());
  25149. var SignatureResultOverride = /** @class */ (function () {
  25150. function SignatureResultOverride(signature, resultType) {
  25151. this.signature = signature;
  25152. this.resultType = resultType;
  25153. }
  25154. Object.defineProperty(SignatureResultOverride.prototype, "arguments", {
  25155. get: function () { return this.signature.arguments; },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. Object.defineProperty(SignatureResultOverride.prototype, "result", {
  25160. get: function () { return this.resultType; },
  25161. enumerable: true,
  25162. configurable: true
  25163. });
  25164. return SignatureResultOverride;
  25165. }());
  25166. /**
  25167. * Indicates the lower bound TypeScript version supporting `SymbolTable` as an ES6 `Map`.
  25168. * For lower versions, `SymbolTable` is implemented as a dictionary
  25169. */
  25170. var MIN_TS_VERSION_SUPPORTING_MAP = '2.2';
  25171. var toSymbolTableFactory = function (tsVersion) { return function (symbols) {
  25172. var e_3, _a, e_4, _b;
  25173. if (isVersionBetween(tsVersion, MIN_TS_VERSION_SUPPORTING_MAP)) {
  25174. // ∀ Typescript version >= 2.2, `SymbolTable` is implemented as an ES6 `Map`
  25175. var result_1 = new Map();
  25176. try {
  25177. for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
  25178. var symbol = symbols_1_1.value;
  25179. result_1.set(symbol.name, symbol);
  25180. }
  25181. }
  25182. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  25183. finally {
  25184. try {
  25185. if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
  25186. }
  25187. finally { if (e_3) throw e_3.error; }
  25188. }
  25189. // First, tell the compiler that `result` is of type `any`. Then, use a second type assertion
  25190. // to `ts.SymbolTable`.
  25191. // Otherwise, `Map<string, ts.Symbol>` and `ts.SymbolTable` will be considered as incompatible
  25192. // types by the compiler
  25193. return result_1;
  25194. }
  25195. // ∀ Typescript version < 2.2, `SymbolTable` is implemented as a dictionary
  25196. var result = {};
  25197. try {
  25198. for (var symbols_2 = __values(symbols), symbols_2_1 = symbols_2.next(); !symbols_2_1.done; symbols_2_1 = symbols_2.next()) {
  25199. var symbol = symbols_2_1.value;
  25200. result[symbol.name] = symbol;
  25201. }
  25202. }
  25203. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  25204. finally {
  25205. try {
  25206. if (symbols_2_1 && !symbols_2_1.done && (_b = symbols_2.return)) _b.call(symbols_2);
  25207. }
  25208. finally { if (e_4) throw e_4.error; }
  25209. }
  25210. return result;
  25211. }; };
  25212. function toSymbols(symbolTable) {
  25213. if (!symbolTable)
  25214. return [];
  25215. var table = symbolTable;
  25216. if (typeof table.values === 'function') {
  25217. return Array.from(table.values());
  25218. }
  25219. var result = [];
  25220. var own = typeof table.hasOwnProperty === 'function' ?
  25221. function (name) { return table.hasOwnProperty(name); } :
  25222. function (name) { return !!table[name]; };
  25223. for (var name in table) {
  25224. if (own(name)) {
  25225. result.push(table[name]);
  25226. }
  25227. }
  25228. return result;
  25229. }
  25230. var SymbolTableWrapper = /** @class */ (function () {
  25231. function SymbolTableWrapper(symbols, context) {
  25232. this.context = context;
  25233. symbols = symbols || [];
  25234. if (Array.isArray(symbols)) {
  25235. this.symbols = symbols;
  25236. var toSymbolTable = toSymbolTableFactory(ts.version);
  25237. this.symbolTable = toSymbolTable(symbols);
  25238. }
  25239. else {
  25240. this.symbols = toSymbols(symbols);
  25241. this.symbolTable = symbols;
  25242. }
  25243. }
  25244. Object.defineProperty(SymbolTableWrapper.prototype, "size", {
  25245. get: function () { return this.symbols.length; },
  25246. enumerable: true,
  25247. configurable: true
  25248. });
  25249. SymbolTableWrapper.prototype.get = function (key) {
  25250. var symbol = getFromSymbolTable(this.symbolTable, key);
  25251. return symbol ? new SymbolWrapper(symbol, this.context) : undefined;
  25252. };
  25253. SymbolTableWrapper.prototype.has = function (key) {
  25254. var table = this.symbolTable;
  25255. return (typeof table.has === 'function') ? table.has(key) : table[key] != null;
  25256. };
  25257. SymbolTableWrapper.prototype.values = function () {
  25258. var _this = this;
  25259. return this.symbols.map(function (s) { return new SymbolWrapper(s, _this.context); });
  25260. };
  25261. return SymbolTableWrapper;
  25262. }());
  25263. var MapSymbolTable = /** @class */ (function () {
  25264. function MapSymbolTable() {
  25265. this.map = new Map();
  25266. this._values = [];
  25267. }
  25268. Object.defineProperty(MapSymbolTable.prototype, "size", {
  25269. get: function () { return this.map.size; },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. MapSymbolTable.prototype.get = function (key) { return this.map.get(key); };
  25274. MapSymbolTable.prototype.add = function (symbol) {
  25275. if (this.map.has(symbol.name)) {
  25276. var previous = this.map.get(symbol.name);
  25277. this._values[this._values.indexOf(previous)] = symbol;
  25278. }
  25279. this.map.set(symbol.name, symbol);
  25280. this._values.push(symbol);
  25281. };
  25282. MapSymbolTable.prototype.addAll = function (symbols) {
  25283. var e_5, _a;
  25284. try {
  25285. for (var symbols_3 = __values(symbols), symbols_3_1 = symbols_3.next(); !symbols_3_1.done; symbols_3_1 = symbols_3.next()) {
  25286. var symbol = symbols_3_1.value;
  25287. this.add(symbol);
  25288. }
  25289. }
  25290. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  25291. finally {
  25292. try {
  25293. if (symbols_3_1 && !symbols_3_1.done && (_a = symbols_3.return)) _a.call(symbols_3);
  25294. }
  25295. finally { if (e_5) throw e_5.error; }
  25296. }
  25297. };
  25298. MapSymbolTable.prototype.has = function (key) { return this.map.has(key); };
  25299. MapSymbolTable.prototype.values = function () {
  25300. // Switch to this.map.values once iterables are supported by the target language.
  25301. return this._values;
  25302. };
  25303. return MapSymbolTable;
  25304. }());
  25305. var PipesTable = /** @class */ (function () {
  25306. function PipesTable(pipes, context) {
  25307. this.pipes = pipes;
  25308. this.context = context;
  25309. }
  25310. Object.defineProperty(PipesTable.prototype, "size", {
  25311. get: function () { return this.pipes.length; },
  25312. enumerable: true,
  25313. configurable: true
  25314. });
  25315. PipesTable.prototype.get = function (key) {
  25316. var pipe = this.pipes.find(function (pipe) { return pipe.name == key; });
  25317. if (pipe) {
  25318. return new PipeSymbol(pipe, this.context);
  25319. }
  25320. };
  25321. PipesTable.prototype.has = function (key) { return this.pipes.find(function (pipe) { return pipe.name == key; }) != null; };
  25322. PipesTable.prototype.values = function () {
  25323. var _this = this;
  25324. return this.pipes.map(function (pipe) { return new PipeSymbol(pipe, _this.context); });
  25325. };
  25326. return PipesTable;
  25327. }());
  25328. // This matches .d.ts files that look like ".../<package-name>/<package-name>.d.ts",
  25329. var INDEX_PATTERN = /[\\/]([^\\/]+)[\\/]\1\.d\.ts$/;
  25330. var PipeSymbol = /** @class */ (function () {
  25331. function PipeSymbol(pipe, context) {
  25332. this.pipe = pipe;
  25333. this.context = context;
  25334. this.kind = 'pipe';
  25335. this.language = 'typescript';
  25336. this.container = undefined;
  25337. this.callable = true;
  25338. this.nullable = false;
  25339. this.public = true;
  25340. }
  25341. Object.defineProperty(PipeSymbol.prototype, "name", {
  25342. get: function () { return this.pipe.name; },
  25343. enumerable: true,
  25344. configurable: true
  25345. });
  25346. Object.defineProperty(PipeSymbol.prototype, "type", {
  25347. get: function () { return new TypeWrapper(this.tsType, this.context); },
  25348. enumerable: true,
  25349. configurable: true
  25350. });
  25351. Object.defineProperty(PipeSymbol.prototype, "definition", {
  25352. get: function () {
  25353. var symbol = this.tsType.getSymbol();
  25354. return symbol ? definitionFromTsSymbol(symbol) : undefined;
  25355. },
  25356. enumerable: true,
  25357. configurable: true
  25358. });
  25359. PipeSymbol.prototype.members = function () { return EmptyTable.instance; };
  25360. PipeSymbol.prototype.signatures = function () { return signaturesOf(this.tsType, this.context); };
  25361. PipeSymbol.prototype.selectSignature = function (types) {
  25362. var signature = selectSignature(this.tsType, this.context, types);
  25363. if (types.length == 1) {
  25364. var parameterType = types[0];
  25365. if (parameterType instanceof TypeWrapper) {
  25366. var resultType = undefined;
  25367. switch (this.name) {
  25368. case 'async':
  25369. switch (parameterType.name) {
  25370. case 'Observable':
  25371. case 'Promise':
  25372. case 'EventEmitter':
  25373. resultType = getTypeParameterOf(parameterType.tsType, parameterType.name);
  25374. break;
  25375. default:
  25376. resultType = getBuiltinTypeFromTs(BuiltinType$1.Any, this.context);
  25377. break;
  25378. }
  25379. break;
  25380. case 'slice':
  25381. resultType = getTypeParameterOf(parameterType.tsType, 'Array');
  25382. break;
  25383. }
  25384. if (resultType) {
  25385. signature = new SignatureResultOverride(signature, new TypeWrapper(resultType, parameterType.context));
  25386. }
  25387. }
  25388. }
  25389. return signature;
  25390. };
  25391. PipeSymbol.prototype.indexed = function (argument) { return undefined; };
  25392. Object.defineProperty(PipeSymbol.prototype, "tsType", {
  25393. get: function () {
  25394. var type = this._tsType;
  25395. if (!type) {
  25396. var classSymbol = this.findClassSymbol(this.pipe.type.reference);
  25397. if (classSymbol) {
  25398. type = this._tsType = this.findTransformMethodType(classSymbol);
  25399. }
  25400. if (!type) {
  25401. type = this._tsType = getBuiltinTypeFromTs(BuiltinType$1.Any, this.context);
  25402. }
  25403. }
  25404. return type;
  25405. },
  25406. enumerable: true,
  25407. configurable: true
  25408. });
  25409. PipeSymbol.prototype.findClassSymbol = function (type) {
  25410. return findClassSymbolInContext(type, this.context);
  25411. };
  25412. PipeSymbol.prototype.findTransformMethodType = function (classSymbol) {
  25413. var classType = this.context.checker.getDeclaredTypeOfSymbol(classSymbol);
  25414. if (classType) {
  25415. var transform = classType.getProperty('transform');
  25416. if (transform) {
  25417. return this.context.checker.getTypeOfSymbolAtLocation(transform, this.context.node);
  25418. }
  25419. }
  25420. };
  25421. return PipeSymbol;
  25422. }());
  25423. function findClassSymbolInContext(type, context) {
  25424. var sourceFile = context.program.getSourceFile(type.filePath);
  25425. if (!sourceFile) {
  25426. // This handles a case where an <packageName>/index.d.ts and a <packageName>/<packageName>.d.ts
  25427. // are in the same directory. If we are looking for <packageName>/<packageName> and didn't
  25428. // find it, look for <packageName>/index.d.ts as the program might have found that instead.
  25429. var p = type.filePath;
  25430. var m = p.match(INDEX_PATTERN);
  25431. if (m) {
  25432. var indexVersion = path.join(path.dirname(p), 'index.d.ts');
  25433. sourceFile = context.program.getSourceFile(indexVersion);
  25434. }
  25435. }
  25436. if (sourceFile) {
  25437. var moduleSymbol = sourceFile.module || sourceFile.symbol;
  25438. var exports_1 = context.checker.getExportsOfModule(moduleSymbol);
  25439. return (exports_1 || []).find(function (symbol) { return symbol.name == type.name; });
  25440. }
  25441. }
  25442. var EmptyTable = /** @class */ (function () {
  25443. function EmptyTable() {
  25444. this.size = 0;
  25445. }
  25446. EmptyTable.prototype.get = function (key) { return undefined; };
  25447. EmptyTable.prototype.has = function (key) { return false; };
  25448. EmptyTable.prototype.values = function () { return []; };
  25449. EmptyTable.instance = new EmptyTable();
  25450. return EmptyTable;
  25451. }());
  25452. function isSymbolPrivate(s) {
  25453. return !!s.valueDeclaration && isPrivate(s.valueDeclaration);
  25454. }
  25455. function getBuiltinTypeFromTs(kind, context) {
  25456. var type;
  25457. var checker = context.checker;
  25458. var node = context.node;
  25459. switch (kind) {
  25460. case BuiltinType$1.Any:
  25461. type = checker.getTypeAtLocation(setParents({
  25462. kind: ts.SyntaxKind.AsExpression,
  25463. expression: { kind: ts.SyntaxKind.TrueKeyword },
  25464. type: { kind: ts.SyntaxKind.AnyKeyword }
  25465. }, node));
  25466. break;
  25467. case BuiltinType$1.Boolean:
  25468. type =
  25469. checker.getTypeAtLocation(setParents({ kind: ts.SyntaxKind.TrueKeyword }, node));
  25470. break;
  25471. case BuiltinType$1.Null:
  25472. type =
  25473. checker.getTypeAtLocation(setParents({ kind: ts.SyntaxKind.NullKeyword }, node));
  25474. break;
  25475. case BuiltinType$1.Number:
  25476. var numeric = {
  25477. kind: ts.SyntaxKind.NumericLiteral,
  25478. text: node.getText(),
  25479. };
  25480. setParents({ kind: ts.SyntaxKind.ExpressionStatement, expression: numeric }, node);
  25481. type = checker.getTypeAtLocation(numeric);
  25482. break;
  25483. case BuiltinType$1.String:
  25484. type = checker.getTypeAtLocation(setParents({
  25485. kind: ts.SyntaxKind.NoSubstitutionTemplateLiteral,
  25486. text: node.getText(),
  25487. }, node));
  25488. break;
  25489. case BuiltinType$1.Undefined:
  25490. type = checker.getTypeAtLocation(setParents({
  25491. kind: ts.SyntaxKind.VoidExpression,
  25492. expression: { kind: ts.SyntaxKind.NumericLiteral }
  25493. }, node));
  25494. break;
  25495. default:
  25496. throw new Error("Internal error, unhandled literal kind " + kind + ":" + BuiltinType$1[kind]);
  25497. }
  25498. return type;
  25499. }
  25500. function setParents(node, parent) {
  25501. node.parent = parent;
  25502. ts.forEachChild(node, function (child) { return setParents(child, node); });
  25503. return node;
  25504. }
  25505. function spanAt(sourceFile, line, column) {
  25506. if (line != null && column != null) {
  25507. var position_1 = ts.getPositionOfLineAndCharacter(sourceFile, line, column);
  25508. var findChild = function findChild(node) {
  25509. if (node.kind > ts.SyntaxKind.LastToken && node.pos <= position_1 && node.end > position_1) {
  25510. var betterNode = ts.forEachChild(node, findChild);
  25511. return betterNode || node;
  25512. }
  25513. };
  25514. var node = ts.forEachChild(sourceFile, findChild);
  25515. if (node) {
  25516. return { start: node.getStart(), end: node.getEnd() };
  25517. }
  25518. }
  25519. }
  25520. function definitionFromTsSymbol(symbol) {
  25521. var declarations = symbol.declarations;
  25522. if (declarations) {
  25523. return declarations.map(function (declaration) {
  25524. var sourceFile = declaration.getSourceFile();
  25525. return {
  25526. fileName: sourceFile.fileName,
  25527. span: { start: declaration.getStart(), end: declaration.getEnd() }
  25528. };
  25529. });
  25530. }
  25531. }
  25532. function parentDeclarationOf(node) {
  25533. while (node) {
  25534. switch (node.kind) {
  25535. case ts.SyntaxKind.ClassDeclaration:
  25536. case ts.SyntaxKind.InterfaceDeclaration:
  25537. return node;
  25538. case ts.SyntaxKind.SourceFile:
  25539. return undefined;
  25540. }
  25541. node = node.parent;
  25542. }
  25543. }
  25544. function getContainerOf(symbol, context) {
  25545. var e_6, _a;
  25546. if (symbol.getFlags() & ts.SymbolFlags.ClassMember && symbol.declarations) {
  25547. try {
  25548. for (var _b = __values(symbol.declarations), _c = _b.next(); !_c.done; _c = _b.next()) {
  25549. var declaration = _c.value;
  25550. var parent = parentDeclarationOf(declaration);
  25551. if (parent) {
  25552. var type = context.checker.getTypeAtLocation(parent);
  25553. if (type) {
  25554. return new TypeWrapper(type, context);
  25555. }
  25556. }
  25557. }
  25558. }
  25559. catch (e_6_1) { e_6 = { error: e_6_1 }; }
  25560. finally {
  25561. try {
  25562. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  25563. }
  25564. finally { if (e_6) throw e_6.error; }
  25565. }
  25566. }
  25567. }
  25568. function getTypeParameterOf(type, name) {
  25569. if (type && type.symbol && type.symbol.name == name) {
  25570. var typeArguments = type.typeArguments;
  25571. if (typeArguments && typeArguments.length <= 1) {
  25572. return typeArguments[0];
  25573. }
  25574. }
  25575. }
  25576. function typeKindOf(type) {
  25577. var e_7, _a;
  25578. if (type) {
  25579. if (type.flags & ts.TypeFlags.Any) {
  25580. return BuiltinType$1.Any;
  25581. }
  25582. else if (type.flags & (ts.TypeFlags.String | ts.TypeFlags.StringLike | ts.TypeFlags.StringLiteral)) {
  25583. return BuiltinType$1.String;
  25584. }
  25585. else if (type.flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLike)) {
  25586. return BuiltinType$1.Number;
  25587. }
  25588. else if (type.flags & (ts.TypeFlags.Undefined)) {
  25589. return BuiltinType$1.Undefined;
  25590. }
  25591. else if (type.flags & (ts.TypeFlags.Null)) {
  25592. return BuiltinType$1.Null;
  25593. }
  25594. else if (type.flags & ts.TypeFlags.Union) {
  25595. // If all the constituent types of a union are the same kind, it is also that kind.
  25596. var candidate = null;
  25597. var unionType_1 = type;
  25598. if (unionType_1.types.length > 0) {
  25599. candidate = typeKindOf(unionType_1.types[0]);
  25600. try {
  25601. for (var _b = __values(unionType_1.types), _c = _b.next(); !_c.done; _c = _b.next()) {
  25602. var subType = _c.value;
  25603. if (candidate != typeKindOf(subType)) {
  25604. return BuiltinType$1.Other;
  25605. }
  25606. }
  25607. }
  25608. catch (e_7_1) { e_7 = { error: e_7_1 }; }
  25609. finally {
  25610. try {
  25611. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  25612. }
  25613. finally { if (e_7) throw e_7.error; }
  25614. }
  25615. }
  25616. if (candidate != null) {
  25617. return candidate;
  25618. }
  25619. }
  25620. else if (type.flags & ts.TypeFlags.TypeParameter) {
  25621. return BuiltinType$1.Unbound;
  25622. }
  25623. }
  25624. return BuiltinType$1.Other;
  25625. }
  25626. function getFromSymbolTable(symbolTable, key) {
  25627. var table = symbolTable;
  25628. var symbol;
  25629. if (typeof table.get === 'function') {
  25630. // TS 2.2 uses a Map
  25631. symbol = table.get(key);
  25632. }
  25633. else {
  25634. // TS pre-2.2 uses an object
  25635. symbol = table[key];
  25636. }
  25637. return symbol;
  25638. }
  25639. /**
  25640. * @license
  25641. * Copyright Google Inc. All Rights Reserved.
  25642. *
  25643. * Use of this source code is governed by an MIT-style license that can be
  25644. * found in the LICENSE file at https://angular.io/license
  25645. */
  25646. // Metadata Schema
  25647. // If you make a backwards incompatible change to the schema, increment the METADTA_VERSION number.
  25648. // If you make a backwards compatible change to the metadata (such as adding an option field) then
  25649. // leave METADATA_VERSION the same. If possible, supply as many versions of the metadata that can
  25650. // represent the semantics of the file in an array. For example, when generating a version 2 file,
  25651. // if version 1 can accurately represent the metadata, generate both version 1 and version 2 in
  25652. // an array.
  25653. var METADATA_VERSION = 4;
  25654. function isClassMetadata(value) {
  25655. return value && value.__symbolic === 'class';
  25656. }
  25657. function isMethodMetadata(value) {
  25658. return value && (value.__symbolic === 'constructor' || value.__symbolic === 'method');
  25659. }
  25660. function isConstructorMetadata(value) {
  25661. return value && value.__symbolic === 'constructor';
  25662. }
  25663. function isFunctionMetadata(value) {
  25664. return value && value.__symbolic === 'function';
  25665. }
  25666. function isMetadataSymbolicExpression(value) {
  25667. if (value) {
  25668. switch (value.__symbolic) {
  25669. case 'binary':
  25670. case 'call':
  25671. case 'index':
  25672. case 'new':
  25673. case 'pre':
  25674. case 'reference':
  25675. case 'select':
  25676. case 'spread':
  25677. case 'if':
  25678. return true;
  25679. }
  25680. }
  25681. return false;
  25682. }
  25683. function isMetadataGlobalReferenceExpression(value) {
  25684. return value && value.name && !value.module && isMetadataSymbolicReferenceExpression(value);
  25685. }
  25686. function isMetadataModuleReferenceExpression(value) {
  25687. return value && value.module && !value.name && !value.default &&
  25688. isMetadataSymbolicReferenceExpression(value);
  25689. }
  25690. function isMetadataImportedSymbolReferenceExpression(value) {
  25691. return value && value.module && !!value.name && isMetadataSymbolicReferenceExpression(value);
  25692. }
  25693. function isMetadataImportDefaultReference(value) {
  25694. return value && value.module && value.default && isMetadataSymbolicReferenceExpression(value);
  25695. }
  25696. function isMetadataSymbolicReferenceExpression(value) {
  25697. return value && value.__symbolic === 'reference';
  25698. }
  25699. function isMetadataSymbolicSelectExpression(value) {
  25700. return value && value.__symbolic === 'select';
  25701. }
  25702. function isMetadataSymbolicSpreadExpression(value) {
  25703. return value && value.__symbolic === 'spread';
  25704. }
  25705. function isMetadataError$1(value) {
  25706. return value && value.__symbolic === 'error';
  25707. }
  25708. /**
  25709. * @license
  25710. * Copyright Google Inc. All Rights Reserved.
  25711. *
  25712. * Use of this source code is governed by an MIT-style license that can be
  25713. * found in the LICENSE file at https://angular.io/license
  25714. */
  25715. // In TypeScript 2.1 the spread element kind was renamed.
  25716. var spreadElementSyntaxKind = ts.SyntaxKind.SpreadElement || ts.SyntaxKind.SpreadElementExpression;
  25717. function isMethodCallOf(callExpression, memberName) {
  25718. var expression = callExpression.expression;
  25719. if (expression.kind === ts.SyntaxKind.PropertyAccessExpression) {
  25720. var propertyAccessExpression = expression;
  25721. var name = propertyAccessExpression.name;
  25722. if (name.kind == ts.SyntaxKind.Identifier) {
  25723. return name.text === memberName;
  25724. }
  25725. }
  25726. return false;
  25727. }
  25728. function isCallOf(callExpression, ident) {
  25729. var expression = callExpression.expression;
  25730. if (expression.kind === ts.SyntaxKind.Identifier) {
  25731. var identifier = expression;
  25732. return identifier.text === ident;
  25733. }
  25734. return false;
  25735. }
  25736. /* @internal */
  25737. function recordMapEntry(entry, node, nodeMap, sourceFile) {
  25738. if (!nodeMap.has(entry)) {
  25739. nodeMap.set(entry, node);
  25740. if (node && (isMetadataImportedSymbolReferenceExpression(entry) ||
  25741. isMetadataImportDefaultReference(entry)) &&
  25742. entry.line == null) {
  25743. var info = sourceInfo(node, sourceFile);
  25744. if (info.line != null)
  25745. entry.line = info.line;
  25746. if (info.character != null)
  25747. entry.character = info.character;
  25748. }
  25749. }
  25750. return entry;
  25751. }
  25752. /**
  25753. * ts.forEachChild stops iterating children when the callback return a truthy value.
  25754. * This method inverts this to implement an `every` style iterator. It will return
  25755. * true if every call to `cb` returns `true`.
  25756. */
  25757. function everyNodeChild(node, cb) {
  25758. return !ts.forEachChild(node, function (node) { return !cb(node); });
  25759. }
  25760. function isPrimitive$1(value) {
  25761. return Object(value) !== value;
  25762. }
  25763. function isDefined$1(obj) {
  25764. return obj !== undefined;
  25765. }
  25766. function getSourceFileOfNode(node) {
  25767. while (node && node.kind != ts.SyntaxKind.SourceFile) {
  25768. node = node.parent;
  25769. }
  25770. return node;
  25771. }
  25772. /* @internal */
  25773. function sourceInfo(node, sourceFile) {
  25774. if (node) {
  25775. sourceFile = sourceFile || getSourceFileOfNode(node);
  25776. if (sourceFile) {
  25777. return ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile));
  25778. }
  25779. }
  25780. return {};
  25781. }
  25782. /* @internal */
  25783. function errorSymbol(message, node, context, sourceFile) {
  25784. var result = __assign({ __symbolic: 'error', message: message }, sourceInfo(node, sourceFile));
  25785. if (context) {
  25786. result.context = context;
  25787. }
  25788. return result;
  25789. }
  25790. /**
  25791. * Produce a symbolic representation of an expression folding values into their final value when
  25792. * possible.
  25793. */
  25794. var Evaluator = /** @class */ (function () {
  25795. function Evaluator(symbols, nodeMap, options, recordExport) {
  25796. if (options === void 0) { options = {}; }
  25797. this.symbols = symbols;
  25798. this.nodeMap = nodeMap;
  25799. this.options = options;
  25800. this.recordExport = recordExport;
  25801. }
  25802. Evaluator.prototype.nameOf = function (node) {
  25803. if (node && node.kind == ts.SyntaxKind.Identifier) {
  25804. return node.text;
  25805. }
  25806. var result = node && this.evaluateNode(node);
  25807. if (isMetadataError$1(result) || typeof result === 'string') {
  25808. return result;
  25809. }
  25810. else {
  25811. return errorSymbol('Name expected', node, { received: (node && node.getText()) || '<missing>' });
  25812. }
  25813. };
  25814. /**
  25815. * Returns true if the expression represented by `node` can be folded into a literal expression.
  25816. *
  25817. * For example, a literal is always foldable. This means that literal expressions such as `1.2`
  25818. * `"Some value"` `true` `false` are foldable.
  25819. *
  25820. * - An object literal is foldable if all the properties in the literal are foldable.
  25821. * - An array literal is foldable if all the elements are foldable.
  25822. * - A call is foldable if it is a call to a Array.prototype.concat or a call to CONST_EXPR.
  25823. * - A property access is foldable if the object is foldable.
  25824. * - A array index is foldable if index expression is foldable and the array is foldable.
  25825. * - Binary operator expressions are foldable if the left and right expressions are foldable and
  25826. * it is one of '+', '-', '*', '/', '%', '||', and '&&'.
  25827. * - An identifier is foldable if a value can be found for its symbol in the evaluator symbol
  25828. * table.
  25829. */
  25830. Evaluator.prototype.isFoldable = function (node) {
  25831. return this.isFoldableWorker(node, new Map());
  25832. };
  25833. Evaluator.prototype.isFoldableWorker = function (node, folding) {
  25834. var _this = this;
  25835. if (node) {
  25836. switch (node.kind) {
  25837. case ts.SyntaxKind.ObjectLiteralExpression:
  25838. return everyNodeChild(node, function (child) {
  25839. if (child.kind === ts.SyntaxKind.PropertyAssignment) {
  25840. var propertyAssignment = child;
  25841. return _this.isFoldableWorker(propertyAssignment.initializer, folding);
  25842. }
  25843. return false;
  25844. });
  25845. case ts.SyntaxKind.ArrayLiteralExpression:
  25846. return everyNodeChild(node, function (child) { return _this.isFoldableWorker(child, folding); });
  25847. case ts.SyntaxKind.CallExpression:
  25848. var callExpression = node;
  25849. // We can fold a <array>.concat(<v>).
  25850. if (isMethodCallOf(callExpression, 'concat') &&
  25851. arrayOrEmpty(callExpression.arguments).length === 1) {
  25852. var arrayNode = callExpression.expression.expression;
  25853. if (this.isFoldableWorker(arrayNode, folding) &&
  25854. this.isFoldableWorker(callExpression.arguments[0], folding)) {
  25855. // It needs to be an array.
  25856. var arrayValue = this.evaluateNode(arrayNode);
  25857. if (arrayValue && Array.isArray(arrayValue)) {
  25858. return true;
  25859. }
  25860. }
  25861. }
  25862. // We can fold a call to CONST_EXPR
  25863. if (isCallOf(callExpression, 'CONST_EXPR') &&
  25864. arrayOrEmpty(callExpression.arguments).length === 1)
  25865. return this.isFoldableWorker(callExpression.arguments[0], folding);
  25866. return false;
  25867. case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
  25868. case ts.SyntaxKind.StringLiteral:
  25869. case ts.SyntaxKind.NumericLiteral:
  25870. case ts.SyntaxKind.NullKeyword:
  25871. case ts.SyntaxKind.TrueKeyword:
  25872. case ts.SyntaxKind.FalseKeyword:
  25873. case ts.SyntaxKind.TemplateHead:
  25874. case ts.SyntaxKind.TemplateMiddle:
  25875. case ts.SyntaxKind.TemplateTail:
  25876. return true;
  25877. case ts.SyntaxKind.ParenthesizedExpression:
  25878. var parenthesizedExpression = node;
  25879. return this.isFoldableWorker(parenthesizedExpression.expression, folding);
  25880. case ts.SyntaxKind.BinaryExpression:
  25881. var binaryExpression = node;
  25882. switch (binaryExpression.operatorToken.kind) {
  25883. case ts.SyntaxKind.PlusToken:
  25884. case ts.SyntaxKind.MinusToken:
  25885. case ts.SyntaxKind.AsteriskToken:
  25886. case ts.SyntaxKind.SlashToken:
  25887. case ts.SyntaxKind.PercentToken:
  25888. case ts.SyntaxKind.AmpersandAmpersandToken:
  25889. case ts.SyntaxKind.BarBarToken:
  25890. return this.isFoldableWorker(binaryExpression.left, folding) &&
  25891. this.isFoldableWorker(binaryExpression.right, folding);
  25892. default:
  25893. return false;
  25894. }
  25895. case ts.SyntaxKind.PropertyAccessExpression:
  25896. var propertyAccessExpression = node;
  25897. return this.isFoldableWorker(propertyAccessExpression.expression, folding);
  25898. case ts.SyntaxKind.ElementAccessExpression:
  25899. var elementAccessExpression = node;
  25900. return this.isFoldableWorker(elementAccessExpression.expression, folding) &&
  25901. this.isFoldableWorker(elementAccessExpression.argumentExpression, folding);
  25902. case ts.SyntaxKind.Identifier:
  25903. var identifier = node;
  25904. var reference = this.symbols.resolve(identifier.text);
  25905. if (reference !== undefined && isPrimitive$1(reference)) {
  25906. return true;
  25907. }
  25908. break;
  25909. case ts.SyntaxKind.TemplateExpression:
  25910. var templateExpression = node;
  25911. return templateExpression.templateSpans.every(function (span) { return _this.isFoldableWorker(span.expression, folding); });
  25912. }
  25913. }
  25914. return false;
  25915. };
  25916. /**
  25917. * Produce a JSON serialiable object representing `node`. The foldable values in the expression
  25918. * tree are folded. For example, a node representing `1 + 2` is folded into `3`.
  25919. */
  25920. Evaluator.prototype.evaluateNode = function (node, preferReference) {
  25921. var _this = this;
  25922. var t = this;
  25923. var error;
  25924. function recordEntry(entry, node) {
  25925. if (t.options.substituteExpression) {
  25926. var newEntry = t.options.substituteExpression(entry, node);
  25927. if (t.recordExport && newEntry != entry && isMetadataGlobalReferenceExpression(newEntry)) {
  25928. t.recordExport(newEntry.name, entry);
  25929. }
  25930. entry = newEntry;
  25931. }
  25932. return recordMapEntry(entry, node, t.nodeMap);
  25933. }
  25934. function isFoldableError(value) {
  25935. return !t.options.verboseInvalidExpression && isMetadataError$1(value);
  25936. }
  25937. var resolveName = function (name, preferReference) {
  25938. var reference = _this.symbols.resolve(name, preferReference);
  25939. if (reference === undefined) {
  25940. // Encode as a global reference. StaticReflector will check the reference.
  25941. return recordEntry({ __symbolic: 'reference', name: name }, node);
  25942. }
  25943. if (reference && isMetadataSymbolicReferenceExpression(reference)) {
  25944. return recordEntry(__assign({}, reference), node);
  25945. }
  25946. return reference;
  25947. };
  25948. switch (node.kind) {
  25949. case ts.SyntaxKind.ObjectLiteralExpression:
  25950. var obj_1 = {};
  25951. var quoted_1 = [];
  25952. ts.forEachChild(node, function (child) {
  25953. switch (child.kind) {
  25954. case ts.SyntaxKind.ShorthandPropertyAssignment:
  25955. case ts.SyntaxKind.PropertyAssignment:
  25956. var assignment = child;
  25957. if (assignment.name.kind == ts.SyntaxKind.StringLiteral) {
  25958. var name_1 = assignment.name.text;
  25959. quoted_1.push(name_1);
  25960. }
  25961. var propertyName = _this.nameOf(assignment.name);
  25962. if (isFoldableError(propertyName)) {
  25963. error = propertyName;
  25964. return true;
  25965. }
  25966. var propertyValue = isPropertyAssignment(assignment) ?
  25967. _this.evaluateNode(assignment.initializer, /* preferReference */ true) :
  25968. resolveName(propertyName, /* preferReference */ true);
  25969. if (isFoldableError(propertyValue)) {
  25970. error = propertyValue;
  25971. return true; // Stop the forEachChild.
  25972. }
  25973. else {
  25974. obj_1[propertyName] = isPropertyAssignment(assignment) ?
  25975. recordEntry(propertyValue, assignment.initializer) :
  25976. propertyValue;
  25977. }
  25978. }
  25979. });
  25980. if (error)
  25981. return error;
  25982. if (this.options.quotedNames && quoted_1.length) {
  25983. obj_1['$quoted$'] = quoted_1;
  25984. }
  25985. return recordEntry(obj_1, node);
  25986. case ts.SyntaxKind.ArrayLiteralExpression:
  25987. var arr_1 = [];
  25988. ts.forEachChild(node, function (child) {
  25989. var e_1, _a;
  25990. var value = _this.evaluateNode(child, /* preferReference */ true);
  25991. // Check for error
  25992. if (isFoldableError(value)) {
  25993. error = value;
  25994. return true; // Stop the forEachChild.
  25995. }
  25996. // Handle spread expressions
  25997. if (isMetadataSymbolicSpreadExpression(value)) {
  25998. if (Array.isArray(value.expression)) {
  25999. try {
  26000. for (var _b = __values(value.expression), _c = _b.next(); !_c.done; _c = _b.next()) {
  26001. var spreadValue = _c.value;
  26002. arr_1.push(spreadValue);
  26003. }
  26004. }
  26005. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  26006. finally {
  26007. try {
  26008. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  26009. }
  26010. finally { if (e_1) throw e_1.error; }
  26011. }
  26012. return;
  26013. }
  26014. }
  26015. arr_1.push(value);
  26016. });
  26017. if (error)
  26018. return error;
  26019. return recordEntry(arr_1, node);
  26020. case spreadElementSyntaxKind:
  26021. var spreadExpression = this.evaluateNode(node.expression);
  26022. return recordEntry({ __symbolic: 'spread', expression: spreadExpression }, node);
  26023. case ts.SyntaxKind.CallExpression:
  26024. var callExpression = node;
  26025. if (isCallOf(callExpression, 'forwardRef') &&
  26026. arrayOrEmpty(callExpression.arguments).length === 1) {
  26027. var firstArgument = callExpression.arguments[0];
  26028. if (firstArgument.kind == ts.SyntaxKind.ArrowFunction) {
  26029. var arrowFunction = firstArgument;
  26030. return recordEntry(this.evaluateNode(arrowFunction.body), node);
  26031. }
  26032. }
  26033. var args = arrayOrEmpty(callExpression.arguments).map(function (arg) { return _this.evaluateNode(arg); });
  26034. if (this.isFoldable(callExpression)) {
  26035. if (isMethodCallOf(callExpression, 'concat')) {
  26036. var arrayValue = this.evaluateNode(callExpression.expression.expression);
  26037. if (isFoldableError(arrayValue))
  26038. return arrayValue;
  26039. return arrayValue.concat(args[0]);
  26040. }
  26041. }
  26042. // Always fold a CONST_EXPR even if the argument is not foldable.
  26043. if (isCallOf(callExpression, 'CONST_EXPR') &&
  26044. arrayOrEmpty(callExpression.arguments).length === 1) {
  26045. return recordEntry(args[0], node);
  26046. }
  26047. var expression = this.evaluateNode(callExpression.expression);
  26048. if (isFoldableError(expression)) {
  26049. return recordEntry(expression, node);
  26050. }
  26051. var result = { __symbolic: 'call', expression: expression };
  26052. if (args && args.length) {
  26053. result.arguments = args;
  26054. }
  26055. return recordEntry(result, node);
  26056. case ts.SyntaxKind.NewExpression:
  26057. var newExpression = node;
  26058. var newArgs = arrayOrEmpty(newExpression.arguments).map(function (arg) { return _this.evaluateNode(arg); });
  26059. var newTarget = this.evaluateNode(newExpression.expression);
  26060. if (isMetadataError$1(newTarget)) {
  26061. return recordEntry(newTarget, node);
  26062. }
  26063. var call = { __symbolic: 'new', expression: newTarget };
  26064. if (newArgs.length) {
  26065. call.arguments = newArgs;
  26066. }
  26067. return recordEntry(call, node);
  26068. case ts.SyntaxKind.PropertyAccessExpression: {
  26069. var propertyAccessExpression = node;
  26070. var expression_1 = this.evaluateNode(propertyAccessExpression.expression);
  26071. if (isFoldableError(expression_1)) {
  26072. return recordEntry(expression_1, node);
  26073. }
  26074. var member = this.nameOf(propertyAccessExpression.name);
  26075. if (isFoldableError(member)) {
  26076. return recordEntry(member, node);
  26077. }
  26078. if (expression_1 && this.isFoldable(propertyAccessExpression.expression))
  26079. return expression_1[member];
  26080. if (isMetadataModuleReferenceExpression(expression_1)) {
  26081. // A select into a module reference and be converted into a reference to the symbol
  26082. // in the module
  26083. return recordEntry({ __symbolic: 'reference', module: expression_1.module, name: member }, node);
  26084. }
  26085. return recordEntry({ __symbolic: 'select', expression: expression_1, member: member }, node);
  26086. }
  26087. case ts.SyntaxKind.ElementAccessExpression: {
  26088. var elementAccessExpression = node;
  26089. var expression_2 = this.evaluateNode(elementAccessExpression.expression);
  26090. if (isFoldableError(expression_2)) {
  26091. return recordEntry(expression_2, node);
  26092. }
  26093. if (!elementAccessExpression.argumentExpression) {
  26094. return recordEntry(errorSymbol('Expression form not supported', node), node);
  26095. }
  26096. var index = this.evaluateNode(elementAccessExpression.argumentExpression);
  26097. if (isFoldableError(expression_2)) {
  26098. return recordEntry(expression_2, node);
  26099. }
  26100. if (this.isFoldable(elementAccessExpression.expression) &&
  26101. this.isFoldable(elementAccessExpression.argumentExpression))
  26102. return expression_2[index];
  26103. return recordEntry({ __symbolic: 'index', expression: expression_2, index: index }, node);
  26104. }
  26105. case ts.SyntaxKind.Identifier:
  26106. var identifier = node;
  26107. var name = identifier.text;
  26108. return resolveName(name, preferReference);
  26109. case ts.SyntaxKind.TypeReference:
  26110. var typeReferenceNode = node;
  26111. var typeNameNode_1 = typeReferenceNode.typeName;
  26112. var getReference = function (node) {
  26113. if (typeNameNode_1.kind === ts.SyntaxKind.QualifiedName) {
  26114. var qualifiedName = node;
  26115. var left_1 = _this.evaluateNode(qualifiedName.left);
  26116. if (isMetadataModuleReferenceExpression(left_1)) {
  26117. return recordEntry({
  26118. __symbolic: 'reference',
  26119. module: left_1.module,
  26120. name: qualifiedName.right.text
  26121. }, node);
  26122. }
  26123. // Record a type reference to a declared type as a select.
  26124. return { __symbolic: 'select', expression: left_1, member: qualifiedName.right.text };
  26125. }
  26126. else {
  26127. var identifier_1 = typeNameNode_1;
  26128. var symbol = _this.symbols.resolve(identifier_1.text);
  26129. if (isFoldableError(symbol) || isMetadataSymbolicReferenceExpression(symbol)) {
  26130. return recordEntry(symbol, node);
  26131. }
  26132. return recordEntry(errorSymbol('Could not resolve type', node, { typeName: identifier_1.text }), node);
  26133. }
  26134. };
  26135. var typeReference = getReference(typeNameNode_1);
  26136. if (isFoldableError(typeReference)) {
  26137. return recordEntry(typeReference, node);
  26138. }
  26139. if (!isMetadataModuleReferenceExpression(typeReference) &&
  26140. typeReferenceNode.typeArguments && typeReferenceNode.typeArguments.length) {
  26141. var args_1 = typeReferenceNode.typeArguments.map(function (element) { return _this.evaluateNode(element); });
  26142. // TODO: Remove typecast when upgraded to 2.0 as it will be correctly inferred.
  26143. // Some versions of 1.9 do not infer this correctly.
  26144. typeReference.arguments = args_1;
  26145. }
  26146. return recordEntry(typeReference, node);
  26147. case ts.SyntaxKind.UnionType:
  26148. var unionType_1 = node;
  26149. // Remove null and undefined from the list of unions.
  26150. var references = unionType_1.types
  26151. .filter(function (n) { return n.kind != ts.SyntaxKind.NullKeyword &&
  26152. n.kind != ts.SyntaxKind.UndefinedKeyword; })
  26153. .map(function (n) { return _this.evaluateNode(n); });
  26154. // The remmaining reference must be the same. If two have type arguments consider them
  26155. // different even if the type arguments are the same.
  26156. var candidate = null;
  26157. for (var i = 0; i < references.length; i++) {
  26158. var reference = references[i];
  26159. if (isMetadataSymbolicReferenceExpression(reference)) {
  26160. if (candidate) {
  26161. if (reference.name == candidate.name &&
  26162. reference.module == candidate.module && !reference.arguments) {
  26163. candidate = reference;
  26164. }
  26165. }
  26166. else {
  26167. candidate = reference;
  26168. }
  26169. }
  26170. else {
  26171. return reference;
  26172. }
  26173. }
  26174. if (candidate)
  26175. return candidate;
  26176. break;
  26177. case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
  26178. case ts.SyntaxKind.StringLiteral:
  26179. case ts.SyntaxKind.TemplateHead:
  26180. case ts.SyntaxKind.TemplateTail:
  26181. case ts.SyntaxKind.TemplateMiddle:
  26182. return node.text;
  26183. case ts.SyntaxKind.NumericLiteral:
  26184. return parseFloat(node.text);
  26185. case ts.SyntaxKind.AnyKeyword:
  26186. return recordEntry({ __symbolic: 'reference', name: 'any' }, node);
  26187. case ts.SyntaxKind.StringKeyword:
  26188. return recordEntry({ __symbolic: 'reference', name: 'string' }, node);
  26189. case ts.SyntaxKind.NumberKeyword:
  26190. return recordEntry({ __symbolic: 'reference', name: 'number' }, node);
  26191. case ts.SyntaxKind.BooleanKeyword:
  26192. return recordEntry({ __symbolic: 'reference', name: 'boolean' }, node);
  26193. case ts.SyntaxKind.ArrayType:
  26194. var arrayTypeNode = node;
  26195. return recordEntry({
  26196. __symbolic: 'reference',
  26197. name: 'Array',
  26198. arguments: [this.evaluateNode(arrayTypeNode.elementType)]
  26199. }, node);
  26200. case ts.SyntaxKind.NullKeyword:
  26201. return null;
  26202. case ts.SyntaxKind.TrueKeyword:
  26203. return true;
  26204. case ts.SyntaxKind.FalseKeyword:
  26205. return false;
  26206. case ts.SyntaxKind.ParenthesizedExpression:
  26207. var parenthesizedExpression = node;
  26208. return this.evaluateNode(parenthesizedExpression.expression);
  26209. case ts.SyntaxKind.TypeAssertionExpression:
  26210. var typeAssertion = node;
  26211. return this.evaluateNode(typeAssertion.expression);
  26212. case ts.SyntaxKind.PrefixUnaryExpression:
  26213. var prefixUnaryExpression = node;
  26214. var operand = this.evaluateNode(prefixUnaryExpression.operand);
  26215. if (isDefined$1(operand) && isPrimitive$1(operand)) {
  26216. switch (prefixUnaryExpression.operator) {
  26217. case ts.SyntaxKind.PlusToken:
  26218. return +operand;
  26219. case ts.SyntaxKind.MinusToken:
  26220. return -operand;
  26221. case ts.SyntaxKind.TildeToken:
  26222. return ~operand;
  26223. case ts.SyntaxKind.ExclamationToken:
  26224. return !operand;
  26225. }
  26226. }
  26227. var operatorText = void 0;
  26228. switch (prefixUnaryExpression.operator) {
  26229. case ts.SyntaxKind.PlusToken:
  26230. operatorText = '+';
  26231. break;
  26232. case ts.SyntaxKind.MinusToken:
  26233. operatorText = '-';
  26234. break;
  26235. case ts.SyntaxKind.TildeToken:
  26236. operatorText = '~';
  26237. break;
  26238. case ts.SyntaxKind.ExclamationToken:
  26239. operatorText = '!';
  26240. break;
  26241. default:
  26242. return undefined;
  26243. }
  26244. return recordEntry({ __symbolic: 'pre', operator: operatorText, operand: operand }, node);
  26245. case ts.SyntaxKind.BinaryExpression:
  26246. var binaryExpression = node;
  26247. var left = this.evaluateNode(binaryExpression.left);
  26248. var right = this.evaluateNode(binaryExpression.right);
  26249. if (isDefined$1(left) && isDefined$1(right)) {
  26250. if (isPrimitive$1(left) && isPrimitive$1(right))
  26251. switch (binaryExpression.operatorToken.kind) {
  26252. case ts.SyntaxKind.BarBarToken:
  26253. return left || right;
  26254. case ts.SyntaxKind.AmpersandAmpersandToken:
  26255. return left && right;
  26256. case ts.SyntaxKind.AmpersandToken:
  26257. return left & right;
  26258. case ts.SyntaxKind.BarToken:
  26259. return left | right;
  26260. case ts.SyntaxKind.CaretToken:
  26261. return left ^ right;
  26262. case ts.SyntaxKind.EqualsEqualsToken:
  26263. return left == right;
  26264. case ts.SyntaxKind.ExclamationEqualsToken:
  26265. return left != right;
  26266. case ts.SyntaxKind.EqualsEqualsEqualsToken:
  26267. return left === right;
  26268. case ts.SyntaxKind.ExclamationEqualsEqualsToken:
  26269. return left !== right;
  26270. case ts.SyntaxKind.LessThanToken:
  26271. return left < right;
  26272. case ts.SyntaxKind.GreaterThanToken:
  26273. return left > right;
  26274. case ts.SyntaxKind.LessThanEqualsToken:
  26275. return left <= right;
  26276. case ts.SyntaxKind.GreaterThanEqualsToken:
  26277. return left >= right;
  26278. case ts.SyntaxKind.LessThanLessThanToken:
  26279. return left << right;
  26280. case ts.SyntaxKind.GreaterThanGreaterThanToken:
  26281. return left >> right;
  26282. case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
  26283. return left >>> right;
  26284. case ts.SyntaxKind.PlusToken:
  26285. return left + right;
  26286. case ts.SyntaxKind.MinusToken:
  26287. return left - right;
  26288. case ts.SyntaxKind.AsteriskToken:
  26289. return left * right;
  26290. case ts.SyntaxKind.SlashToken:
  26291. return left / right;
  26292. case ts.SyntaxKind.PercentToken:
  26293. return left % right;
  26294. }
  26295. return recordEntry({
  26296. __symbolic: 'binop',
  26297. operator: binaryExpression.operatorToken.getText(),
  26298. left: left,
  26299. right: right
  26300. }, node);
  26301. }
  26302. break;
  26303. case ts.SyntaxKind.ConditionalExpression:
  26304. var conditionalExpression = node;
  26305. var condition = this.evaluateNode(conditionalExpression.condition);
  26306. var thenExpression = this.evaluateNode(conditionalExpression.whenTrue);
  26307. var elseExpression = this.evaluateNode(conditionalExpression.whenFalse);
  26308. if (isPrimitive$1(condition)) {
  26309. return condition ? thenExpression : elseExpression;
  26310. }
  26311. return recordEntry({ __symbolic: 'if', condition: condition, thenExpression: thenExpression, elseExpression: elseExpression }, node);
  26312. case ts.SyntaxKind.FunctionExpression:
  26313. case ts.SyntaxKind.ArrowFunction:
  26314. return recordEntry(errorSymbol('Lambda not supported', node), node);
  26315. case ts.SyntaxKind.TaggedTemplateExpression:
  26316. return recordEntry(errorSymbol('Tagged template expressions are not supported in metadata', node), node);
  26317. case ts.SyntaxKind.TemplateExpression:
  26318. var templateExpression = node;
  26319. if (this.isFoldable(node)) {
  26320. return templateExpression.templateSpans.reduce(function (previous, current) { return previous + _this.evaluateNode(current.expression) +
  26321. _this.evaluateNode(current.literal); }, this.evaluateNode(templateExpression.head));
  26322. }
  26323. else {
  26324. return templateExpression.templateSpans.reduce(function (previous, current) {
  26325. var expr = _this.evaluateNode(current.expression);
  26326. var literal = _this.evaluateNode(current.literal);
  26327. if (isFoldableError(expr))
  26328. return expr;
  26329. if (isFoldableError(literal))
  26330. return literal;
  26331. if (typeof previous === 'string' && typeof expr === 'string' &&
  26332. typeof literal === 'string') {
  26333. return previous + expr + literal;
  26334. }
  26335. var result = expr;
  26336. if (previous !== '') {
  26337. result = { __symbolic: 'binop', operator: '+', left: previous, right: expr };
  26338. }
  26339. if (literal != '') {
  26340. result = { __symbolic: 'binop', operator: '+', left: result, right: literal };
  26341. }
  26342. return result;
  26343. }, this.evaluateNode(templateExpression.head));
  26344. }
  26345. case ts.SyntaxKind.AsExpression:
  26346. var asExpression = node;
  26347. return this.evaluateNode(asExpression.expression);
  26348. case ts.SyntaxKind.ClassExpression:
  26349. return { __symbolic: 'class' };
  26350. }
  26351. return recordEntry(errorSymbol('Expression form not supported', node), node);
  26352. };
  26353. return Evaluator;
  26354. }());
  26355. function isPropertyAssignment(node) {
  26356. return node.kind == ts.SyntaxKind.PropertyAssignment;
  26357. }
  26358. var empty = ts.createNodeArray();
  26359. function arrayOrEmpty(v) {
  26360. return v || empty;
  26361. }
  26362. /**
  26363. * @license
  26364. * Copyright Google Inc. All Rights Reserved.
  26365. *
  26366. * Use of this source code is governed by an MIT-style license that can be
  26367. * found in the LICENSE file at https://angular.io/license
  26368. */
  26369. var Symbols = /** @class */ (function () {
  26370. function Symbols(sourceFile) {
  26371. this.sourceFile = sourceFile;
  26372. this.references = new Map();
  26373. }
  26374. Symbols.prototype.resolve = function (name, preferReference) {
  26375. return (preferReference && this.references.get(name)) || this.symbols.get(name);
  26376. };
  26377. Symbols.prototype.define = function (name, value) { this.symbols.set(name, value); };
  26378. Symbols.prototype.defineReference = function (name, value) {
  26379. this.references.set(name, value);
  26380. };
  26381. Symbols.prototype.has = function (name) { return this.symbols.has(name); };
  26382. Object.defineProperty(Symbols.prototype, "symbols", {
  26383. get: function () {
  26384. var result = this._symbols;
  26385. if (!result) {
  26386. result = this._symbols = new Map();
  26387. populateBuiltins(result);
  26388. this.buildImports();
  26389. }
  26390. return result;
  26391. },
  26392. enumerable: true,
  26393. configurable: true
  26394. });
  26395. Symbols.prototype.buildImports = function () {
  26396. var _this = this;
  26397. var symbols = this._symbols;
  26398. // Collect the imported symbols into this.symbols
  26399. var stripQuotes = function (s) { return s.replace(/^['"]|['"]$/g, ''); };
  26400. var visit = function (node) {
  26401. var e_1, _a;
  26402. switch (node.kind) {
  26403. case ts.SyntaxKind.ImportEqualsDeclaration:
  26404. var importEqualsDeclaration = node;
  26405. if (importEqualsDeclaration.moduleReference.kind ===
  26406. ts.SyntaxKind.ExternalModuleReference) {
  26407. var externalReference = importEqualsDeclaration.moduleReference;
  26408. if (externalReference.expression) {
  26409. // An `import <identifier> = require(<module-specifier>);
  26410. if (!externalReference.expression.parent) {
  26411. // The `parent` field of a node is set by the TypeScript binder (run as
  26412. // part of the type checker). Setting it here allows us to call `getText()`
  26413. // even if the `SourceFile` was not type checked (which looks for `SourceFile`
  26414. // in the parent chain). This doesn't damage the node as the binder unconditionally
  26415. // sets the parent.
  26416. externalReference.expression.parent = externalReference;
  26417. externalReference.parent = _this.sourceFile;
  26418. }
  26419. var from_1 = stripQuotes(externalReference.expression.getText());
  26420. symbols.set(importEqualsDeclaration.name.text, { __symbolic: 'reference', module: from_1 });
  26421. break;
  26422. }
  26423. }
  26424. symbols.set(importEqualsDeclaration.name.text, { __symbolic: 'error', message: "Unsupported import syntax" });
  26425. break;
  26426. case ts.SyntaxKind.ImportDeclaration:
  26427. var importDecl = node;
  26428. if (!importDecl.importClause) {
  26429. // An `import <module-specifier>` clause which does not bring symbols into scope.
  26430. break;
  26431. }
  26432. if (!importDecl.moduleSpecifier.parent) {
  26433. // See note above in the `ImportEqualDeclaration` case.
  26434. importDecl.moduleSpecifier.parent = importDecl;
  26435. importDecl.parent = _this.sourceFile;
  26436. }
  26437. var from = stripQuotes(importDecl.moduleSpecifier.getText());
  26438. if (importDecl.importClause.name) {
  26439. // An `import <identifier> form <module-specifier>` clause. Record the default symbol.
  26440. symbols.set(importDecl.importClause.name.text, { __symbolic: 'reference', module: from, default: true });
  26441. }
  26442. var bindings = importDecl.importClause.namedBindings;
  26443. if (bindings) {
  26444. switch (bindings.kind) {
  26445. case ts.SyntaxKind.NamedImports:
  26446. try {
  26447. // An `import { [<identifier> [, <identifier>] } from <module-specifier>` clause
  26448. for (var _b = __values(bindings.elements), _c = _b.next(); !_c.done; _c = _b.next()) {
  26449. var binding = _c.value;
  26450. symbols.set(binding.name.text, {
  26451. __symbolic: 'reference',
  26452. module: from,
  26453. name: binding.propertyName ? binding.propertyName.text : binding.name.text
  26454. });
  26455. }
  26456. }
  26457. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  26458. finally {
  26459. try {
  26460. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  26461. }
  26462. finally { if (e_1) throw e_1.error; }
  26463. }
  26464. break;
  26465. case ts.SyntaxKind.NamespaceImport:
  26466. // An `input * as <identifier> from <module-specifier>` clause.
  26467. symbols.set(bindings.name.text, { __symbolic: 'reference', module: from });
  26468. break;
  26469. }
  26470. }
  26471. break;
  26472. }
  26473. ts.forEachChild(node, visit);
  26474. };
  26475. if (this.sourceFile) {
  26476. ts.forEachChild(this.sourceFile, visit);
  26477. }
  26478. };
  26479. return Symbols;
  26480. }());
  26481. function populateBuiltins(symbols) {
  26482. // From lib.core.d.ts (all "define const")
  26483. ['Object', 'Function', 'String', 'Number', 'Array', 'Boolean', 'Map', 'NaN', 'Infinity', 'Math',
  26484. 'Date', 'RegExp', 'Error', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError',
  26485. 'TypeError', 'URIError', 'JSON', 'ArrayBuffer', 'DataView', 'Int8Array', 'Uint8Array',
  26486. 'Uint8ClampedArray', 'Uint16Array', 'Int16Array', 'Int32Array', 'Uint32Array', 'Float32Array',
  26487. 'Float64Array']
  26488. .forEach(function (name) { return symbols.set(name, { __symbolic: 'reference', name: name }); });
  26489. }
  26490. /**
  26491. * @license
  26492. * Copyright Google Inc. All Rights Reserved.
  26493. *
  26494. * Use of this source code is governed by an MIT-style license that can be
  26495. * found in the LICENSE file at https://angular.io/license
  26496. */
  26497. var isStatic = function (node) {
  26498. return ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Static;
  26499. };
  26500. /**
  26501. * Collect decorator metadata from a TypeScript module.
  26502. */
  26503. var MetadataCollector = /** @class */ (function () {
  26504. function MetadataCollector(options) {
  26505. if (options === void 0) { options = {}; }
  26506. this.options = options;
  26507. }
  26508. /**
  26509. * Returns a JSON.stringify friendly form describing the decorators of the exported classes from
  26510. * the source file that is expected to correspond to a module.
  26511. */
  26512. MetadataCollector.prototype.getMetadata = function (sourceFile, strict, substituteExpression) {
  26513. var _this = this;
  26514. if (strict === void 0) { strict = false; }
  26515. var locals = new Symbols(sourceFile);
  26516. var nodeMap = new Map();
  26517. var composedSubstituter = substituteExpression && this.options.substituteExpression ?
  26518. function (value, node) {
  26519. return _this.options.substituteExpression(substituteExpression(value, node), node);
  26520. } :
  26521. substituteExpression;
  26522. var evaluatorOptions = substituteExpression ? __assign({}, this.options, { substituteExpression: composedSubstituter }) :
  26523. this.options;
  26524. var metadata;
  26525. var evaluator = new Evaluator(locals, nodeMap, evaluatorOptions, function (name, value) {
  26526. if (!metadata)
  26527. metadata = {};
  26528. metadata[name] = value;
  26529. });
  26530. var exports = undefined;
  26531. function objFromDecorator(decoratorNode) {
  26532. return evaluator.evaluateNode(decoratorNode.expression);
  26533. }
  26534. function recordEntry(entry, node) {
  26535. if (composedSubstituter) {
  26536. entry = composedSubstituter(entry, node);
  26537. }
  26538. return recordMapEntry(entry, node, nodeMap, sourceFile);
  26539. }
  26540. function errorSym(message, node, context) {
  26541. return errorSymbol(message, node, context, sourceFile);
  26542. }
  26543. function maybeGetSimpleFunction(functionDeclaration) {
  26544. if (functionDeclaration.name && functionDeclaration.name.kind == ts.SyntaxKind.Identifier) {
  26545. var nameNode = functionDeclaration.name;
  26546. var functionName = nameNode.text;
  26547. var functionBody = functionDeclaration.body;
  26548. if (functionBody && functionBody.statements.length == 1) {
  26549. var statement = functionBody.statements[0];
  26550. if (statement.kind === ts.SyntaxKind.ReturnStatement) {
  26551. var returnStatement = statement;
  26552. if (returnStatement.expression) {
  26553. var func = {
  26554. __symbolic: 'function',
  26555. parameters: namesOf(functionDeclaration.parameters),
  26556. value: evaluator.evaluateNode(returnStatement.expression)
  26557. };
  26558. if (functionDeclaration.parameters.some(function (p) { return p.initializer != null; })) {
  26559. func.defaults = functionDeclaration.parameters.map(function (p) { return p.initializer && evaluator.evaluateNode(p.initializer); });
  26560. }
  26561. return recordEntry({ func: func, name: functionName }, functionDeclaration);
  26562. }
  26563. }
  26564. }
  26565. }
  26566. }
  26567. function classMetadataOf(classDeclaration) {
  26568. var e_1, _a, e_2, _b;
  26569. var result = { __symbolic: 'class' };
  26570. function getDecorators(decorators) {
  26571. if (decorators && decorators.length)
  26572. return decorators.map(function (decorator) { return objFromDecorator(decorator); });
  26573. return undefined;
  26574. }
  26575. function referenceFrom(node) {
  26576. var result = evaluator.evaluateNode(node);
  26577. if (isMetadataError$1(result) || isMetadataSymbolicReferenceExpression(result) ||
  26578. isMetadataSymbolicSelectExpression(result)) {
  26579. return result;
  26580. }
  26581. else {
  26582. return errorSym('Symbol reference expected', node);
  26583. }
  26584. }
  26585. // Add class parents
  26586. if (classDeclaration.heritageClauses) {
  26587. classDeclaration.heritageClauses.forEach(function (hc) {
  26588. if (hc.token === ts.SyntaxKind.ExtendsKeyword && hc.types) {
  26589. hc.types.forEach(function (type) { return result.extends = referenceFrom(type.expression); });
  26590. }
  26591. });
  26592. }
  26593. // Add arity if the type is generic
  26594. var typeParameters = classDeclaration.typeParameters;
  26595. if (typeParameters && typeParameters.length) {
  26596. result.arity = typeParameters.length;
  26597. }
  26598. // Add class decorators
  26599. if (classDeclaration.decorators) {
  26600. result.decorators = getDecorators(classDeclaration.decorators);
  26601. }
  26602. // member decorators
  26603. var members = null;
  26604. function recordMember(name, metadata) {
  26605. if (!members)
  26606. members = {};
  26607. var data = members.hasOwnProperty(name) ? members[name] : [];
  26608. data.push(metadata);
  26609. members[name] = data;
  26610. }
  26611. // static member
  26612. var statics = null;
  26613. function recordStaticMember(name, value) {
  26614. if (!statics)
  26615. statics = {};
  26616. statics[name] = value;
  26617. }
  26618. try {
  26619. for (var _c = __values(classDeclaration.members), _d = _c.next(); !_d.done; _d = _c.next()) {
  26620. var member = _d.value;
  26621. var isConstructor = false;
  26622. switch (member.kind) {
  26623. case ts.SyntaxKind.Constructor:
  26624. case ts.SyntaxKind.MethodDeclaration:
  26625. isConstructor = member.kind === ts.SyntaxKind.Constructor;
  26626. var method = member;
  26627. if (isStatic(method)) {
  26628. var maybeFunc = maybeGetSimpleFunction(method);
  26629. if (maybeFunc) {
  26630. recordStaticMember(maybeFunc.name, maybeFunc.func);
  26631. }
  26632. continue;
  26633. }
  26634. var methodDecorators = getDecorators(method.decorators);
  26635. var parameters = method.parameters;
  26636. var parameterDecoratorData = [];
  26637. var parametersData = [];
  26638. var hasDecoratorData = false;
  26639. var hasParameterData = false;
  26640. try {
  26641. for (var parameters_1 = __values(parameters), parameters_1_1 = parameters_1.next(); !parameters_1_1.done; parameters_1_1 = parameters_1.next()) {
  26642. var parameter = parameters_1_1.value;
  26643. var parameterData = getDecorators(parameter.decorators);
  26644. parameterDecoratorData.push(parameterData);
  26645. hasDecoratorData = hasDecoratorData || !!parameterData;
  26646. if (isConstructor) {
  26647. if (parameter.type) {
  26648. parametersData.push(referenceFrom(parameter.type));
  26649. }
  26650. else {
  26651. parametersData.push(null);
  26652. }
  26653. hasParameterData = true;
  26654. }
  26655. }
  26656. }
  26657. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  26658. finally {
  26659. try {
  26660. if (parameters_1_1 && !parameters_1_1.done && (_b = parameters_1.return)) _b.call(parameters_1);
  26661. }
  26662. finally { if (e_2) throw e_2.error; }
  26663. }
  26664. var data = { __symbolic: isConstructor ? 'constructor' : 'method' };
  26665. var name = isConstructor ? '__ctor__' : evaluator.nameOf(member.name);
  26666. if (methodDecorators) {
  26667. data.decorators = methodDecorators;
  26668. }
  26669. if (hasDecoratorData) {
  26670. data.parameterDecorators = parameterDecoratorData;
  26671. }
  26672. if (hasParameterData) {
  26673. data.parameters = parametersData;
  26674. }
  26675. if (!isMetadataError$1(name)) {
  26676. recordMember(name, data);
  26677. }
  26678. break;
  26679. case ts.SyntaxKind.PropertyDeclaration:
  26680. case ts.SyntaxKind.GetAccessor:
  26681. case ts.SyntaxKind.SetAccessor:
  26682. var property = member;
  26683. if (isStatic(property)) {
  26684. var name_1 = evaluator.nameOf(property.name);
  26685. if (!isMetadataError$1(name_1)) {
  26686. if (property.initializer) {
  26687. var value = evaluator.evaluateNode(property.initializer);
  26688. recordStaticMember(name_1, value);
  26689. }
  26690. else {
  26691. recordStaticMember(name_1, errorSym('Variable not initialized', property.name));
  26692. }
  26693. }
  26694. }
  26695. var propertyDecorators = getDecorators(property.decorators);
  26696. if (propertyDecorators) {
  26697. var name_2 = evaluator.nameOf(property.name);
  26698. if (!isMetadataError$1(name_2)) {
  26699. recordMember(name_2, { __symbolic: 'property', decorators: propertyDecorators });
  26700. }
  26701. }
  26702. break;
  26703. }
  26704. }
  26705. }
  26706. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  26707. finally {
  26708. try {
  26709. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  26710. }
  26711. finally { if (e_1) throw e_1.error; }
  26712. }
  26713. if (members) {
  26714. result.members = members;
  26715. }
  26716. if (statics) {
  26717. result.statics = statics;
  26718. }
  26719. return recordEntry(result, classDeclaration);
  26720. }
  26721. // Collect all exported symbols from an exports clause.
  26722. var exportMap = new Map();
  26723. ts.forEachChild(sourceFile, function (node) {
  26724. switch (node.kind) {
  26725. case ts.SyntaxKind.ExportDeclaration:
  26726. var exportDeclaration = node;
  26727. var moduleSpecifier = exportDeclaration.moduleSpecifier, exportClause = exportDeclaration.exportClause;
  26728. if (!moduleSpecifier) {
  26729. // If there is a module specifier there is also an exportClause
  26730. exportClause.elements.forEach(function (spec) {
  26731. var exportedAs = spec.name.text;
  26732. var name = (spec.propertyName || spec.name).text;
  26733. exportMap.set(name, exportedAs);
  26734. });
  26735. }
  26736. }
  26737. });
  26738. var isExport = function (node) { return sourceFile.isDeclarationFile ||
  26739. ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export; };
  26740. var isExportedIdentifier = function (identifier) {
  26741. return identifier && exportMap.has(identifier.text);
  26742. };
  26743. var isExported = function (node) {
  26744. return isExport(node) || isExportedIdentifier(node.name);
  26745. };
  26746. var exportedIdentifierName = function (identifier) {
  26747. return identifier && (exportMap.get(identifier.text) || identifier.text);
  26748. };
  26749. var exportedName = function (node) { return exportedIdentifierName(node.name); };
  26750. // Pre-declare classes and functions
  26751. ts.forEachChild(sourceFile, function (node) {
  26752. switch (node.kind) {
  26753. case ts.SyntaxKind.ClassDeclaration:
  26754. var classDeclaration = node;
  26755. if (classDeclaration.name) {
  26756. var className = classDeclaration.name.text;
  26757. if (isExported(classDeclaration)) {
  26758. locals.define(className, { __symbolic: 'reference', name: exportedName(classDeclaration) });
  26759. }
  26760. else {
  26761. locals.define(className, errorSym('Reference to non-exported class', node, { className: className }));
  26762. }
  26763. }
  26764. break;
  26765. case ts.SyntaxKind.InterfaceDeclaration:
  26766. var interfaceDeclaration = node;
  26767. if (interfaceDeclaration.name) {
  26768. var interfaceName = interfaceDeclaration.name.text;
  26769. // All references to interfaces should be converted to references to `any`.
  26770. locals.define(interfaceName, { __symbolic: 'reference', name: 'any' });
  26771. }
  26772. break;
  26773. case ts.SyntaxKind.FunctionDeclaration:
  26774. var functionDeclaration = node;
  26775. if (!isExported(functionDeclaration)) {
  26776. // Report references to this function as an error.
  26777. var nameNode = functionDeclaration.name;
  26778. if (nameNode && nameNode.text) {
  26779. locals.define(nameNode.text, errorSym('Reference to a non-exported function', nameNode, { name: nameNode.text }));
  26780. }
  26781. }
  26782. break;
  26783. }
  26784. });
  26785. ts.forEachChild(sourceFile, function (node) {
  26786. var e_3, _a, e_4, _b;
  26787. switch (node.kind) {
  26788. case ts.SyntaxKind.ExportDeclaration:
  26789. // Record export declarations
  26790. var exportDeclaration = node;
  26791. var moduleSpecifier = exportDeclaration.moduleSpecifier, exportClause = exportDeclaration.exportClause;
  26792. if (!moduleSpecifier) {
  26793. // no module specifier -> export {propName as name};
  26794. if (exportClause) {
  26795. exportClause.elements.forEach(function (spec) {
  26796. var name = spec.name.text;
  26797. // If the symbol was not already exported, export a reference since it is a
  26798. // reference to an import
  26799. if (!metadata || !metadata[name]) {
  26800. var propNode = spec.propertyName || spec.name;
  26801. var value = evaluator.evaluateNode(propNode);
  26802. if (!metadata)
  26803. metadata = {};
  26804. metadata[name] = recordEntry(value, node);
  26805. }
  26806. });
  26807. }
  26808. }
  26809. if (moduleSpecifier && moduleSpecifier.kind == ts.SyntaxKind.StringLiteral) {
  26810. // Ignore exports that don't have string literals as exports.
  26811. // This is allowed by the syntax but will be flagged as an error by the type checker.
  26812. var from = moduleSpecifier.text;
  26813. var moduleExport = { from: from };
  26814. if (exportClause) {
  26815. moduleExport.export = exportClause.elements.map(function (spec) { return spec.propertyName ? { name: spec.propertyName.text, as: spec.name.text } :
  26816. spec.name.text; });
  26817. }
  26818. if (!exports)
  26819. exports = [];
  26820. exports.push(moduleExport);
  26821. }
  26822. break;
  26823. case ts.SyntaxKind.ClassDeclaration:
  26824. var classDeclaration = node;
  26825. if (classDeclaration.name) {
  26826. if (isExported(classDeclaration)) {
  26827. var name = exportedName(classDeclaration);
  26828. if (name) {
  26829. if (!metadata)
  26830. metadata = {};
  26831. metadata[name] = classMetadataOf(classDeclaration);
  26832. }
  26833. }
  26834. }
  26835. // Otherwise don't record metadata for the class.
  26836. break;
  26837. case ts.SyntaxKind.TypeAliasDeclaration:
  26838. var typeDeclaration = node;
  26839. if (typeDeclaration.name && isExported(typeDeclaration)) {
  26840. var name = exportedName(typeDeclaration);
  26841. if (name) {
  26842. if (!metadata)
  26843. metadata = {};
  26844. metadata[name] = { __symbolic: 'interface' };
  26845. }
  26846. }
  26847. break;
  26848. case ts.SyntaxKind.InterfaceDeclaration:
  26849. var interfaceDeclaration = node;
  26850. if (interfaceDeclaration.name && isExported(interfaceDeclaration)) {
  26851. var name = exportedName(interfaceDeclaration);
  26852. if (name) {
  26853. if (!metadata)
  26854. metadata = {};
  26855. metadata[name] = { __symbolic: 'interface' };
  26856. }
  26857. }
  26858. break;
  26859. case ts.SyntaxKind.FunctionDeclaration:
  26860. // Record functions that return a single value. Record the parameter
  26861. // names substitution will be performed by the StaticReflector.
  26862. var functionDeclaration = node;
  26863. if (isExported(functionDeclaration) && functionDeclaration.name) {
  26864. var name = exportedName(functionDeclaration);
  26865. var maybeFunc = maybeGetSimpleFunction(functionDeclaration);
  26866. if (name) {
  26867. if (!metadata)
  26868. metadata = {};
  26869. // TODO(alxhub): The literal here is not valid FunctionMetadata.
  26870. metadata[name] = maybeFunc ? recordEntry(maybeFunc.func, node) :
  26871. { __symbolic: 'function' };
  26872. }
  26873. }
  26874. break;
  26875. case ts.SyntaxKind.EnumDeclaration:
  26876. var enumDeclaration = node;
  26877. if (isExported(enumDeclaration)) {
  26878. var enumValueHolder = {};
  26879. var enumName = exportedName(enumDeclaration);
  26880. var nextDefaultValue = 0;
  26881. var writtenMembers = 0;
  26882. try {
  26883. for (var _c = __values(enumDeclaration.members), _d = _c.next(); !_d.done; _d = _c.next()) {
  26884. var member = _d.value;
  26885. var enumValue = void 0;
  26886. if (!member.initializer) {
  26887. enumValue = nextDefaultValue;
  26888. }
  26889. else {
  26890. enumValue = evaluator.evaluateNode(member.initializer);
  26891. }
  26892. var name = undefined;
  26893. if (member.name.kind == ts.SyntaxKind.Identifier) {
  26894. var identifier = member.name;
  26895. name = identifier.text;
  26896. enumValueHolder[name] = enumValue;
  26897. writtenMembers++;
  26898. }
  26899. if (typeof enumValue === 'number') {
  26900. nextDefaultValue = enumValue + 1;
  26901. }
  26902. else if (name) {
  26903. // TODO(alxhub): 'left' here has a name propery which is not valid for
  26904. // MetadataSymbolicSelectExpression.
  26905. nextDefaultValue = {
  26906. __symbolic: 'binary',
  26907. operator: '+',
  26908. left: {
  26909. __symbolic: 'select',
  26910. expression: recordEntry({ __symbolic: 'reference', name: enumName }, node), name: name
  26911. },
  26912. };
  26913. }
  26914. else {
  26915. nextDefaultValue =
  26916. recordEntry(errorSym('Unsupported enum member name', member.name), node);
  26917. }
  26918. }
  26919. }
  26920. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  26921. finally {
  26922. try {
  26923. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  26924. }
  26925. finally { if (e_3) throw e_3.error; }
  26926. }
  26927. if (writtenMembers) {
  26928. if (enumName) {
  26929. if (!metadata)
  26930. metadata = {};
  26931. metadata[enumName] = recordEntry(enumValueHolder, node);
  26932. }
  26933. }
  26934. }
  26935. break;
  26936. case ts.SyntaxKind.VariableStatement:
  26937. var variableStatement = node;
  26938. var _loop_1 = function (variableDeclaration) {
  26939. if (variableDeclaration.name.kind == ts.SyntaxKind.Identifier) {
  26940. var nameNode = variableDeclaration.name;
  26941. var varValue = void 0;
  26942. if (variableDeclaration.initializer) {
  26943. varValue = evaluator.evaluateNode(variableDeclaration.initializer);
  26944. }
  26945. else {
  26946. varValue = recordEntry(errorSym('Variable not initialized', nameNode), nameNode);
  26947. }
  26948. var exported = false;
  26949. if (isExport(variableStatement) || isExport(variableDeclaration) ||
  26950. isExportedIdentifier(nameNode)) {
  26951. var name = exportedIdentifierName(nameNode);
  26952. if (name) {
  26953. if (!metadata)
  26954. metadata = {};
  26955. metadata[name] = recordEntry(varValue, node);
  26956. }
  26957. exported = true;
  26958. }
  26959. if (typeof varValue == 'string' || typeof varValue == 'number' ||
  26960. typeof varValue == 'boolean') {
  26961. locals.define(nameNode.text, varValue);
  26962. if (exported) {
  26963. locals.defineReference(nameNode.text, { __symbolic: 'reference', name: nameNode.text });
  26964. }
  26965. }
  26966. else if (!exported) {
  26967. if (varValue && !isMetadataError$1(varValue)) {
  26968. locals.define(nameNode.text, recordEntry(varValue, node));
  26969. }
  26970. else {
  26971. locals.define(nameNode.text, recordEntry(errorSym('Reference to a local symbol', nameNode, { name: nameNode.text }), node));
  26972. }
  26973. }
  26974. }
  26975. else {
  26976. // Destructuring (or binding) declarations are not supported,
  26977. // var {<identifier>[, <identifier>]+} = <expression>;
  26978. // or
  26979. // var [<identifier>[, <identifier}+] = <expression>;
  26980. // are not supported.
  26981. var report_1 = function (nameNode) {
  26982. switch (nameNode.kind) {
  26983. case ts.SyntaxKind.Identifier:
  26984. var name = nameNode;
  26985. var varValue = errorSym('Destructuring not supported', name);
  26986. locals.define(name.text, varValue);
  26987. if (isExport(node)) {
  26988. if (!metadata)
  26989. metadata = {};
  26990. metadata[name.text] = varValue;
  26991. }
  26992. break;
  26993. case ts.SyntaxKind.BindingElement:
  26994. var bindingElement = nameNode;
  26995. report_1(bindingElement.name);
  26996. break;
  26997. case ts.SyntaxKind.ObjectBindingPattern:
  26998. case ts.SyntaxKind.ArrayBindingPattern:
  26999. var bindings = nameNode;
  27000. bindings.elements.forEach(report_1);
  27001. break;
  27002. }
  27003. };
  27004. report_1(variableDeclaration.name);
  27005. }
  27006. };
  27007. try {
  27008. for (var _e = __values(variableStatement.declarationList.declarations), _f = _e.next(); !_f.done; _f = _e.next()) {
  27009. var variableDeclaration = _f.value;
  27010. _loop_1(variableDeclaration);
  27011. }
  27012. }
  27013. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  27014. finally {
  27015. try {
  27016. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  27017. }
  27018. finally { if (e_4) throw e_4.error; }
  27019. }
  27020. break;
  27021. }
  27022. });
  27023. if (metadata || exports) {
  27024. if (!metadata)
  27025. metadata = {};
  27026. else if (strict) {
  27027. validateMetadata(sourceFile, nodeMap, metadata);
  27028. }
  27029. var result = {
  27030. __symbolic: 'module',
  27031. version: this.options.version || METADATA_VERSION, metadata: metadata
  27032. };
  27033. if (sourceFile.moduleName)
  27034. result.importAs = sourceFile.moduleName;
  27035. if (exports)
  27036. result.exports = exports;
  27037. return result;
  27038. }
  27039. };
  27040. return MetadataCollector;
  27041. }());
  27042. // This will throw if the metadata entry given contains an error node.
  27043. function validateMetadata(sourceFile, nodeMap, metadata) {
  27044. var locals = new Set(['Array', 'Object', 'Set', 'Map', 'string', 'number', 'any']);
  27045. function validateExpression(expression) {
  27046. if (!expression) {
  27047. return;
  27048. }
  27049. else if (Array.isArray(expression)) {
  27050. expression.forEach(validateExpression);
  27051. }
  27052. else if (typeof expression === 'object' && !expression.hasOwnProperty('__symbolic')) {
  27053. Object.getOwnPropertyNames(expression).forEach(function (v) { return validateExpression(expression[v]); });
  27054. }
  27055. else if (isMetadataError$1(expression)) {
  27056. reportError(expression);
  27057. }
  27058. else if (isMetadataGlobalReferenceExpression(expression)) {
  27059. if (!locals.has(expression.name)) {
  27060. var reference = metadata[expression.name];
  27061. if (reference) {
  27062. validateExpression(reference);
  27063. }
  27064. }
  27065. }
  27066. else if (isFunctionMetadata(expression)) {
  27067. validateFunction(expression);
  27068. }
  27069. else if (isMetadataSymbolicExpression(expression)) {
  27070. switch (expression.__symbolic) {
  27071. case 'binary':
  27072. var binaryExpression = expression;
  27073. validateExpression(binaryExpression.left);
  27074. validateExpression(binaryExpression.right);
  27075. break;
  27076. case 'call':
  27077. case 'new':
  27078. var callExpression = expression;
  27079. validateExpression(callExpression.expression);
  27080. if (callExpression.arguments)
  27081. callExpression.arguments.forEach(validateExpression);
  27082. break;
  27083. case 'index':
  27084. var indexExpression = expression;
  27085. validateExpression(indexExpression.expression);
  27086. validateExpression(indexExpression.index);
  27087. break;
  27088. case 'pre':
  27089. var prefixExpression = expression;
  27090. validateExpression(prefixExpression.operand);
  27091. break;
  27092. case 'select':
  27093. var selectExpression = expression;
  27094. validateExpression(selectExpression.expression);
  27095. break;
  27096. case 'spread':
  27097. var spreadExpression = expression;
  27098. validateExpression(spreadExpression.expression);
  27099. break;
  27100. case 'if':
  27101. var ifExpression = expression;
  27102. validateExpression(ifExpression.condition);
  27103. validateExpression(ifExpression.elseExpression);
  27104. validateExpression(ifExpression.thenExpression);
  27105. break;
  27106. }
  27107. }
  27108. }
  27109. function validateMember(classData, member) {
  27110. if (member.decorators) {
  27111. member.decorators.forEach(validateExpression);
  27112. }
  27113. if (isMethodMetadata(member) && member.parameterDecorators) {
  27114. member.parameterDecorators.forEach(validateExpression);
  27115. }
  27116. // Only validate parameters of classes for which we know that are used with our DI
  27117. if (classData.decorators && isConstructorMetadata(member) && member.parameters) {
  27118. member.parameters.forEach(validateExpression);
  27119. }
  27120. }
  27121. function validateClass(classData) {
  27122. if (classData.decorators) {
  27123. classData.decorators.forEach(validateExpression);
  27124. }
  27125. if (classData.members) {
  27126. Object.getOwnPropertyNames(classData.members)
  27127. .forEach(function (name) { return classData.members[name].forEach(function (m) { return validateMember(classData, m); }); });
  27128. }
  27129. if (classData.statics) {
  27130. Object.getOwnPropertyNames(classData.statics).forEach(function (name) {
  27131. var staticMember = classData.statics[name];
  27132. if (isFunctionMetadata(staticMember)) {
  27133. validateExpression(staticMember.value);
  27134. }
  27135. else {
  27136. validateExpression(staticMember);
  27137. }
  27138. });
  27139. }
  27140. }
  27141. function validateFunction(functionDeclaration) {
  27142. if (functionDeclaration.value) {
  27143. var oldLocals = locals;
  27144. if (functionDeclaration.parameters) {
  27145. locals = new Set(oldLocals.values());
  27146. if (functionDeclaration.parameters)
  27147. functionDeclaration.parameters.forEach(function (n) { return locals.add(n); });
  27148. }
  27149. validateExpression(functionDeclaration.value);
  27150. locals = oldLocals;
  27151. }
  27152. }
  27153. function shouldReportNode(node) {
  27154. if (node) {
  27155. var nodeStart = node.getStart();
  27156. return !(node.pos != nodeStart &&
  27157. sourceFile.text.substring(node.pos, nodeStart).indexOf('@dynamic') >= 0);
  27158. }
  27159. return true;
  27160. }
  27161. function reportError(error) {
  27162. var node = nodeMap.get(error);
  27163. if (shouldReportNode(node)) {
  27164. var lineInfo = error.line != undefined ?
  27165. error.character != undefined ? ":" + (error.line + 1) + ":" + (error.character + 1) :
  27166. ":" + (error.line + 1) :
  27167. '';
  27168. throw new Error("" + sourceFile.fileName + lineInfo + ": Metadata collected contains an error that will be reported at runtime: " + expandedMessage$1(error) + ".\n " + JSON.stringify(error));
  27169. }
  27170. }
  27171. Object.getOwnPropertyNames(metadata).forEach(function (name) {
  27172. var entry = metadata[name];
  27173. try {
  27174. if (isClassMetadata(entry)) {
  27175. validateClass(entry);
  27176. }
  27177. }
  27178. catch (e) {
  27179. var node = nodeMap.get(entry);
  27180. if (shouldReportNode(node)) {
  27181. if (node) {
  27182. var _a = sourceFile.getLineAndCharacterOfPosition(node.getStart()), line = _a.line, character = _a.character;
  27183. throw new Error(sourceFile.fileName + ":" + (line + 1) + ":" + (character + 1) + ": Error encountered in metadata generated for exported symbol '" + name + "': \n " + e.message);
  27184. }
  27185. throw new Error("Error encountered in metadata generated for exported symbol " + name + ": \n " + e.message);
  27186. }
  27187. }
  27188. });
  27189. }
  27190. // Collect parameter names from a function.
  27191. function namesOf(parameters) {
  27192. var e_5, _a;
  27193. var result = [];
  27194. function addNamesOf(name) {
  27195. var e_6, _a;
  27196. if (name.kind == ts.SyntaxKind.Identifier) {
  27197. var identifier = name;
  27198. result.push(identifier.text);
  27199. }
  27200. else {
  27201. var bindingPattern = name;
  27202. try {
  27203. for (var _b = __values(bindingPattern.elements), _c = _b.next(); !_c.done; _c = _b.next()) {
  27204. var element = _c.value;
  27205. var name_3 = element.name;
  27206. if (name_3) {
  27207. addNamesOf(name_3);
  27208. }
  27209. }
  27210. }
  27211. catch (e_6_1) { e_6 = { error: e_6_1 }; }
  27212. finally {
  27213. try {
  27214. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  27215. }
  27216. finally { if (e_6) throw e_6.error; }
  27217. }
  27218. }
  27219. }
  27220. try {
  27221. for (var parameters_2 = __values(parameters), parameters_2_1 = parameters_2.next(); !parameters_2_1.done; parameters_2_1 = parameters_2.next()) {
  27222. var parameter = parameters_2_1.value;
  27223. addNamesOf(parameter.name);
  27224. }
  27225. }
  27226. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  27227. finally {
  27228. try {
  27229. if (parameters_2_1 && !parameters_2_1.done && (_a = parameters_2.return)) _a.call(parameters_2);
  27230. }
  27231. finally { if (e_5) throw e_5.error; }
  27232. }
  27233. return result;
  27234. }
  27235. function expandedMessage$1(error) {
  27236. switch (error.message) {
  27237. case 'Reference to non-exported class':
  27238. if (error.context && error.context.className) {
  27239. return "Reference to a non-exported class " + error.context.className + ". Consider exporting the class";
  27240. }
  27241. break;
  27242. case 'Variable not initialized':
  27243. return 'Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler';
  27244. case 'Destructuring not supported':
  27245. return 'Referencing an exported destructured variable or constant is not supported by the template compiler. Consider simplifying this to avoid destructuring';
  27246. case 'Could not resolve type':
  27247. if (error.context && error.context.typeName) {
  27248. return "Could not resolve type " + error.context.typeName;
  27249. }
  27250. break;
  27251. case 'Function call not supported':
  27252. var prefix = error.context && error.context.name ? "Calling function '" + error.context.name + "', f" : 'F';
  27253. return prefix +
  27254. 'unction calls are not supported. Consider replacing the function or lambda with a reference to an exported function';
  27255. case 'Reference to a local symbol':
  27256. if (error.context && error.context.name) {
  27257. return "Reference to a local (non-exported) symbol '" + error.context.name + "'. Consider exporting the symbol";
  27258. }
  27259. }
  27260. return error.message;
  27261. }
  27262. /**
  27263. * @license
  27264. * Copyright Google Inc. All Rights Reserved.
  27265. *
  27266. * Use of this source code is governed by an MIT-style license that can be
  27267. * found in the LICENSE file at https://angular.io/license
  27268. */
  27269. /**
  27270. * @license
  27271. * Copyright Google Inc. All Rights Reserved.
  27272. *
  27273. * Use of this source code is governed by an MIT-style license that can be
  27274. * found in the LICENSE file at https://angular.io/license
  27275. */
  27276. /**
  27277. * @license
  27278. * Copyright Google Inc. All Rights Reserved.
  27279. *
  27280. * Use of this source code is governed by an MIT-style license that can be
  27281. * found in the LICENSE file at https://angular.io/license
  27282. */
  27283. /**
  27284. * @license
  27285. * Copyright Google Inc. All Rights Reserved.
  27286. *
  27287. * Use of this source code is governed by an MIT-style license that can be
  27288. * found in the LICENSE file at https://angular.io/license
  27289. */
  27290. var EmitFlags;
  27291. (function (EmitFlags) {
  27292. EmitFlags[EmitFlags["DTS"] = 1] = "DTS";
  27293. EmitFlags[EmitFlags["JS"] = 2] = "JS";
  27294. EmitFlags[EmitFlags["Metadata"] = 4] = "Metadata";
  27295. EmitFlags[EmitFlags["I18nBundle"] = 8] = "I18nBundle";
  27296. EmitFlags[EmitFlags["Codegen"] = 16] = "Codegen";
  27297. EmitFlags[EmitFlags["Default"] = 19] = "Default";
  27298. EmitFlags[EmitFlags["All"] = 31] = "All";
  27299. })(EmitFlags || (EmitFlags = {}));
  27300. /**
  27301. * @license
  27302. * Copyright Google Inc. All Rights Reserved.
  27303. *
  27304. * Use of this source code is governed by an MIT-style license that can be
  27305. * found in the LICENSE file at https://angular.io/license
  27306. */
  27307. var DTS = /\.d\.ts$/;
  27308. /**
  27309. * @license
  27310. * Copyright Google Inc. All Rights Reserved.
  27311. *
  27312. * Use of this source code is governed by an MIT-style license that can be
  27313. * found in the LICENSE file at https://angular.io/license
  27314. */
  27315. function createMetadataReaderCache() {
  27316. var data = new Map();
  27317. return { data: data };
  27318. }
  27319. function readMetadata(filePath, host, cache) {
  27320. var metadatas = cache && cache.data.get(filePath);
  27321. if (metadatas) {
  27322. return metadatas;
  27323. }
  27324. if (host.fileExists(filePath)) {
  27325. // If the file doesn't exists then we cannot return metadata for the file.
  27326. // This will occur if the user referenced a declared module for which no file
  27327. // exists for the module (i.e. jQuery or angularjs).
  27328. if (DTS.test(filePath)) {
  27329. metadatas = readMetadataFile(host, filePath);
  27330. if (!metadatas) {
  27331. // If there is a .d.ts file but no metadata file we need to produce a
  27332. // metadata from the .d.ts file as metadata files capture reexports
  27333. // (starting with v3).
  27334. metadatas = [upgradeMetadataWithDtsData(host, { '__symbolic': 'module', 'version': 1, 'metadata': {} }, filePath)];
  27335. }
  27336. }
  27337. else {
  27338. var metadata = host.getSourceFileMetadata(filePath);
  27339. metadatas = metadata ? [metadata] : [];
  27340. }
  27341. }
  27342. if (cache && (!host.cacheMetadata || host.cacheMetadata(filePath))) {
  27343. cache.data.set(filePath, metadatas);
  27344. }
  27345. return metadatas;
  27346. }
  27347. function readMetadataFile(host, dtsFilePath) {
  27348. var metadataPath = dtsFilePath.replace(DTS, '.metadata.json');
  27349. if (!host.fileExists(metadataPath)) {
  27350. return undefined;
  27351. }
  27352. try {
  27353. var metadataOrMetadatas = JSON.parse(host.readFile(metadataPath));
  27354. var metadatas = metadataOrMetadatas ?
  27355. (Array.isArray(metadataOrMetadatas) ? metadataOrMetadatas : [metadataOrMetadatas]) :
  27356. [];
  27357. if (metadatas.length) {
  27358. var maxMetadata = metadatas.reduce(function (p, c) { return p.version > c.version ? p : c; });
  27359. if (maxMetadata.version < METADATA_VERSION) {
  27360. metadatas.push(upgradeMetadataWithDtsData(host, maxMetadata, dtsFilePath));
  27361. }
  27362. }
  27363. return metadatas;
  27364. }
  27365. catch (e) {
  27366. console.error("Failed to read JSON file " + metadataPath);
  27367. throw e;
  27368. }
  27369. }
  27370. function upgradeMetadataWithDtsData(host, oldMetadata, dtsFilePath) {
  27371. // patch v1 to v3 by adding exports and the `extends` clause.
  27372. // patch v3 to v4 by adding `interface` symbols for TypeAlias
  27373. var newMetadata = {
  27374. '__symbolic': 'module',
  27375. 'version': METADATA_VERSION,
  27376. 'metadata': __assign({}, oldMetadata.metadata),
  27377. };
  27378. if (oldMetadata.exports) {
  27379. newMetadata.exports = oldMetadata.exports;
  27380. }
  27381. if (oldMetadata.importAs) {
  27382. newMetadata.importAs = oldMetadata.importAs;
  27383. }
  27384. if (oldMetadata.origins) {
  27385. newMetadata.origins = oldMetadata.origins;
  27386. }
  27387. var dtsMetadata = host.getSourceFileMetadata(dtsFilePath);
  27388. if (dtsMetadata) {
  27389. for (var prop in dtsMetadata.metadata) {
  27390. if (!newMetadata.metadata[prop]) {
  27391. newMetadata.metadata[prop] = dtsMetadata.metadata[prop];
  27392. }
  27393. }
  27394. if (dtsMetadata['importAs'])
  27395. newMetadata['importAs'] = dtsMetadata['importAs'];
  27396. // Only copy exports from exports from metadata prior to version 3.
  27397. // Starting with version 3 the collector began collecting exports and
  27398. // this should be redundant. Also, with bundler will rewrite the exports
  27399. // which will hoist the exports from modules referenced indirectly causing
  27400. // the imports to be different than the .d.ts files and using the .d.ts file
  27401. // exports would cause the StaticSymbolResolver to redirect symbols to the
  27402. // incorrect location.
  27403. if ((!oldMetadata.version || oldMetadata.version < 3) && dtsMetadata.exports) {
  27404. newMetadata.exports = dtsMetadata.exports;
  27405. }
  27406. }
  27407. return newMetadata;
  27408. }
  27409. /**
  27410. * @license
  27411. * Copyright Google Inc. All Rights Reserved.
  27412. *
  27413. * Use of this source code is governed by an MIT-style license that can be
  27414. * found in the LICENSE file at https://angular.io/license
  27415. */
  27416. /**
  27417. * @license
  27418. * Copyright Google Inc. All Rights Reserved.
  27419. *
  27420. * Use of this source code is governed by an MIT-style license that can be
  27421. * found in the LICENSE file at https://angular.io/license
  27422. */
  27423. /**
  27424. * The kind of diagnostic message.
  27425. *
  27426. * @publicApi
  27427. */
  27428. var DiagnosticKind$1;
  27429. (function (DiagnosticKind) {
  27430. DiagnosticKind[DiagnosticKind["Error"] = 0] = "Error";
  27431. DiagnosticKind[DiagnosticKind["Warning"] = 1] = "Warning";
  27432. })(DiagnosticKind$1 || (DiagnosticKind$1 = {}));
  27433. /**
  27434. * @license
  27435. * Copyright Google Inc. All Rights Reserved.
  27436. *
  27437. * Use of this source code is governed by an MIT-style license that can be
  27438. * found in the LICENSE file at https://angular.io/license
  27439. */
  27440. function isParseSourceSpan(value) {
  27441. return value && !!value.start;
  27442. }
  27443. function spanOf$2(span) {
  27444. if (!span)
  27445. return undefined;
  27446. if (isParseSourceSpan(span)) {
  27447. return { start: span.start.offset, end: span.end.offset };
  27448. }
  27449. else {
  27450. if (span.endSourceSpan) {
  27451. return { start: span.sourceSpan.start.offset, end: span.endSourceSpan.end.offset };
  27452. }
  27453. else if (span.children && span.children.length) {
  27454. return {
  27455. start: span.sourceSpan.start.offset,
  27456. end: spanOf$2(span.children[span.children.length - 1]).end
  27457. };
  27458. }
  27459. return { start: span.sourceSpan.start.offset, end: span.sourceSpan.end.offset };
  27460. }
  27461. }
  27462. function inSpan(position, span, exclusive) {
  27463. return span != null && (exclusive ? position >= span.start && position < span.end :
  27464. position >= span.start && position <= span.end);
  27465. }
  27466. function offsetSpan$1(span, amount) {
  27467. return { start: span.start + amount, end: span.end + amount };
  27468. }
  27469. function isNarrower(spanA, spanB) {
  27470. return spanA.start >= spanB.start && spanA.end <= spanB.end;
  27471. }
  27472. function hasTemplateReference$1(type) {
  27473. var e_1, _a;
  27474. if (type.diDeps) {
  27475. try {
  27476. for (var _b = __values(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {
  27477. var diDep = _c.value;
  27478. if (diDep.token && diDep.token.identifier &&
  27479. identifierName(diDep.token.identifier) == 'TemplateRef')
  27480. return true;
  27481. }
  27482. }
  27483. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  27484. finally {
  27485. try {
  27486. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  27487. }
  27488. finally { if (e_1) throw e_1.error; }
  27489. }
  27490. }
  27491. return false;
  27492. }
  27493. function getSelectors(info) {
  27494. var map = new Map();
  27495. var selectors = flatten$1(info.directives.map(function (directive) {
  27496. var selectors = CssSelector.parse(directive.selector);
  27497. selectors.forEach(function (selector) { return map.set(selector, directive); });
  27498. return selectors;
  27499. }));
  27500. return { selectors: selectors, map: map };
  27501. }
  27502. function flatten$1(a) {
  27503. var _a;
  27504. return (_a = []).concat.apply(_a, __spread(a));
  27505. }
  27506. function removeSuffix(value, suffix) {
  27507. if (value.endsWith(suffix))
  27508. return value.substring(0, value.length - suffix.length);
  27509. return value;
  27510. }
  27511. function uniqueByName(elements) {
  27512. var e_2, _a;
  27513. if (elements) {
  27514. var result = [];
  27515. var set = new Set();
  27516. try {
  27517. for (var elements_1 = __values(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) {
  27518. var element = elements_1_1.value;
  27519. if (!set.has(element.name)) {
  27520. set.add(element.name);
  27521. result.push(element);
  27522. }
  27523. }
  27524. }
  27525. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  27526. finally {
  27527. try {
  27528. if (elements_1_1 && !elements_1_1.done && (_a = elements_1.return)) _a.call(elements_1);
  27529. }
  27530. finally { if (e_2) throw e_2.error; }
  27531. }
  27532. return result;
  27533. }
  27534. }
  27535. function diagnosticInfoFromTemplateInfo(info) {
  27536. return {
  27537. fileName: info.fileName,
  27538. offset: info.template.span.start,
  27539. query: info.template.query,
  27540. members: info.template.members,
  27541. htmlAst: info.htmlAst,
  27542. templateAst: info.templateAst
  27543. };
  27544. }
  27545. function findTemplateAstAt(ast, position, allowWidening) {
  27546. if (allowWidening === void 0) { allowWidening = false; }
  27547. var path = [];
  27548. var visitor = new /** @class */ (function (_super) {
  27549. __extends(class_1, _super);
  27550. function class_1() {
  27551. return _super !== null && _super.apply(this, arguments) || this;
  27552. }
  27553. class_1.prototype.visit = function (ast, context) {
  27554. var span = spanOf$2(ast);
  27555. if (inSpan(position, span)) {
  27556. var len = path.length;
  27557. if (!len || allowWidening || isNarrower(span, spanOf$2(path[len - 1]))) {
  27558. path.push(ast);
  27559. }
  27560. }
  27561. else {
  27562. // Returning a value here will result in the children being skipped.
  27563. return true;
  27564. }
  27565. };
  27566. class_1.prototype.visitEmbeddedTemplate = function (ast, context) {
  27567. return this.visitChildren(context, function (visit) {
  27568. // Ignore reference, variable and providers
  27569. visit(ast.attrs);
  27570. visit(ast.directives);
  27571. visit(ast.children);
  27572. });
  27573. };
  27574. class_1.prototype.visitElement = function (ast, context) {
  27575. return this.visitChildren(context, function (visit) {
  27576. // Ingnore providers
  27577. visit(ast.attrs);
  27578. visit(ast.inputs);
  27579. visit(ast.outputs);
  27580. visit(ast.references);
  27581. visit(ast.directives);
  27582. visit(ast.children);
  27583. });
  27584. };
  27585. class_1.prototype.visitDirective = function (ast, context) {
  27586. // Ignore the host properties of a directive
  27587. var result = this.visitChildren(context, function (visit) { visit(ast.inputs); });
  27588. // We never care about the diretive itself, just its inputs.
  27589. if (path[path.length - 1] == ast) {
  27590. path.pop();
  27591. }
  27592. return result;
  27593. };
  27594. return class_1;
  27595. }(RecursiveTemplateAstVisitor));
  27596. templateVisitAll(visitor, ast);
  27597. return new AstPath(path, position);
  27598. }
  27599. /**
  27600. * @license
  27601. * Copyright Google Inc. All Rights Reserved.
  27602. *
  27603. * Use of this source code is governed by an MIT-style license that can be
  27604. * found in the LICENSE file at https://angular.io/license
  27605. */
  27606. function findAstAt(ast, position, excludeEmpty) {
  27607. if (excludeEmpty === void 0) { excludeEmpty = false; }
  27608. var path = [];
  27609. var visitor = new /** @class */ (function (_super) {
  27610. __extends(class_1, _super);
  27611. function class_1() {
  27612. return _super !== null && _super.apply(this, arguments) || this;
  27613. }
  27614. class_1.prototype.visit = function (ast) {
  27615. if ((!excludeEmpty || ast.span.start < ast.span.end) && inSpan(position, ast.span)) {
  27616. path.push(ast);
  27617. visitAstChildren(ast, this);
  27618. }
  27619. };
  27620. return class_1;
  27621. }(NullAstVisitor));
  27622. // We never care about the ASTWithSource node and its visit() method calls its ast's visit so
  27623. // the visit() method above would never see it.
  27624. if (ast instanceof ASTWithSource) {
  27625. ast = ast.ast;
  27626. }
  27627. visitor.visit(ast);
  27628. return new AstPath(path, position);
  27629. }
  27630. function getExpressionCompletions(scope, ast, position, query) {
  27631. var path = findAstAt(ast, position);
  27632. if (path.empty)
  27633. return undefined;
  27634. var tail = path.tail;
  27635. var result = scope;
  27636. function getType(ast) { return new AstType(scope, query, {}).getType(ast); }
  27637. // If the completion request is in a not in a pipe or property access then the global scope
  27638. // (that is the scope of the implicit receiver) is the right scope as the user is typing the
  27639. // beginning of an expression.
  27640. tail.visit({
  27641. visitBinary: function (ast) { },
  27642. visitChain: function (ast) { },
  27643. visitConditional: function (ast) { },
  27644. visitFunctionCall: function (ast) { },
  27645. visitImplicitReceiver: function (ast) { },
  27646. visitInterpolation: function (ast) { result = undefined; },
  27647. visitKeyedRead: function (ast) { },
  27648. visitKeyedWrite: function (ast) { },
  27649. visitLiteralArray: function (ast) { },
  27650. visitLiteralMap: function (ast) { },
  27651. visitLiteralPrimitive: function (ast) { },
  27652. visitMethodCall: function (ast) { },
  27653. visitPipe: function (ast) {
  27654. if (position >= ast.exp.span.end &&
  27655. (!ast.args || !ast.args.length || position < ast.args[0].span.start)) {
  27656. // We are in a position a pipe name is expected.
  27657. result = query.getPipes();
  27658. }
  27659. },
  27660. visitPrefixNot: function (ast) { },
  27661. visitNonNullAssert: function (ast) { },
  27662. visitPropertyRead: function (ast) {
  27663. var receiverType = getType(ast.receiver);
  27664. result = receiverType ? receiverType.members() : scope;
  27665. },
  27666. visitPropertyWrite: function (ast) {
  27667. var receiverType = getType(ast.receiver);
  27668. result = receiverType ? receiverType.members() : scope;
  27669. },
  27670. visitQuote: function (ast) {
  27671. // For a quote, return the members of any (if there are any).
  27672. result = query.getBuiltinType(BuiltinType$1.Any).members();
  27673. },
  27674. visitSafeMethodCall: function (ast) {
  27675. var receiverType = getType(ast.receiver);
  27676. result = receiverType ? receiverType.members() : scope;
  27677. },
  27678. visitSafePropertyRead: function (ast) {
  27679. var receiverType = getType(ast.receiver);
  27680. result = receiverType ? receiverType.members() : scope;
  27681. },
  27682. });
  27683. return result && result.values();
  27684. }
  27685. function getExpressionSymbol(scope, ast, position, query) {
  27686. var path = findAstAt(ast, position, /* excludeEmpty */ true);
  27687. if (path.empty)
  27688. return undefined;
  27689. var tail = path.tail;
  27690. function getType(ast) { return new AstType(scope, query, {}).getType(ast); }
  27691. var symbol = undefined;
  27692. var span = undefined;
  27693. // If the completion request is in a not in a pipe or property access then the global scope
  27694. // (that is the scope of the implicit receiver) is the right scope as the user is typing the
  27695. // beginning of an expression.
  27696. tail.visit({
  27697. visitBinary: function (ast) { },
  27698. visitChain: function (ast) { },
  27699. visitConditional: function (ast) { },
  27700. visitFunctionCall: function (ast) { },
  27701. visitImplicitReceiver: function (ast) { },
  27702. visitInterpolation: function (ast) { },
  27703. visitKeyedRead: function (ast) { },
  27704. visitKeyedWrite: function (ast) { },
  27705. visitLiteralArray: function (ast) { },
  27706. visitLiteralMap: function (ast) { },
  27707. visitLiteralPrimitive: function (ast) { },
  27708. visitMethodCall: function (ast) {
  27709. var receiverType = getType(ast.receiver);
  27710. symbol = receiverType && receiverType.members().get(ast.name);
  27711. span = ast.span;
  27712. },
  27713. visitPipe: function (ast) {
  27714. if (position >= ast.exp.span.end &&
  27715. (!ast.args || !ast.args.length || position < ast.args[0].span.start)) {
  27716. // We are in a position a pipe name is expected.
  27717. var pipes = query.getPipes();
  27718. if (pipes) {
  27719. symbol = pipes.get(ast.name);
  27720. span = ast.span;
  27721. }
  27722. }
  27723. },
  27724. visitPrefixNot: function (ast) { },
  27725. visitNonNullAssert: function (ast) { },
  27726. visitPropertyRead: function (ast) {
  27727. var receiverType = getType(ast.receiver);
  27728. symbol = receiverType && receiverType.members().get(ast.name);
  27729. span = ast.span;
  27730. },
  27731. visitPropertyWrite: function (ast) {
  27732. var receiverType = getType(ast.receiver);
  27733. symbol = receiverType && receiverType.members().get(ast.name);
  27734. span = ast.span;
  27735. },
  27736. visitQuote: function (ast) { },
  27737. visitSafeMethodCall: function (ast) {
  27738. var receiverType = getType(ast.receiver);
  27739. symbol = receiverType && receiverType.members().get(ast.name);
  27740. span = ast.span;
  27741. },
  27742. visitSafePropertyRead: function (ast) {
  27743. var receiverType = getType(ast.receiver);
  27744. symbol = receiverType && receiverType.members().get(ast.name);
  27745. span = ast.span;
  27746. },
  27747. });
  27748. if (symbol && span) {
  27749. return { symbol: symbol, span: span };
  27750. }
  27751. }
  27752. /**
  27753. * @license
  27754. * Copyright Google Inc. All Rights Reserved.
  27755. *
  27756. * Use of this source code is governed by an MIT-style license that can be
  27757. * found in the LICENSE file at https://angular.io/license
  27758. */
  27759. var values = [
  27760. 'ID',
  27761. 'CDATA',
  27762. 'NAME',
  27763. ['ltr', 'rtl'],
  27764. ['rect', 'circle', 'poly', 'default'],
  27765. 'NUMBER',
  27766. ['nohref'],
  27767. ['ismap'],
  27768. ['declare'],
  27769. ['DATA', 'REF', 'OBJECT'],
  27770. ['GET', 'POST'],
  27771. 'IDREF',
  27772. ['TEXT', 'PASSWORD', 'CHECKBOX', 'RADIO', 'SUBMIT', 'RESET', 'FILE', 'HIDDEN', 'IMAGE', 'BUTTON'],
  27773. ['checked'],
  27774. ['disabled'],
  27775. ['readonly'],
  27776. ['multiple'],
  27777. ['selected'],
  27778. ['button', 'submit', 'reset'],
  27779. ['void', 'above', 'below', 'hsides', 'lhs', 'rhs', 'vsides', 'box', 'border'],
  27780. ['none', 'groups', 'rows', 'cols', 'all'],
  27781. ['left', 'center', 'right', 'justify', 'char'],
  27782. ['top', 'middle', 'bottom', 'baseline'],
  27783. 'IDREFS',
  27784. ['row', 'col', 'rowgroup', 'colgroup'],
  27785. ['defer']
  27786. ];
  27787. var groups = [
  27788. { id: 0 },
  27789. {
  27790. onclick: 1,
  27791. ondblclick: 1,
  27792. onmousedown: 1,
  27793. onmouseup: 1,
  27794. onmouseover: 1,
  27795. onmousemove: 1,
  27796. onmouseout: 1,
  27797. onkeypress: 1,
  27798. onkeydown: 1,
  27799. onkeyup: 1
  27800. },
  27801. { lang: 2, dir: 3 },
  27802. { onload: 1, onunload: 1 },
  27803. { name: 1 },
  27804. { href: 1 },
  27805. { type: 1 },
  27806. { alt: 1 },
  27807. { tabindex: 5 },
  27808. { media: 1 },
  27809. { nohref: 6 },
  27810. { usemap: 1 },
  27811. { src: 1 },
  27812. { onfocus: 1, onblur: 1 },
  27813. { charset: 1 },
  27814. { declare: 8, classid: 1, codebase: 1, data: 1, codetype: 1, archive: 1, standby: 1 },
  27815. { title: 1 },
  27816. { value: 1 },
  27817. { cite: 1 },
  27818. { datetime: 1 },
  27819. { accept: 1 },
  27820. { shape: 4, coords: 1 },
  27821. { for: 11
  27822. },
  27823. { action: 1, method: 10, enctype: 1, onsubmit: 1, onreset: 1, 'accept-charset': 1 },
  27824. { valuetype: 9 },
  27825. { longdesc: 1 },
  27826. { width: 1 },
  27827. { disabled: 14 },
  27828. { readonly: 15, onselect: 1 },
  27829. { accesskey: 1 },
  27830. { size: 5, multiple: 16 },
  27831. { onchange: 1 },
  27832. { label: 1 },
  27833. { selected: 17 },
  27834. { type: 12, checked: 13, size: 1, maxlength: 5 },
  27835. { rows: 5, cols: 5 },
  27836. { type: 18 },
  27837. { height: 1 },
  27838. { summary: 1, border: 1, frame: 19, rules: 20, cellspacing: 1, cellpadding: 1, datapagesize: 1 },
  27839. { align: 21, char: 1, charoff: 1, valign: 22 },
  27840. { span: 5 },
  27841. { abbr: 1, axis: 1, headers: 23, scope: 24, rowspan: 5, colspan: 5 },
  27842. { profile: 1 },
  27843. { 'http-equiv': 2, name: 2, content: 1, scheme: 1 },
  27844. { class: 1, style: 1 },
  27845. { hreflang: 2, rel: 1, rev: 1 },
  27846. { ismap: 7 },
  27847. { defer: 25, event: 1, for: 1 }
  27848. ];
  27849. var elements = {
  27850. TT: [0, 1, 2, 16, 44],
  27851. I: [0, 1, 2, 16, 44],
  27852. B: [0, 1, 2, 16, 44],
  27853. BIG: [0, 1, 2, 16, 44],
  27854. SMALL: [0, 1, 2, 16, 44],
  27855. EM: [0, 1, 2, 16, 44],
  27856. STRONG: [0, 1, 2, 16, 44],
  27857. DFN: [0, 1, 2, 16, 44],
  27858. CODE: [0, 1, 2, 16, 44],
  27859. SAMP: [0, 1, 2, 16, 44],
  27860. KBD: [0, 1, 2, 16, 44],
  27861. VAR: [0, 1, 2, 16, 44],
  27862. CITE: [0, 1, 2, 16, 44],
  27863. ABBR: [0, 1, 2, 16, 44],
  27864. ACRONYM: [0, 1, 2, 16, 44],
  27865. SUB: [0, 1, 2, 16, 44],
  27866. SUP: [0, 1, 2, 16, 44],
  27867. SPAN: [0, 1, 2, 16, 44],
  27868. BDO: [0, 2, 16, 44],
  27869. BR: [0, 16, 44],
  27870. BODY: [0, 1, 2, 3, 16, 44],
  27871. ADDRESS: [0, 1, 2, 16, 44],
  27872. DIV: [0, 1, 2, 16, 44],
  27873. A: [0, 1, 2, 4, 5, 6, 8, 13, 14, 16, 21, 29, 44, 45],
  27874. MAP: [0, 1, 2, 4, 16, 44],
  27875. AREA: [0, 1, 2, 5, 7, 8, 10, 13, 16, 21, 29, 44],
  27876. LINK: [0, 1, 2, 5, 6, 9, 14, 16, 44, 45],
  27877. IMG: [0, 1, 2, 4, 7, 11, 12, 16, 25, 26, 37, 44, 46],
  27878. OBJECT: [0, 1, 2, 4, 6, 8, 11, 15, 16, 26, 37, 44],
  27879. PARAM: [0, 4, 6, 17, 24],
  27880. HR: [0, 1, 2, 16, 44],
  27881. P: [0, 1, 2, 16, 44],
  27882. H1: [0, 1, 2, 16, 44],
  27883. H2: [0, 1, 2, 16, 44],
  27884. H3: [0, 1, 2, 16, 44],
  27885. H4: [0, 1, 2, 16, 44],
  27886. H5: [0, 1, 2, 16, 44],
  27887. H6: [0, 1, 2, 16, 44],
  27888. PRE: [0, 1, 2, 16, 44],
  27889. Q: [0, 1, 2, 16, 18, 44],
  27890. BLOCKQUOTE: [0, 1, 2, 16, 18, 44],
  27891. INS: [0, 1, 2, 16, 18, 19, 44],
  27892. DEL: [0, 1, 2, 16, 18, 19, 44],
  27893. DL: [0, 1, 2, 16, 44],
  27894. DT: [0, 1, 2, 16, 44],
  27895. DD: [0, 1, 2, 16, 44],
  27896. OL: [0, 1, 2, 16, 44],
  27897. UL: [0, 1, 2, 16, 44],
  27898. LI: [0, 1, 2, 16, 44],
  27899. FORM: [0, 1, 2, 4, 16, 20, 23, 44],
  27900. LABEL: [0, 1, 2, 13, 16, 22, 29, 44],
  27901. INPUT: [0, 1, 2, 4, 7, 8, 11, 12, 13, 16, 17, 20, 27, 28, 29, 31, 34, 44, 46],
  27902. SELECT: [0, 1, 2, 4, 8, 13, 16, 27, 30, 31, 44],
  27903. OPTGROUP: [0, 1, 2, 16, 27, 32, 44],
  27904. OPTION: [0, 1, 2, 16, 17, 27, 32, 33, 44],
  27905. TEXTAREA: [0, 1, 2, 4, 8, 13, 16, 27, 28, 29, 31, 35, 44],
  27906. FIELDSET: [0, 1, 2, 16, 44],
  27907. LEGEND: [0, 1, 2, 16, 29, 44],
  27908. BUTTON: [0, 1, 2, 4, 8, 13, 16, 17, 27, 29, 36, 44],
  27909. TABLE: [0, 1, 2, 16, 26, 38, 44],
  27910. CAPTION: [0, 1, 2, 16, 44],
  27911. COLGROUP: [0, 1, 2, 16, 26, 39, 40, 44],
  27912. COL: [0, 1, 2, 16, 26, 39, 40, 44],
  27913. THEAD: [0, 1, 2, 16, 39, 44],
  27914. TBODY: [0, 1, 2, 16, 39, 44],
  27915. TFOOT: [0, 1, 2, 16, 39, 44],
  27916. TR: [0, 1, 2, 16, 39, 44],
  27917. TH: [0, 1, 2, 16, 39, 41, 44],
  27918. TD: [0, 1, 2, 16, 39, 41, 44],
  27919. HEAD: [2, 42],
  27920. TITLE: [2],
  27921. BASE: [5],
  27922. META: [2, 43],
  27923. STYLE: [2, 6, 9, 16],
  27924. SCRIPT: [6, 12, 14, 47],
  27925. NOSCRIPT: [0, 1, 2, 16, 44],
  27926. HTML: [2]
  27927. };
  27928. var defaultAttributes = [0, 1, 2, 4];
  27929. function elementNames() {
  27930. return Object.keys(elements).sort().map(function (v) { return v.toLowerCase(); });
  27931. }
  27932. function compose(indexes) {
  27933. var e_1, _a;
  27934. var result = {};
  27935. if (indexes) {
  27936. try {
  27937. for (var indexes_1 = __values(indexes), indexes_1_1 = indexes_1.next(); !indexes_1_1.done; indexes_1_1 = indexes_1.next()) {
  27938. var index = indexes_1_1.value;
  27939. var group = groups[index];
  27940. for (var name_1 in group)
  27941. if (group.hasOwnProperty(name_1))
  27942. result[name_1] = values[group[name_1]];
  27943. }
  27944. }
  27945. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  27946. finally {
  27947. try {
  27948. if (indexes_1_1 && !indexes_1_1.done && (_a = indexes_1.return)) _a.call(indexes_1);
  27949. }
  27950. finally { if (e_1) throw e_1.error; }
  27951. }
  27952. }
  27953. return result;
  27954. }
  27955. function attributeNames(element) {
  27956. return Object.keys(compose(elements[element.toUpperCase()] || defaultAttributes)).sort();
  27957. }
  27958. // This section is describes the DOM property surface of a DOM element and is derivgulp formated
  27959. // from
  27960. // from the SCHEMA strings from the security context information. SCHEMA is copied here because
  27961. // it would be an unnecessary risk to allow this array to be imported from the security context
  27962. // schema registry.
  27963. var SCHEMA$1 = [
  27964. '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
  27965. /* added manually to avoid breaking changes */
  27966. ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
  27967. '[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
  27968. 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
  27969. 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
  27970. ':svg:^[HTMLElement]|*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex',
  27971. ':svg:graphics^:svg:|',
  27972. ':svg:animation^:svg:|*begin,*end,*repeat',
  27973. ':svg:geometry^:svg:|',
  27974. ':svg:componentTransferFunction^:svg:|',
  27975. ':svg:gradient^:svg:|',
  27976. ':svg:textContent^:svg:graphics|',
  27977. ':svg:textPositioning^:svg:textContent|',
  27978. 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username',
  27979. 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
  27980. 'audio^media|',
  27981. 'br^[HTMLElement]|clear',
  27982. 'base^[HTMLElement]|href,target',
  27983. 'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink',
  27984. 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
  27985. 'canvas^[HTMLElement]|#height,#width',
  27986. 'content^[HTMLElement]|select',
  27987. 'dl^[HTMLElement]|!compact',
  27988. 'datalist^[HTMLElement]|',
  27989. 'details^[HTMLElement]|!open',
  27990. 'dialog^[HTMLElement]|!open,returnValue',
  27991. 'dir^[HTMLElement]|!compact',
  27992. 'div^[HTMLElement]|align',
  27993. 'embed^[HTMLElement]|align,height,name,src,type,width',
  27994. 'fieldset^[HTMLElement]|!disabled,name',
  27995. 'font^[HTMLElement]|color,face,size',
  27996. 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
  27997. 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
  27998. 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
  27999. 'hr^[HTMLElement]|align,color,!noShade,size,width',
  28000. 'head^[HTMLElement]|',
  28001. 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
  28002. 'html^[HTMLElement]|version',
  28003. 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
  28004. 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
  28005. 'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width',
  28006. 'li^[HTMLElement]|type,#value',
  28007. 'label^[HTMLElement]|htmlFor',
  28008. 'legend^[HTMLElement]|align',
  28009. 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
  28010. 'map^[HTMLElement]|name',
  28011. 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
  28012. 'menu^[HTMLElement]|!compact',
  28013. 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
  28014. 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
  28015. 'ins,del^[HTMLElement]|cite,dateTime',
  28016. 'ol^[HTMLElement]|!compact,!reversed,#start,type',
  28017. 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
  28018. 'optgroup^[HTMLElement]|!disabled,label',
  28019. 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
  28020. 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
  28021. 'p^[HTMLElement]|align',
  28022. 'param^[HTMLElement]|name,type,value,valueType',
  28023. 'picture^[HTMLElement]|',
  28024. 'pre^[HTMLElement]|#width',
  28025. 'progress^[HTMLElement]|#max,#value',
  28026. 'q,blockquote,cite^[HTMLElement]|',
  28027. 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
  28028. 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
  28029. 'shadow^[HTMLElement]|',
  28030. 'slot^[HTMLElement]|name',
  28031. 'source^[HTMLElement]|media,sizes,src,srcset,type',
  28032. 'span^[HTMLElement]|',
  28033. 'style^[HTMLElement]|!disabled,media,type',
  28034. 'caption^[HTMLElement]|align',
  28035. 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
  28036. 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
  28037. 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
  28038. 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
  28039. 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
  28040. 'template^[HTMLElement]|',
  28041. 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
  28042. 'title^[HTMLElement]|text',
  28043. 'track^[HTMLElement]|!default,kind,label,src,srclang',
  28044. 'ul^[HTMLElement]|!compact,type',
  28045. 'unknown^[HTMLElement]|',
  28046. 'video^media|#height,poster,#width',
  28047. ':svg:a^:svg:graphics|',
  28048. ':svg:animate^:svg:animation|',
  28049. ':svg:animateMotion^:svg:animation|',
  28050. ':svg:animateTransform^:svg:animation|',
  28051. ':svg:circle^:svg:geometry|',
  28052. ':svg:clipPath^:svg:graphics|',
  28053. ':svg:defs^:svg:graphics|',
  28054. ':svg:desc^:svg:|',
  28055. ':svg:discard^:svg:|',
  28056. ':svg:ellipse^:svg:geometry|',
  28057. ':svg:feBlend^:svg:|',
  28058. ':svg:feColorMatrix^:svg:|',
  28059. ':svg:feComponentTransfer^:svg:|',
  28060. ':svg:feComposite^:svg:|',
  28061. ':svg:feConvolveMatrix^:svg:|',
  28062. ':svg:feDiffuseLighting^:svg:|',
  28063. ':svg:feDisplacementMap^:svg:|',
  28064. ':svg:feDistantLight^:svg:|',
  28065. ':svg:feDropShadow^:svg:|',
  28066. ':svg:feFlood^:svg:|',
  28067. ':svg:feFuncA^:svg:componentTransferFunction|',
  28068. ':svg:feFuncB^:svg:componentTransferFunction|',
  28069. ':svg:feFuncG^:svg:componentTransferFunction|',
  28070. ':svg:feFuncR^:svg:componentTransferFunction|',
  28071. ':svg:feGaussianBlur^:svg:|',
  28072. ':svg:feImage^:svg:|',
  28073. ':svg:feMerge^:svg:|',
  28074. ':svg:feMergeNode^:svg:|',
  28075. ':svg:feMorphology^:svg:|',
  28076. ':svg:feOffset^:svg:|',
  28077. ':svg:fePointLight^:svg:|',
  28078. ':svg:feSpecularLighting^:svg:|',
  28079. ':svg:feSpotLight^:svg:|',
  28080. ':svg:feTile^:svg:|',
  28081. ':svg:feTurbulence^:svg:|',
  28082. ':svg:filter^:svg:|',
  28083. ':svg:foreignObject^:svg:graphics|',
  28084. ':svg:g^:svg:graphics|',
  28085. ':svg:image^:svg:graphics|',
  28086. ':svg:line^:svg:geometry|',
  28087. ':svg:linearGradient^:svg:gradient|',
  28088. ':svg:mpath^:svg:|',
  28089. ':svg:marker^:svg:|',
  28090. ':svg:mask^:svg:|',
  28091. ':svg:metadata^:svg:|',
  28092. ':svg:path^:svg:geometry|',
  28093. ':svg:pattern^:svg:|',
  28094. ':svg:polygon^:svg:geometry|',
  28095. ':svg:polyline^:svg:geometry|',
  28096. ':svg:radialGradient^:svg:gradient|',
  28097. ':svg:rect^:svg:geometry|',
  28098. ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
  28099. ':svg:script^:svg:|type',
  28100. ':svg:set^:svg:animation|',
  28101. ':svg:stop^:svg:|',
  28102. ':svg:style^:svg:|!disabled,media,title,type',
  28103. ':svg:switch^:svg:graphics|',
  28104. ':svg:symbol^:svg:|',
  28105. ':svg:tspan^:svg:textPositioning|',
  28106. ':svg:text^:svg:textPositioning|',
  28107. ':svg:textPath^:svg:textContent|',
  28108. ':svg:title^:svg:|',
  28109. ':svg:use^:svg:graphics|',
  28110. ':svg:view^:svg:|#zoomAndPan',
  28111. 'data^[HTMLElement]|value',
  28112. 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
  28113. 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
  28114. 'summary^[HTMLElement]|',
  28115. 'time^[HTMLElement]|dateTime',
  28116. ':svg:cursor^:svg:|',
  28117. ];
  28118. var EVENT = 'event';
  28119. var BOOLEAN$1 = 'boolean';
  28120. var NUMBER$1 = 'number';
  28121. var STRING$1 = 'string';
  28122. var OBJECT$1 = 'object';
  28123. var SchemaInformation = /** @class */ (function () {
  28124. function SchemaInformation() {
  28125. var _this = this;
  28126. this.schema = {};
  28127. SCHEMA$1.forEach(function (encodedType) {
  28128. var parts = encodedType.split('|');
  28129. var properties = parts[1].split(',');
  28130. var typeParts = (parts[0] + '^').split('^');
  28131. var typeName = typeParts[0];
  28132. var type = {};
  28133. typeName.split(',').forEach(function (tag) { return _this.schema[tag.toLowerCase()] = type; });
  28134. var superName = typeParts[1];
  28135. var superType = superName && _this.schema[superName.toLowerCase()];
  28136. if (superType) {
  28137. for (var key in superType) {
  28138. type[key] = superType[key];
  28139. }
  28140. }
  28141. properties.forEach(function (property) {
  28142. if (property == '') ;
  28143. else if (property.startsWith('*')) {
  28144. type[property.substring(1)] = EVENT;
  28145. }
  28146. else if (property.startsWith('!')) {
  28147. type[property.substring(1)] = BOOLEAN$1;
  28148. }
  28149. else if (property.startsWith('#')) {
  28150. type[property.substring(1)] = NUMBER$1;
  28151. }
  28152. else if (property.startsWith('%')) {
  28153. type[property.substring(1)] = OBJECT$1;
  28154. }
  28155. else {
  28156. type[property] = STRING$1;
  28157. }
  28158. });
  28159. });
  28160. }
  28161. SchemaInformation.prototype.allKnownElements = function () { return Object.keys(this.schema); };
  28162. SchemaInformation.prototype.eventsOf = function (elementName) {
  28163. var elementType = this.schema[elementName.toLowerCase()] || {};
  28164. return Object.keys(elementType).filter(function (property) { return elementType[property] === EVENT; });
  28165. };
  28166. SchemaInformation.prototype.propertiesOf = function (elementName) {
  28167. var elementType = this.schema[elementName.toLowerCase()] || {};
  28168. return Object.keys(elementType).filter(function (property) { return elementType[property] !== EVENT; });
  28169. };
  28170. SchemaInformation.prototype.typeOf = function (elementName, property) {
  28171. return (this.schema[elementName.toLowerCase()] || {})[property];
  28172. };
  28173. Object.defineProperty(SchemaInformation, "instance", {
  28174. get: function () {
  28175. var result = SchemaInformation._instance;
  28176. if (!result) {
  28177. result = SchemaInformation._instance = new SchemaInformation();
  28178. }
  28179. return result;
  28180. },
  28181. enumerable: true,
  28182. configurable: true
  28183. });
  28184. return SchemaInformation;
  28185. }());
  28186. function eventNames(elementName) {
  28187. return SchemaInformation.instance.eventsOf(elementName);
  28188. }
  28189. function propertyNames(elementName) {
  28190. return SchemaInformation.instance.propertiesOf(elementName);
  28191. }
  28192. /**
  28193. * @license
  28194. * Copyright Google Inc. All Rights Reserved.
  28195. *
  28196. * Use of this source code is governed by an MIT-style license that can be
  28197. * found in the LICENSE file at https://angular.io/license
  28198. */
  28199. var TEMPLATE_ATTR_PREFIX$2 = '*';
  28200. var hiddenHtmlElements = {
  28201. html: true,
  28202. script: true,
  28203. noscript: true,
  28204. base: true,
  28205. body: true,
  28206. title: true,
  28207. head: true,
  28208. link: true,
  28209. };
  28210. function getTemplateCompletions(templateInfo) {
  28211. var result = undefined;
  28212. var htmlAst = templateInfo.htmlAst, templateAst = templateInfo.templateAst, template = templateInfo.template;
  28213. // The templateNode starts at the delimiter character so we add 1 to skip it.
  28214. if (templateInfo.position != null) {
  28215. var templatePosition_1 = templateInfo.position - template.span.start;
  28216. var path_1 = findNode(htmlAst, templatePosition_1);
  28217. var mostSpecific = path_1.tail;
  28218. if (path_1.empty || !mostSpecific) {
  28219. result = elementCompletions(templateInfo, path_1);
  28220. }
  28221. else {
  28222. var astPosition_1 = templatePosition_1 - mostSpecific.sourceSpan.start.offset;
  28223. mostSpecific.visit({
  28224. visitElement: function (ast) {
  28225. var startTagSpan = spanOf$2(ast.sourceSpan);
  28226. var tagLen = ast.name.length;
  28227. if (templatePosition_1 <=
  28228. startTagSpan.start + tagLen + 1 /* 1 for the opening angle bracked */) {
  28229. // If we are in the tag then return the element completions.
  28230. result = elementCompletions(templateInfo, path_1);
  28231. }
  28232. else if (templatePosition_1 < startTagSpan.end) {
  28233. // We are in the attribute section of the element (but not in an attribute).
  28234. // Return the attribute completions.
  28235. result = attributeCompletions(templateInfo, path_1);
  28236. }
  28237. },
  28238. visitAttribute: function (ast) {
  28239. if (!ast.valueSpan || !inSpan(templatePosition_1, spanOf$2(ast.valueSpan))) {
  28240. // We are in the name of an attribute. Show attribute completions.
  28241. result = attributeCompletions(templateInfo, path_1);
  28242. }
  28243. else if (ast.valueSpan && inSpan(templatePosition_1, spanOf$2(ast.valueSpan))) {
  28244. result = attributeValueCompletions(templateInfo, templatePosition_1, ast);
  28245. }
  28246. },
  28247. visitText: function (ast) {
  28248. // Check if we are in a entity.
  28249. result = entityCompletions(getSourceText(template, spanOf$2(ast)), astPosition_1);
  28250. if (result)
  28251. return result;
  28252. result = interpolationCompletions(templateInfo, templatePosition_1);
  28253. if (result)
  28254. return result;
  28255. var element = path_1.first(Element$1);
  28256. if (element) {
  28257. var definition = getHtmlTagDefinition(element.name);
  28258. if (definition.contentType === TagContentType.PARSABLE_DATA) {
  28259. result = voidElementAttributeCompletions(templateInfo, path_1);
  28260. if (!result) {
  28261. // If the element can hold content Show element completions.
  28262. result = elementCompletions(templateInfo, path_1);
  28263. }
  28264. }
  28265. }
  28266. else {
  28267. // If no element container, implies parsable data so show elements.
  28268. result = voidElementAttributeCompletions(templateInfo, path_1);
  28269. if (!result) {
  28270. result = elementCompletions(templateInfo, path_1);
  28271. }
  28272. }
  28273. },
  28274. visitComment: function (ast) { },
  28275. visitExpansion: function (ast) { },
  28276. visitExpansionCase: function (ast) { }
  28277. }, null);
  28278. }
  28279. }
  28280. return result;
  28281. }
  28282. function attributeCompletions(info, path) {
  28283. var item = path.tail instanceof Element$1 ? path.tail : path.parentOf(path.tail);
  28284. if (item instanceof Element$1) {
  28285. return attributeCompletionsForElement(info, item.name, item);
  28286. }
  28287. return undefined;
  28288. }
  28289. function attributeCompletionsForElement(info, elementName, element) {
  28290. var attributes = getAttributeInfosForElement(info, elementName, element);
  28291. // Map all the attributes to a completion
  28292. return attributes.map(function (attr) { return ({
  28293. kind: attr.fromHtml ? 'html attribute' : 'attribute',
  28294. name: nameOfAttr(attr),
  28295. sort: attr.name
  28296. }); });
  28297. }
  28298. function getAttributeInfosForElement(info, elementName, element) {
  28299. var attributes = [];
  28300. // Add html attributes
  28301. var htmlAttributes = attributeNames(elementName) || [];
  28302. if (htmlAttributes) {
  28303. attributes.push.apply(attributes, __spread(htmlAttributes.map(function (name) { return ({ name: name, fromHtml: true }); })));
  28304. }
  28305. // Add html properties
  28306. var htmlProperties = propertyNames(elementName);
  28307. if (htmlProperties) {
  28308. attributes.push.apply(attributes, __spread(htmlProperties.map(function (name) { return ({ name: name, input: true }); })));
  28309. }
  28310. // Add html events
  28311. var htmlEvents = eventNames(elementName);
  28312. if (htmlEvents) {
  28313. attributes.push.apply(attributes, __spread(htmlEvents.map(function (name) { return ({ name: name, output: true }); })));
  28314. }
  28315. var _a = getSelectors(info), selectors = _a.selectors, selectorMap = _a.map;
  28316. if (selectors && selectors.length) {
  28317. // All the attributes that are selectable should be shown.
  28318. var applicableSelectors = selectors.filter(function (selector) { return !selector.element || selector.element == elementName; });
  28319. var selectorAndAttributeNames = applicableSelectors.map(function (selector) { return ({ selector: selector, attrs: selector.attrs.filter(function (a) { return !!a; }) }); });
  28320. var attrs_1 = flatten$1(selectorAndAttributeNames.map(function (selectorAndAttr) {
  28321. var directive = selectorMap.get(selectorAndAttr.selector);
  28322. var result = selectorAndAttr.attrs.map(function (name) { return ({ name: name, input: name in directive.inputs, output: name in directive.outputs }); });
  28323. return result;
  28324. }));
  28325. // Add template attribute if a directive contains a template reference
  28326. selectorAndAttributeNames.forEach(function (selectorAndAttr) {
  28327. var selector = selectorAndAttr.selector;
  28328. var directive = selectorMap.get(selector);
  28329. if (directive && hasTemplateReference$1(directive.type) && selector.attrs.length &&
  28330. selector.attrs[0]) {
  28331. attrs_1.push({ name: selector.attrs[0], template: true });
  28332. }
  28333. });
  28334. // All input and output properties of the matching directives should be added.
  28335. var elementSelector = element ?
  28336. createElementCssSelector$1(element) :
  28337. createElementCssSelector$1(new Element$1(elementName, [], [], null, null, null));
  28338. var matcher = new SelectorMatcher();
  28339. matcher.addSelectables(selectors);
  28340. matcher.match(elementSelector, function (selector) {
  28341. var directive = selectorMap.get(selector);
  28342. if (directive) {
  28343. var inputs_1 = directive.inputs, outputs_1 = directive.outputs;
  28344. attrs_1.push.apply(attrs_1, __spread(Object.keys(inputs_1).map(function (name) { return ({ name: inputs_1[name], input: true }); })));
  28345. attrs_1.push.apply(attrs_1, __spread(Object.keys(outputs_1).map(function (name) { return ({ name: outputs_1[name], output: true }); })));
  28346. }
  28347. });
  28348. // If a name shows up twice, fold it into a single value.
  28349. attrs_1 = foldAttrs(attrs_1);
  28350. // Now expand them back out to ensure that input/output shows up as well as input and
  28351. // output.
  28352. attributes.push.apply(attributes, __spread(flatten$1(attrs_1.map(expandedAttr))));
  28353. }
  28354. return attributes;
  28355. }
  28356. function attributeValueCompletions(info, position, attr) {
  28357. var path = findTemplateAstAt(info.templateAst, position);
  28358. var mostSpecific = path.tail;
  28359. var dinfo = diagnosticInfoFromTemplateInfo(info);
  28360. if (mostSpecific) {
  28361. var visitor = new ExpressionVisitor(info, position, attr, function () { return getExpressionScope(dinfo, path, false); });
  28362. mostSpecific.visit(visitor, null);
  28363. if (!visitor.result || !visitor.result.length) {
  28364. // Try allwoing widening the path
  28365. var widerPath_1 = findTemplateAstAt(info.templateAst, position, /* allowWidening */ true);
  28366. if (widerPath_1.tail) {
  28367. var widerVisitor = new ExpressionVisitor(info, position, attr, function () { return getExpressionScope(dinfo, widerPath_1, false); });
  28368. widerPath_1.tail.visit(widerVisitor, null);
  28369. return widerVisitor.result;
  28370. }
  28371. }
  28372. return visitor.result;
  28373. }
  28374. }
  28375. function elementCompletions(info, path) {
  28376. var htmlNames = elementNames().filter(function (name) { return !(name in hiddenHtmlElements); });
  28377. // Collect the elements referenced by the selectors
  28378. var directiveElements = getSelectors(info)
  28379. .selectors.map(function (selector) { return selector.element; })
  28380. .filter(function (name) { return !!name; });
  28381. var components = directiveElements.map(function (name) { return ({ kind: 'component', name: name, sort: name }); });
  28382. var htmlElements = htmlNames.map(function (name) { return ({ kind: 'element', name: name, sort: name }); });
  28383. // Return components and html elements
  28384. return uniqueByName(htmlElements.concat(components));
  28385. }
  28386. function entityCompletions(value, position) {
  28387. // Look for entity completions
  28388. var re = /&[A-Za-z]*;?(?!\d)/g;
  28389. var found;
  28390. var result = undefined;
  28391. while (found = re.exec(value)) {
  28392. var len = found[0].length;
  28393. if (position >= found.index && position < (found.index + len)) {
  28394. result = Object.keys(NAMED_ENTITIES)
  28395. .map(function (name) { return ({ kind: 'entity', name: "&" + name + ";", sort: name }); });
  28396. break;
  28397. }
  28398. }
  28399. return result;
  28400. }
  28401. function interpolationCompletions(info, position) {
  28402. // Look for an interpolation in at the position.
  28403. var templatePath = findTemplateAstAt(info.templateAst, position);
  28404. var mostSpecific = templatePath.tail;
  28405. if (mostSpecific) {
  28406. var visitor = new ExpressionVisitor(info, position, undefined, function () { return getExpressionScope(diagnosticInfoFromTemplateInfo(info), templatePath, false); });
  28407. mostSpecific.visit(visitor, null);
  28408. return uniqueByName(visitor.result);
  28409. }
  28410. }
  28411. // There is a special case of HTML where text that contains a unclosed tag is treated as
  28412. // text. For exaple '<h1> Some <a text </h1>' produces a text nodes inside of the H1
  28413. // element "Some <a text". We, however, want to treat this as if the user was requesting
  28414. // the attributes of an "a" element, not requesting completion in the a text element. This
  28415. // code checks for this case and returns element completions if it is detected or undefined
  28416. // if it is not.
  28417. function voidElementAttributeCompletions(info, path) {
  28418. var tail = path.tail;
  28419. if (tail instanceof Text$3) {
  28420. var match = tail.value.match(/<(\w(\w|\d|-)*:)?(\w(\w|\d|-)*)\s/);
  28421. // The position must be after the match, otherwise we are still in a place where elements
  28422. // are expected (such as `<|a` or `<a|`; we only want attributes for `<a |` or after).
  28423. if (match &&
  28424. path.position >= (match.index || 0) + match[0].length + tail.sourceSpan.start.offset) {
  28425. return attributeCompletionsForElement(info, match[3]);
  28426. }
  28427. }
  28428. }
  28429. var ExpressionVisitor = /** @class */ (function (_super) {
  28430. __extends(ExpressionVisitor, _super);
  28431. function ExpressionVisitor(info, position, attr, getExpressionScope) {
  28432. var _this = _super.call(this) || this;
  28433. _this.info = info;
  28434. _this.position = position;
  28435. _this.attr = attr;
  28436. _this.getExpressionScope = getExpressionScope || (function () { return info.template.members; });
  28437. return _this;
  28438. }
  28439. ExpressionVisitor.prototype.visitDirectiveProperty = function (ast) {
  28440. this.attributeValueCompletions(ast.value);
  28441. };
  28442. ExpressionVisitor.prototype.visitElementProperty = function (ast) {
  28443. this.attributeValueCompletions(ast.value);
  28444. };
  28445. ExpressionVisitor.prototype.visitEvent = function (ast) { this.attributeValueCompletions(ast.handler); };
  28446. ExpressionVisitor.prototype.visitElement = function (ast) {
  28447. var _this = this;
  28448. if (this.attr && getSelectors(this.info) && this.attr.name.startsWith(TEMPLATE_ATTR_PREFIX$2)) {
  28449. // The value is a template expression but the expression AST was not produced when the
  28450. // TemplateAst was produce so
  28451. // do that now.
  28452. var key_1 = this.attr.name.substr(TEMPLATE_ATTR_PREFIX$2.length);
  28453. // Find the selector
  28454. var selectorInfo = getSelectors(this.info);
  28455. var selectors = selectorInfo.selectors;
  28456. var selector_1 = selectors.filter(function (s) { return s.attrs.some(function (attr, i) { return i % 2 == 0 && attr == key_1; }); })[0];
  28457. var templateBindingResult = this.info.expressionParser.parseTemplateBindings(key_1, this.attr.value, null);
  28458. // find the template binding that contains the position
  28459. if (!this.attr.valueSpan)
  28460. return;
  28461. var valueRelativePosition_1 = this.position - this.attr.valueSpan.start.offset;
  28462. var bindings = templateBindingResult.templateBindings;
  28463. var binding = bindings.find(function (binding) { return inSpan(valueRelativePosition_1, binding.span, /* exclusive */ true); }) ||
  28464. bindings.find(function (binding) { return inSpan(valueRelativePosition_1, binding.span); });
  28465. var keyCompletions = function () {
  28466. var keys = [];
  28467. if (selector_1) {
  28468. var attrNames = selector_1.attrs.filter(function (_, i) { return i % 2 == 0; });
  28469. keys = attrNames.filter(function (name) { return name.startsWith(key_1) && name != key_1; })
  28470. .map(function (name) { return lowerName(name.substr(key_1.length)); });
  28471. }
  28472. keys.push('let');
  28473. _this.result = keys.map(function (key) { return ({ kind: 'key', name: key, sort: key }); });
  28474. };
  28475. if (!binding || (binding.key == key_1 && !binding.expression)) {
  28476. // We are in the root binding. We should return `let` and keys that are left in the
  28477. // selector.
  28478. keyCompletions();
  28479. }
  28480. else if (binding.keyIsVar) {
  28481. var equalLocation = this.attr.value.indexOf('=');
  28482. this.result = [];
  28483. if (equalLocation >= 0 && valueRelativePosition_1 >= equalLocation) {
  28484. // We are after the '=' in a let clause. The valid values here are the members of the
  28485. // template reference's type parameter.
  28486. var directiveMetadata = selectorInfo.map.get(selector_1);
  28487. if (directiveMetadata) {
  28488. var contextTable = this.info.template.query.getTemplateContext(directiveMetadata.type.reference);
  28489. if (contextTable) {
  28490. this.result = this.symbolsToCompletions(contextTable.values());
  28491. }
  28492. }
  28493. }
  28494. else if (binding.key && valueRelativePosition_1 <= (binding.key.length - key_1.length)) {
  28495. keyCompletions();
  28496. }
  28497. }
  28498. else {
  28499. // If the position is in the expression or after the key or there is no key, return the
  28500. // expression completions
  28501. if ((binding.expression && inSpan(valueRelativePosition_1, binding.expression.ast.span)) ||
  28502. (binding.key &&
  28503. valueRelativePosition_1 > binding.span.start + (binding.key.length - key_1.length)) ||
  28504. !binding.key) {
  28505. var span = new ParseSpan(0, this.attr.value.length);
  28506. this.attributeValueCompletions(binding.expression ? binding.expression.ast :
  28507. new PropertyRead(span, new ImplicitReceiver(span), ''), valueRelativePosition_1);
  28508. }
  28509. else {
  28510. keyCompletions();
  28511. }
  28512. }
  28513. }
  28514. };
  28515. ExpressionVisitor.prototype.visitBoundText = function (ast) {
  28516. var expressionPosition = this.position - ast.sourceSpan.start.offset;
  28517. if (inSpan(expressionPosition, ast.value.span)) {
  28518. var completions = getExpressionCompletions(this.getExpressionScope(), ast.value, expressionPosition, this.info.template.query);
  28519. if (completions) {
  28520. this.result = this.symbolsToCompletions(completions);
  28521. }
  28522. }
  28523. };
  28524. ExpressionVisitor.prototype.attributeValueCompletions = function (value, position) {
  28525. var symbols = getExpressionCompletions(this.getExpressionScope(), value, position == null ? this.attributeValuePosition : position, this.info.template.query);
  28526. if (symbols) {
  28527. this.result = this.symbolsToCompletions(symbols);
  28528. }
  28529. };
  28530. ExpressionVisitor.prototype.symbolsToCompletions = function (symbols) {
  28531. return symbols.filter(function (s) { return !s.name.startsWith('__') && s.public; })
  28532. .map(function (symbol) { return ({ kind: symbol.kind, name: symbol.name, sort: symbol.name }); });
  28533. };
  28534. Object.defineProperty(ExpressionVisitor.prototype, "attributeValuePosition", {
  28535. get: function () {
  28536. if (this.attr && this.attr.valueSpan) {
  28537. return this.position - this.attr.valueSpan.start.offset;
  28538. }
  28539. return 0;
  28540. },
  28541. enumerable: true,
  28542. configurable: true
  28543. });
  28544. return ExpressionVisitor;
  28545. }(NullTemplateVisitor));
  28546. function getSourceText(template, span) {
  28547. return template.source.substring(span.start, span.end);
  28548. }
  28549. function nameOfAttr(attr) {
  28550. var name = attr.name;
  28551. if (attr.output) {
  28552. name = removeSuffix(name, 'Events');
  28553. name = removeSuffix(name, 'Changed');
  28554. }
  28555. var result = [name];
  28556. if (attr.input) {
  28557. result.unshift('[');
  28558. result.push(']');
  28559. }
  28560. if (attr.output) {
  28561. result.unshift('(');
  28562. result.push(')');
  28563. }
  28564. if (attr.template) {
  28565. result.unshift('*');
  28566. }
  28567. return result.join('');
  28568. }
  28569. var templateAttr = /^(\w+:)?(template$|^\*)/;
  28570. function createElementCssSelector$1(element) {
  28571. var e_1, _a;
  28572. var cssSelector = new CssSelector();
  28573. var elNameNoNs = splitNsName(element.name)[1];
  28574. cssSelector.setElement(elNameNoNs);
  28575. try {
  28576. for (var _b = __values(element.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
  28577. var attr = _c.value;
  28578. if (!attr.name.match(templateAttr)) {
  28579. var _d = __read(splitNsName(attr.name), 2), _ = _d[0], attrNameNoNs = _d[1];
  28580. cssSelector.addAttribute(attrNameNoNs, attr.value);
  28581. if (attr.name.toLowerCase() == 'class') {
  28582. var classes = attr.value.split(/s+/g);
  28583. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  28584. }
  28585. }
  28586. }
  28587. }
  28588. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  28589. finally {
  28590. try {
  28591. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  28592. }
  28593. finally { if (e_1) throw e_1.error; }
  28594. }
  28595. return cssSelector;
  28596. }
  28597. function foldAttrs(attrs) {
  28598. var inputOutput = new Map();
  28599. var templates = new Map();
  28600. var result = [];
  28601. attrs.forEach(function (attr) {
  28602. if (attr.fromHtml) {
  28603. return attr;
  28604. }
  28605. if (attr.template) {
  28606. var duplicate = templates.get(attr.name);
  28607. if (!duplicate) {
  28608. result.push({ name: attr.name, template: true });
  28609. templates.set(attr.name, attr);
  28610. }
  28611. }
  28612. if (attr.input || attr.output) {
  28613. var duplicate = inputOutput.get(attr.name);
  28614. if (duplicate) {
  28615. duplicate.input = duplicate.input || attr.input;
  28616. duplicate.output = duplicate.output || attr.output;
  28617. }
  28618. else {
  28619. var cloneAttr = { name: attr.name };
  28620. if (attr.input)
  28621. cloneAttr.input = true;
  28622. if (attr.output)
  28623. cloneAttr.output = true;
  28624. result.push(cloneAttr);
  28625. inputOutput.set(attr.name, cloneAttr);
  28626. }
  28627. }
  28628. });
  28629. return result;
  28630. }
  28631. function expandedAttr(attr) {
  28632. if (attr.input && attr.output) {
  28633. return [
  28634. attr, { name: attr.name, input: true, output: false },
  28635. { name: attr.name, input: false, output: true }
  28636. ];
  28637. }
  28638. return [attr];
  28639. }
  28640. function lowerName(name) {
  28641. return name && (name[0].toLowerCase() + name.substr(1));
  28642. }
  28643. /**
  28644. * @license
  28645. * Copyright Google Inc. All Rights Reserved.
  28646. *
  28647. * Use of this source code is governed by an MIT-style license that can be
  28648. * found in the LICENSE file at https://angular.io/license
  28649. */
  28650. function locateSymbol(info) {
  28651. if (!info.position)
  28652. return undefined;
  28653. var templatePosition = info.position - info.template.span.start;
  28654. var path = findTemplateAstAt(info.templateAst, templatePosition);
  28655. if (path.tail) {
  28656. var symbol_1 = undefined;
  28657. var span_1 = undefined;
  28658. var attributeValueSymbol_1 = function (ast, inEvent) {
  28659. if (inEvent === void 0) { inEvent = false; }
  28660. var attribute = findAttribute(info);
  28661. if (attribute) {
  28662. if (inSpan(templatePosition, spanOf$2(attribute.valueSpan))) {
  28663. var dinfo = diagnosticInfoFromTemplateInfo(info);
  28664. var scope = getExpressionScope(dinfo, path, inEvent);
  28665. if (attribute.valueSpan) {
  28666. var expressionOffset = attribute.valueSpan.start.offset;
  28667. var result = getExpressionSymbol(scope, ast, templatePosition - expressionOffset, info.template.query);
  28668. if (result) {
  28669. symbol_1 = result.symbol;
  28670. span_1 = offsetSpan$1(result.span, expressionOffset);
  28671. }
  28672. }
  28673. return true;
  28674. }
  28675. }
  28676. return false;
  28677. };
  28678. path.tail.visit({
  28679. visitNgContent: function (ast) { },
  28680. visitEmbeddedTemplate: function (ast) { },
  28681. visitElement: function (ast) {
  28682. var component = ast.directives.find(function (d) { return d.directive.isComponent; });
  28683. if (component) {
  28684. symbol_1 = info.template.query.getTypeSymbol(component.directive.type.reference);
  28685. symbol_1 = symbol_1 && new OverrideKindSymbol(symbol_1, 'component');
  28686. span_1 = spanOf$2(ast);
  28687. }
  28688. else {
  28689. // Find a directive that matches the element name
  28690. var directive = ast.directives.find(function (d) { return d.directive.selector != null && d.directive.selector.indexOf(ast.name) >= 0; });
  28691. if (directive) {
  28692. symbol_1 = info.template.query.getTypeSymbol(directive.directive.type.reference);
  28693. symbol_1 = symbol_1 && new OverrideKindSymbol(symbol_1, 'directive');
  28694. span_1 = spanOf$2(ast);
  28695. }
  28696. }
  28697. },
  28698. visitReference: function (ast) {
  28699. symbol_1 = ast.value && info.template.query.getTypeSymbol(tokenReference(ast.value));
  28700. span_1 = spanOf$2(ast);
  28701. },
  28702. visitVariable: function (ast) { },
  28703. visitEvent: function (ast) {
  28704. if (!attributeValueSymbol_1(ast.handler, /* inEvent */ true)) {
  28705. symbol_1 = findOutputBinding(info, path, ast);
  28706. symbol_1 = symbol_1 && new OverrideKindSymbol(symbol_1, 'event');
  28707. span_1 = spanOf$2(ast);
  28708. }
  28709. },
  28710. visitElementProperty: function (ast) { attributeValueSymbol_1(ast.value); },
  28711. visitAttr: function (ast) { },
  28712. visitBoundText: function (ast) {
  28713. var expressionPosition = templatePosition - ast.sourceSpan.start.offset;
  28714. if (inSpan(expressionPosition, ast.value.span)) {
  28715. var dinfo = diagnosticInfoFromTemplateInfo(info);
  28716. var scope = getExpressionScope(dinfo, path, /* includeEvent */ false);
  28717. var result = getExpressionSymbol(scope, ast.value, expressionPosition, info.template.query);
  28718. if (result) {
  28719. symbol_1 = result.symbol;
  28720. span_1 = offsetSpan$1(result.span, ast.sourceSpan.start.offset);
  28721. }
  28722. }
  28723. },
  28724. visitText: function (ast) { },
  28725. visitDirective: function (ast) {
  28726. symbol_1 = info.template.query.getTypeSymbol(ast.directive.type.reference);
  28727. span_1 = spanOf$2(ast);
  28728. },
  28729. visitDirectiveProperty: function (ast) {
  28730. if (!attributeValueSymbol_1(ast.value)) {
  28731. symbol_1 = findInputBinding(info, path, ast);
  28732. span_1 = spanOf$2(ast);
  28733. }
  28734. }
  28735. }, null);
  28736. if (symbol_1 && span_1) {
  28737. return { symbol: symbol_1, span: offsetSpan$1(span_1, info.template.span.start) };
  28738. }
  28739. }
  28740. }
  28741. function findAttribute(info) {
  28742. if (info.position) {
  28743. var templatePosition = info.position - info.template.span.start;
  28744. var path = findNode(info.htmlAst, templatePosition);
  28745. return path.first(Attribute);
  28746. }
  28747. }
  28748. function findInputBinding(info, path, binding) {
  28749. var e_1, _a;
  28750. var element = path.first(ElementAst);
  28751. if (element) {
  28752. try {
  28753. for (var _b = __values(element.directives), _c = _b.next(); !_c.done; _c = _b.next()) {
  28754. var directive = _c.value;
  28755. var invertedInput = invertMap(directive.directive.inputs);
  28756. var fieldName = invertedInput[binding.templateName];
  28757. if (fieldName) {
  28758. var classSymbol = info.template.query.getTypeSymbol(directive.directive.type.reference);
  28759. if (classSymbol) {
  28760. return classSymbol.members().get(fieldName);
  28761. }
  28762. }
  28763. }
  28764. }
  28765. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  28766. finally {
  28767. try {
  28768. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  28769. }
  28770. finally { if (e_1) throw e_1.error; }
  28771. }
  28772. }
  28773. }
  28774. function findOutputBinding(info, path, binding) {
  28775. var e_2, _a;
  28776. var element = path.first(ElementAst);
  28777. if (element) {
  28778. try {
  28779. for (var _b = __values(element.directives), _c = _b.next(); !_c.done; _c = _b.next()) {
  28780. var directive = _c.value;
  28781. var invertedOutputs = invertMap(directive.directive.outputs);
  28782. var fieldName = invertedOutputs[binding.name];
  28783. if (fieldName) {
  28784. var classSymbol = info.template.query.getTypeSymbol(directive.directive.type.reference);
  28785. if (classSymbol) {
  28786. return classSymbol.members().get(fieldName);
  28787. }
  28788. }
  28789. }
  28790. }
  28791. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  28792. finally {
  28793. try {
  28794. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  28795. }
  28796. finally { if (e_2) throw e_2.error; }
  28797. }
  28798. }
  28799. }
  28800. function invertMap(obj) {
  28801. var e_3, _a;
  28802. var result = {};
  28803. try {
  28804. for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
  28805. var name_1 = _c.value;
  28806. var v = obj[name_1];
  28807. result[v] = name_1;
  28808. }
  28809. }
  28810. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  28811. finally {
  28812. try {
  28813. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  28814. }
  28815. finally { if (e_3) throw e_3.error; }
  28816. }
  28817. return result;
  28818. }
  28819. /**
  28820. * Wrap a symbol and change its kind to component.
  28821. */
  28822. var OverrideKindSymbol = /** @class */ (function () {
  28823. function OverrideKindSymbol(sym, kindOverride) {
  28824. this.sym = sym;
  28825. this.kind = kindOverride;
  28826. }
  28827. Object.defineProperty(OverrideKindSymbol.prototype, "name", {
  28828. get: function () { return this.sym.name; },
  28829. enumerable: true,
  28830. configurable: true
  28831. });
  28832. Object.defineProperty(OverrideKindSymbol.prototype, "language", {
  28833. get: function () { return this.sym.language; },
  28834. enumerable: true,
  28835. configurable: true
  28836. });
  28837. Object.defineProperty(OverrideKindSymbol.prototype, "type", {
  28838. get: function () { return this.sym.type; },
  28839. enumerable: true,
  28840. configurable: true
  28841. });
  28842. Object.defineProperty(OverrideKindSymbol.prototype, "container", {
  28843. get: function () { return this.sym.container; },
  28844. enumerable: true,
  28845. configurable: true
  28846. });
  28847. Object.defineProperty(OverrideKindSymbol.prototype, "public", {
  28848. get: function () { return this.sym.public; },
  28849. enumerable: true,
  28850. configurable: true
  28851. });
  28852. Object.defineProperty(OverrideKindSymbol.prototype, "callable", {
  28853. get: function () { return this.sym.callable; },
  28854. enumerable: true,
  28855. configurable: true
  28856. });
  28857. Object.defineProperty(OverrideKindSymbol.prototype, "nullable", {
  28858. get: function () { return this.sym.nullable; },
  28859. enumerable: true,
  28860. configurable: true
  28861. });
  28862. Object.defineProperty(OverrideKindSymbol.prototype, "definition", {
  28863. get: function () { return this.sym.definition; },
  28864. enumerable: true,
  28865. configurable: true
  28866. });
  28867. OverrideKindSymbol.prototype.members = function () { return this.sym.members(); };
  28868. OverrideKindSymbol.prototype.signatures = function () { return this.sym.signatures(); };
  28869. OverrideKindSymbol.prototype.selectSignature = function (types) { return this.sym.selectSignature(types); };
  28870. OverrideKindSymbol.prototype.indexed = function (argument) { return this.sym.indexed(argument); };
  28871. return OverrideKindSymbol;
  28872. }());
  28873. /**
  28874. * @license
  28875. * Copyright Google Inc. All Rights Reserved.
  28876. *
  28877. * Use of this source code is governed by an MIT-style license that can be
  28878. * found in the LICENSE file at https://angular.io/license
  28879. */
  28880. function getDefinition(info) {
  28881. var result = locateSymbol(info);
  28882. return result && result.symbol.definition;
  28883. }
  28884. /**
  28885. * @license
  28886. * Copyright Google Inc. All Rights Reserved.
  28887. *
  28888. * Use of this source code is governed by an MIT-style license that can be
  28889. * found in the LICENSE file at https://angular.io/license
  28890. */
  28891. function getDeclarationDiagnostics(declarations, modules) {
  28892. var e_1, _a;
  28893. var results = [];
  28894. var directives = undefined;
  28895. var _loop_1 = function (declaration) {
  28896. var e_2, _a;
  28897. var report = function (message, span) {
  28898. results.push({
  28899. kind: DiagnosticKind$1.Error,
  28900. span: span || declaration.declarationSpan, message: message
  28901. });
  28902. };
  28903. try {
  28904. for (var _b = __values(declaration.errors), _c = _b.next(); !_c.done; _c = _b.next()) {
  28905. var error = _c.value;
  28906. report(error.message, error.span);
  28907. }
  28908. }
  28909. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  28910. finally {
  28911. try {
  28912. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  28913. }
  28914. finally { if (e_2) throw e_2.error; }
  28915. }
  28916. if (declaration.metadata) {
  28917. if (declaration.metadata.isComponent) {
  28918. if (!modules.ngModuleByPipeOrDirective.has(declaration.type)) {
  28919. report("Component '" + declaration.type.name + "' is not included in a module and will not be available inside a template. Consider adding it to a NgModule declaration");
  28920. }
  28921. var _d = declaration.metadata.template, template = _d.template, templateUrl = _d.templateUrl;
  28922. if (template === null && !templateUrl) {
  28923. report("Component '" + declaration.type.name + "' must have a template or templateUrl");
  28924. }
  28925. else if (template && templateUrl) {
  28926. report("Component '" + declaration.type.name + "' must not have both template and templateUrl");
  28927. }
  28928. }
  28929. else {
  28930. if (!directives) {
  28931. directives = new Set();
  28932. modules.ngModules.forEach(function (module) {
  28933. module.declaredDirectives.forEach(function (directive) { directives.add(directive.reference); });
  28934. });
  28935. }
  28936. if (!directives.has(declaration.type)) {
  28937. report("Directive '" + declaration.type.name + "' is not included in a module and will not be available inside a template. Consider adding it to a NgModule declaration");
  28938. }
  28939. }
  28940. }
  28941. };
  28942. try {
  28943. for (var declarations_1 = __values(declarations), declarations_1_1 = declarations_1.next(); !declarations_1_1.done; declarations_1_1 = declarations_1.next()) {
  28944. var declaration = declarations_1_1.value;
  28945. _loop_1(declaration);
  28946. }
  28947. }
  28948. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  28949. finally {
  28950. try {
  28951. if (declarations_1_1 && !declarations_1_1.done && (_a = declarations_1.return)) _a.call(declarations_1);
  28952. }
  28953. finally { if (e_1) throw e_1.error; }
  28954. }
  28955. return results;
  28956. }
  28957. /**
  28958. * @license
  28959. * Copyright Google Inc. All Rights Reserved.
  28960. *
  28961. * Use of this source code is governed by an MIT-style license that can be
  28962. * found in the LICENSE file at https://angular.io/license
  28963. */
  28964. function getHover(info) {
  28965. var result = locateSymbol(info);
  28966. if (result) {
  28967. return { text: hoverTextOf(result.symbol), span: result.span };
  28968. }
  28969. }
  28970. function hoverTextOf(symbol) {
  28971. var result = [{ text: symbol.kind }, { text: ' ' }, { text: symbol.name, language: symbol.language }];
  28972. var container = symbol.container;
  28973. if (container) {
  28974. result.push({ text: ' of ' }, { text: container.name, language: container.language });
  28975. }
  28976. return result;
  28977. }
  28978. /**
  28979. * @license
  28980. * Copyright Google Inc. All Rights Reserved.
  28981. *
  28982. * Use of this source code is governed by an MIT-style license that can be
  28983. * found in the LICENSE file at https://angular.io/license
  28984. */
  28985. /**
  28986. * Create an instance of an Angular `LanguageService`.
  28987. *
  28988. * @publicApi
  28989. */
  28990. function createLanguageService(host) {
  28991. return new LanguageServiceImpl(host);
  28992. }
  28993. var LanguageServiceImpl = /** @class */ (function () {
  28994. function LanguageServiceImpl(host) {
  28995. this.host = host;
  28996. }
  28997. Object.defineProperty(LanguageServiceImpl.prototype, "metadataResolver", {
  28998. get: function () { return this.host.resolver; },
  28999. enumerable: true,
  29000. configurable: true
  29001. });
  29002. LanguageServiceImpl.prototype.getTemplateReferences = function () { return this.host.getTemplateReferences(); };
  29003. LanguageServiceImpl.prototype.getDiagnostics = function (fileName) {
  29004. var results = [];
  29005. var templates = this.host.getTemplates(fileName);
  29006. if (templates && templates.length) {
  29007. results.push.apply(results, __spread(this.getTemplateDiagnostics(fileName, templates)));
  29008. }
  29009. var declarations = this.host.getDeclarations(fileName);
  29010. if (declarations && declarations.length) {
  29011. var summary = this.host.getAnalyzedModules();
  29012. results.push.apply(results, __spread(getDeclarationDiagnostics(declarations, summary)));
  29013. }
  29014. return uniqueBySpan(results);
  29015. };
  29016. LanguageServiceImpl.prototype.getPipesAt = function (fileName, position) {
  29017. var templateInfo = this.host.getTemplateAstAtPosition(fileName, position);
  29018. if (templateInfo) {
  29019. return templateInfo.pipes;
  29020. }
  29021. return [];
  29022. };
  29023. LanguageServiceImpl.prototype.getCompletionsAt = function (fileName, position) {
  29024. var templateInfo = this.host.getTemplateAstAtPosition(fileName, position);
  29025. if (templateInfo) {
  29026. return getTemplateCompletions(templateInfo);
  29027. }
  29028. };
  29029. LanguageServiceImpl.prototype.getDefinitionAt = function (fileName, position) {
  29030. var templateInfo = this.host.getTemplateAstAtPosition(fileName, position);
  29031. if (templateInfo) {
  29032. return getDefinition(templateInfo);
  29033. }
  29034. };
  29035. LanguageServiceImpl.prototype.getHoverAt = function (fileName, position) {
  29036. var templateInfo = this.host.getTemplateAstAtPosition(fileName, position);
  29037. if (templateInfo) {
  29038. return getHover(templateInfo);
  29039. }
  29040. };
  29041. LanguageServiceImpl.prototype.getTemplateDiagnostics = function (fileName, templates) {
  29042. var e_1, _a;
  29043. var results = [];
  29044. var _loop_1 = function (template) {
  29045. var ast = this_1.host.getTemplateAst(template, fileName);
  29046. if (ast) {
  29047. if (ast.parseErrors && ast.parseErrors.length) {
  29048. results.push.apply(results, __spread(ast.parseErrors.map(function (e) { return ({
  29049. kind: DiagnosticKind$1.Error,
  29050. span: offsetSpan$1(spanOf$2(e.span), template.span.start),
  29051. message: e.msg
  29052. }); })));
  29053. }
  29054. else if (ast.templateAst && ast.htmlAst) {
  29055. var info = {
  29056. templateAst: ast.templateAst,
  29057. htmlAst: ast.htmlAst,
  29058. offset: template.span.start,
  29059. query: template.query,
  29060. members: template.members
  29061. };
  29062. var expressionDiagnostics = getTemplateExpressionDiagnostics(info);
  29063. results.push.apply(results, __spread(expressionDiagnostics));
  29064. }
  29065. if (ast.errors) {
  29066. results.push.apply(results, __spread(ast.errors.map(function (e) { return ({ kind: e.kind, span: e.span || template.span, message: e.message }); })));
  29067. }
  29068. }
  29069. };
  29070. var this_1 = this;
  29071. try {
  29072. for (var templates_1 = __values(templates), templates_1_1 = templates_1.next(); !templates_1_1.done; templates_1_1 = templates_1.next()) {
  29073. var template = templates_1_1.value;
  29074. _loop_1(template);
  29075. }
  29076. }
  29077. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  29078. finally {
  29079. try {
  29080. if (templates_1_1 && !templates_1_1.done && (_a = templates_1.return)) _a.call(templates_1);
  29081. }
  29082. finally { if (e_1) throw e_1.error; }
  29083. }
  29084. return results;
  29085. };
  29086. return LanguageServiceImpl;
  29087. }());
  29088. function uniqueBySpan(elements) {
  29089. var e_2, _a;
  29090. if (elements) {
  29091. var result = [];
  29092. var map = new Map();
  29093. try {
  29094. for (var elements_1 = __values(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) {
  29095. var element = elements_1_1.value;
  29096. var span = element.span;
  29097. var set = map.get(span.start);
  29098. if (!set) {
  29099. set = new Set();
  29100. map.set(span.start, set);
  29101. }
  29102. if (!set.has(span.end)) {
  29103. set.add(span.end);
  29104. result.push(element);
  29105. }
  29106. }
  29107. }
  29108. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  29109. finally {
  29110. try {
  29111. if (elements_1_1 && !elements_1_1.done && (_a = elements_1.return)) _a.call(elements_1);
  29112. }
  29113. finally { if (e_2) throw e_2.error; }
  29114. }
  29115. return result;
  29116. }
  29117. }
  29118. /**
  29119. * @license
  29120. * Copyright Google Inc. All Rights Reserved.
  29121. *
  29122. * Use of this source code is governed by an MIT-style license that can be
  29123. * found in the LICENSE file at https://angular.io/license
  29124. */
  29125. var ANNOTATIONS = '__annotations__';
  29126. var PARAMETERS = '__parameters__';
  29127. var PROP_METADATA = '__prop__metadata__';
  29128. /**
  29129. * @suppress {globalThis}
  29130. */
  29131. function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
  29132. var metaCtor = makeMetadataCtor(props);
  29133. function DecoratorFactory() {
  29134. var _a;
  29135. var args = [];
  29136. for (var _i = 0; _i < arguments.length; _i++) {
  29137. args[_i] = arguments[_i];
  29138. }
  29139. if (this instanceof DecoratorFactory) {
  29140. metaCtor.call.apply(metaCtor, __spread([this], args));
  29141. return this;
  29142. }
  29143. var annotationInstance = new ((_a = DecoratorFactory).bind.apply(_a, __spread([void 0], args)))();
  29144. return function TypeDecorator(cls) {
  29145. if (typeFn)
  29146. typeFn.apply(void 0, __spread([cls], args));
  29147. // Use of Object.defineProperty is important since it creates non-enumerable property which
  29148. // prevents the property is copied during subclassing.
  29149. var annotations = cls.hasOwnProperty(ANNOTATIONS) ?
  29150. cls[ANNOTATIONS] :
  29151. Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS];
  29152. annotations.push(annotationInstance);
  29153. if (additionalProcessing)
  29154. additionalProcessing(cls);
  29155. return cls;
  29156. };
  29157. }
  29158. if (parentClass) {
  29159. DecoratorFactory.prototype = Object.create(parentClass.prototype);
  29160. }
  29161. DecoratorFactory.prototype.ngMetadataName = name;
  29162. DecoratorFactory.annotationCls = DecoratorFactory;
  29163. return DecoratorFactory;
  29164. }
  29165. function makeMetadataCtor(props) {
  29166. return function ctor() {
  29167. var args = [];
  29168. for (var _i = 0; _i < arguments.length; _i++) {
  29169. args[_i] = arguments[_i];
  29170. }
  29171. if (props) {
  29172. var values = props.apply(void 0, __spread(args));
  29173. for (var propName in values) {
  29174. this[propName] = values[propName];
  29175. }
  29176. }
  29177. };
  29178. }
  29179. function makeParamDecorator(name, props, parentClass) {
  29180. var metaCtor = makeMetadataCtor(props);
  29181. function ParamDecoratorFactory() {
  29182. var _a;
  29183. var args = [];
  29184. for (var _i = 0; _i < arguments.length; _i++) {
  29185. args[_i] = arguments[_i];
  29186. }
  29187. if (this instanceof ParamDecoratorFactory) {
  29188. metaCtor.apply(this, args);
  29189. return this;
  29190. }
  29191. var annotationInstance = new ((_a = ParamDecoratorFactory).bind.apply(_a, __spread([void 0], args)))();
  29192. ParamDecorator.annotation = annotationInstance;
  29193. return ParamDecorator;
  29194. function ParamDecorator(cls, unusedKey, index) {
  29195. // Use of Object.defineProperty is important since it creates non-enumerable property which
  29196. // prevents the property is copied during subclassing.
  29197. var parameters = cls.hasOwnProperty(PARAMETERS) ?
  29198. cls[PARAMETERS] :
  29199. Object.defineProperty(cls, PARAMETERS, { value: [] })[PARAMETERS];
  29200. // there might be gaps if some in between parameters do not have annotations.
  29201. // we pad with nulls.
  29202. while (parameters.length <= index) {
  29203. parameters.push(null);
  29204. }
  29205. (parameters[index] = parameters[index] || []).push(annotationInstance);
  29206. return cls;
  29207. }
  29208. }
  29209. if (parentClass) {
  29210. ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
  29211. }
  29212. ParamDecoratorFactory.prototype.ngMetadataName = name;
  29213. ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
  29214. return ParamDecoratorFactory;
  29215. }
  29216. function makePropDecorator(name, props, parentClass, additionalProcessing) {
  29217. var metaCtor = makeMetadataCtor(props);
  29218. function PropDecoratorFactory() {
  29219. var _a;
  29220. var args = [];
  29221. for (var _i = 0; _i < arguments.length; _i++) {
  29222. args[_i] = arguments[_i];
  29223. }
  29224. if (this instanceof PropDecoratorFactory) {
  29225. metaCtor.apply(this, args);
  29226. return this;
  29227. }
  29228. var decoratorInstance = new ((_a = PropDecoratorFactory).bind.apply(_a, __spread([void 0], args)))();
  29229. function PropDecorator(target, name) {
  29230. var constructor = target.constructor;
  29231. // Use of Object.defineProperty is important since it creates non-enumerable property which
  29232. // prevents the property is copied during subclassing.
  29233. var meta = constructor.hasOwnProperty(PROP_METADATA) ?
  29234. constructor[PROP_METADATA] :
  29235. Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA];
  29236. meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
  29237. meta[name].unshift(decoratorInstance);
  29238. if (additionalProcessing)
  29239. additionalProcessing.apply(void 0, __spread([target, name], args));
  29240. }
  29241. return PropDecorator;
  29242. }
  29243. if (parentClass) {
  29244. PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
  29245. }
  29246. PropDecoratorFactory.prototype.ngMetadataName = name;
  29247. PropDecoratorFactory.annotationCls = PropDecoratorFactory;
  29248. return PropDecoratorFactory;
  29249. }
  29250. /**
  29251. * @license
  29252. * Copyright Google Inc. All Rights Reserved.
  29253. *
  29254. * Use of this source code is governed by an MIT-style license that can be
  29255. * found in the LICENSE file at https://angular.io/license
  29256. */
  29257. var ɵ0 = function (token) { return ({ token: token }); };
  29258. /**
  29259. * Inject decorator and metadata.
  29260. *
  29261. * @Annotation
  29262. * @publicApi
  29263. */
  29264. var Inject = makeParamDecorator('Inject', ɵ0);
  29265. /**
  29266. * Optional decorator and metadata.
  29267. *
  29268. * @Annotation
  29269. * @publicApi
  29270. */
  29271. var Optional = makeParamDecorator('Optional');
  29272. /**
  29273. * Self decorator and metadata.
  29274. *
  29275. * @Annotation
  29276. * @publicApi
  29277. */
  29278. var Self = makeParamDecorator('Self');
  29279. /**
  29280. * SkipSelf decorator and metadata.
  29281. *
  29282. * @Annotation
  29283. * @publicApi
  29284. */
  29285. var SkipSelf = makeParamDecorator('SkipSelf');
  29286. /**
  29287. * Host decorator and metadata.
  29288. *
  29289. * @Annotation
  29290. * @publicApi
  29291. */
  29292. var Host = makeParamDecorator('Host');
  29293. var ɵ1 = function (attributeName) { return ({ attributeName: attributeName }); };
  29294. /**
  29295. * Attribute decorator and metadata.
  29296. *
  29297. * @Annotation
  29298. * @publicApi
  29299. */
  29300. var Attribute$1 = makeParamDecorator('Attribute', ɵ1);
  29301. /**
  29302. * @license
  29303. * Copyright Google Inc. All Rights Reserved.
  29304. *
  29305. * Use of this source code is governed by an MIT-style license that can be
  29306. * found in the LICENSE file at https://angular.io/license
  29307. */
  29308. /**
  29309. * Injection flags for DI.
  29310. *
  29311. * @publicApi
  29312. */
  29313. var InjectFlags;
  29314. (function (InjectFlags) {
  29315. // TODO(alxhub): make this 'const' when ngc no longer writes exports of it into ngfactory files.
  29316. /** Check self and check parent injector if needed */
  29317. InjectFlags[InjectFlags["Default"] = 0] = "Default";
  29318. /**
  29319. * Specifies that an injector should retrieve a dependency from any injector until reaching the
  29320. * host element of the current component. (Only used with Element Injector)
  29321. */
  29322. InjectFlags[InjectFlags["Host"] = 1] = "Host";
  29323. /** Don't ascend to ancestors of the node requesting injection. */
  29324. InjectFlags[InjectFlags["Self"] = 2] = "Self";
  29325. /** Skip the node that is requesting injection. */
  29326. InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
  29327. /** Inject `defaultValue` instead if token not found. */
  29328. InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
  29329. })(InjectFlags || (InjectFlags = {}));
  29330. /**
  29331. * @license
  29332. * Copyright Google Inc. All Rights Reserved.
  29333. *
  29334. * Use of this source code is governed by an MIT-style license that can be
  29335. * found in the LICENSE file at https://angular.io/license
  29336. */
  29337. function getClosureSafeProperty(objWithPropertyToExtract) {
  29338. for (var key in objWithPropertyToExtract) {
  29339. if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
  29340. return key;
  29341. }
  29342. }
  29343. throw Error('Could not find renamed property on target object.');
  29344. }
  29345. /**
  29346. * @license
  29347. * Copyright Google Inc. All Rights Reserved.
  29348. *
  29349. * Use of this source code is governed by an MIT-style license that can be
  29350. * found in the LICENSE file at https://angular.io/license
  29351. */
  29352. /**
  29353. * Construct an `InjectableDef` which defines how a token will be constructed by the DI system, and
  29354. * in which injectors (if any) it will be available.
  29355. *
  29356. * This should be assigned to a static `ngInjectableDef` field on a type, which will then be an
  29357. * `InjectableType`.
  29358. *
  29359. * Options:
  29360. * * `providedIn` determines which injectors will include the injectable, by either associating it
  29361. * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
  29362. * provided in the `'root'` injector, which will be the application-level injector in most apps.
  29363. * * `factory` gives the zero argument function which will create an instance of the injectable.
  29364. * The factory can call `inject` to access the `Injector` and request injection of dependencies.
  29365. *
  29366. * @codeGenApi
  29367. */
  29368. function ɵɵdefineInjectable(opts) {
  29369. return {
  29370. token: opts.token, providedIn: opts.providedIn || null, factory: opts.factory,
  29371. value: undefined,
  29372. };
  29373. }
  29374. /**
  29375. * Construct an `InjectorDef` which configures an injector.
  29376. *
  29377. * This should be assigned to a static `ngInjectorDef` field on a type, which will then be an
  29378. * `InjectorType`.
  29379. *
  29380. * Options:
  29381. *
  29382. * * `factory`: an `InjectorType` is an instantiable type, so a zero argument `factory` function to
  29383. * create the type must be provided. If that factory function needs to inject arguments, it can
  29384. * use the `inject` function.
  29385. * * `providers`: an optional array of providers to add to the injector. Each provider must
  29386. * either have a factory or point to a type which has an `ngInjectableDef` static property (the
  29387. * type must be an `InjectableType`).
  29388. * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
  29389. * whose providers will also be added to the injector. Locally provided types will override
  29390. * providers from imports.
  29391. *
  29392. * @publicApi
  29393. */
  29394. function ɵɵdefineInjector(options) {
  29395. return {
  29396. factory: options.factory, providers: options.providers || [], imports: options.imports || [],
  29397. };
  29398. }
  29399. /**
  29400. * Read the `ngInjectableDef` for `type` in a way which is immune to accidentally reading inherited
  29401. * value.
  29402. *
  29403. * @param type A type which may have its own (non-inherited) `ngInjectableDef`.
  29404. */
  29405. function getInjectableDef(type) {
  29406. var def = type[NG_INJECTABLE_DEF];
  29407. // The definition read above may come from a base class. `hasOwnProperty` is not sufficient to
  29408. // distinguish this case, as in older browsers (e.g. IE10) static property inheritance is
  29409. // implemented by copying the properties.
  29410. //
  29411. // Instead, the ngInjectableDef's token is compared to the type, and if they don't match then the
  29412. // property was not defined directly on the type itself, and was likely inherited. The definition
  29413. // is only returned if the type matches the def.token.
  29414. return def && def.token === type ? def : null;
  29415. }
  29416. /**
  29417. * Read the `ngInjectableDef` for `type` or read the `ngInjectableDef` from one of its ancestors.
  29418. *
  29419. * @param type A type which may have `ngInjectableDef`, via inheritance.
  29420. *
  29421. * @deprecated Will be removed in v10, where an error will occur in the scenario if we find the
  29422. * `ngInjectableDef` on an ancestor only.
  29423. */
  29424. function getInheritedInjectableDef(type) {
  29425. if (type && type[NG_INJECTABLE_DEF]) {
  29426. // TODO(FW-1307): Re-add ngDevMode when closure can handle it
  29427. // ngDevMode &&
  29428. console.warn("DEPRECATED: DI is instantiating a token \"" + type.name + "\" that inherits its @Injectable decorator but does not provide one itself.\n" +
  29429. ("This will become an error in v10. Please add @Injectable() to the \"" + type.name + "\" class."));
  29430. return type[NG_INJECTABLE_DEF];
  29431. }
  29432. else {
  29433. return null;
  29434. }
  29435. }
  29436. /**
  29437. * Read the `ngInjectorDef` type in a way which is immune to accidentally reading inherited value.
  29438. *
  29439. * @param type type which may have `ngInjectorDef`
  29440. */
  29441. function getInjectorDef(type) {
  29442. return type && type.hasOwnProperty(NG_INJECTOR_DEF) ? type[NG_INJECTOR_DEF] : null;
  29443. }
  29444. var NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty });
  29445. var NG_INJECTOR_DEF = getClosureSafeProperty({ ngInjectorDef: getClosureSafeProperty });
  29446. /**
  29447. * @license
  29448. * Copyright Google Inc. All Rights Reserved.
  29449. *
  29450. * Use of this source code is governed by an MIT-style license that can be
  29451. * found in the LICENSE file at https://angular.io/license
  29452. */
  29453. function stringify$1(token) {
  29454. if (typeof token === 'string') {
  29455. return token;
  29456. }
  29457. if (token instanceof Array) {
  29458. return '[' + token.map(stringify$1).join(', ') + ']';
  29459. }
  29460. if (token == null) {
  29461. return '' + token;
  29462. }
  29463. if (token.overriddenName) {
  29464. return "" + token.overriddenName;
  29465. }
  29466. if (token.name) {
  29467. return "" + token.name;
  29468. }
  29469. var res = token.toString();
  29470. if (res == null) {
  29471. return '' + res;
  29472. }
  29473. var newLineIndex = res.indexOf('\n');
  29474. return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
  29475. }
  29476. /**
  29477. * @license
  29478. * Copyright Google Inc. All Rights Reserved.
  29479. *
  29480. * Use of this source code is governed by an MIT-style license that can be
  29481. * found in the LICENSE file at https://angular.io/license
  29482. */
  29483. var __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty });
  29484. /**
  29485. * Allows to refer to references which are not yet defined.
  29486. *
  29487. * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
  29488. * DI is declared, but not yet defined. It is also used when the `token` which we use when creating
  29489. * a query is not yet defined.
  29490. *
  29491. * @usageNotes
  29492. * ### Example
  29493. * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
  29494. * @publicApi
  29495. */
  29496. function forwardRef(forwardRefFn) {
  29497. forwardRefFn.__forward_ref__ = forwardRef;
  29498. forwardRefFn.toString = function () { return stringify$1(this()); };
  29499. return forwardRefFn;
  29500. }
  29501. /**
  29502. * Lazily retrieves the reference value from a forwardRef.
  29503. *
  29504. * Acts as the identity function when given a non-forward-ref value.
  29505. *
  29506. * @usageNotes
  29507. * ### Example
  29508. *
  29509. * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
  29510. *
  29511. * @see `forwardRef`
  29512. * @publicApi
  29513. */
  29514. function resolveForwardRef$1(type) {
  29515. var fn = type;
  29516. if (typeof fn === 'function' && fn.hasOwnProperty(__forward_ref__) &&
  29517. fn.__forward_ref__ === forwardRef) {
  29518. return fn();
  29519. }
  29520. else {
  29521. return type;
  29522. }
  29523. }
  29524. /**
  29525. * @license
  29526. * Copyright Google Inc. All Rights Reserved.
  29527. *
  29528. * Use of this source code is governed by an MIT-style license that can be
  29529. * found in the LICENSE file at https://angular.io/license
  29530. */
  29531. var __globalThis = typeof globalThis !== 'undefined' && globalThis;
  29532. var __window$1 = typeof window !== 'undefined' && window;
  29533. var __self$1 = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  29534. self instanceof WorkerGlobalScope && self;
  29535. var __global$1 = typeof global !== 'undefined' && global;
  29536. // Always use __globalThis if available, which is the spec-defined global variable across all
  29537. // environments, then fallback to __global first, because in Node tests both __global and
  29538. // __window may be defined and _global should be __global in that case.
  29539. var _global$1 = __globalThis || __global$1 || __window$1 || __self$1;
  29540. /**
  29541. * @license
  29542. * Copyright Google Inc. All Rights Reserved.
  29543. *
  29544. * Use of this source code is governed by an MIT-style license that can be
  29545. * found in the LICENSE file at https://angular.io/license
  29546. */
  29547. var R3ResolvedDependencyType$1;
  29548. (function (R3ResolvedDependencyType) {
  29549. R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
  29550. R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
  29551. })(R3ResolvedDependencyType$1 || (R3ResolvedDependencyType$1 = {}));
  29552. /**
  29553. * @license
  29554. * Copyright Google Inc. All Rights Reserved.
  29555. *
  29556. * Use of this source code is governed by an MIT-style license that can be
  29557. * found in the LICENSE file at https://angular.io/license
  29558. */
  29559. /**
  29560. * @license
  29561. * Copyright Google Inc. All Rights Reserved.
  29562. *
  29563. * Use of this source code is governed by an MIT-style license that can be
  29564. * found in the LICENSE file at https://angular.io/license
  29565. */
  29566. /**
  29567. * Creates a token that can be used in a DI Provider.
  29568. *
  29569. * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
  29570. * runtime representation) such as when injecting an interface, callable type, array or
  29571. * parameterized type.
  29572. *
  29573. * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
  29574. * the `Injector`. This provides additional level of type safety.
  29575. *
  29576. * ```
  29577. * interface MyInterface {...}
  29578. * var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
  29579. * // myInterface is inferred to be MyInterface.
  29580. * ```
  29581. *
  29582. * When creating an `InjectionToken`, you can optionally specify a factory function which returns
  29583. * (possibly by creating) a default value of the parameterized type `T`. This sets up the
  29584. * `InjectionToken` using this factory as a provider as if it was defined explicitly in the
  29585. * application's root injector. If the factory function, which takes zero arguments, needs to inject
  29586. * dependencies, it can do so using the `inject` function. See below for an example.
  29587. *
  29588. * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
  29589. * overrides the above behavior and marks the token as belonging to a particular `@NgModule`. As
  29590. * mentioned above, `'root'` is the default value for `providedIn`.
  29591. *
  29592. * @usageNotes
  29593. * ### Basic Example
  29594. *
  29595. * ### Plain InjectionToken
  29596. *
  29597. * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
  29598. *
  29599. * ### Tree-shakable InjectionToken
  29600. *
  29601. * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
  29602. *
  29603. *
  29604. * @publicApi
  29605. */
  29606. var InjectionToken = /** @class */ (function () {
  29607. function InjectionToken(_desc, options) {
  29608. this._desc = _desc;
  29609. /** @internal */
  29610. this.ngMetadataName = 'InjectionToken';
  29611. this.ngInjectableDef = undefined;
  29612. if (typeof options == 'number') {
  29613. // This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
  29614. // __NG_ELEMENT_ID__ is Used by Ivy to determine bloom filter id.
  29615. // We are using it to assign `-1` which is used to identify `Injector`.
  29616. this.__NG_ELEMENT_ID__ = options;
  29617. }
  29618. else if (options !== undefined) {
  29619. this.ngInjectableDef = ɵɵdefineInjectable({
  29620. token: this,
  29621. providedIn: options.providedIn || 'root',
  29622. factory: options.factory,
  29623. });
  29624. }
  29625. }
  29626. InjectionToken.prototype.toString = function () { return "InjectionToken " + this._desc; };
  29627. return InjectionToken;
  29628. }());
  29629. /**
  29630. * @license
  29631. * Copyright Google Inc. All Rights Reserved.
  29632. *
  29633. * Use of this source code is governed by an MIT-style license that can be
  29634. * found in the LICENSE file at https://angular.io/license
  29635. */
  29636. /**
  29637. * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
  29638. *
  29639. * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
  29640. * project.
  29641. *
  29642. * @publicApi
  29643. */
  29644. var INJECTOR = new InjectionToken('INJECTOR', -1 // `-1` is used by Ivy DI system as special value to recognize it as `Injector`.
  29645. );
  29646. var _THROW_IF_NOT_FOUND = new Object();
  29647. var THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
  29648. var NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
  29649. var NG_TOKEN_PATH = 'ngTokenPath';
  29650. var NEW_LINE = /\n/gm;
  29651. var NO_NEW_LINE = 'ɵ';
  29652. var SOURCE = '__source';
  29653. var ɵ0$1 = getClosureSafeProperty;
  29654. var USE_VALUE$2 = getClosureSafeProperty({ provide: String, useValue: ɵ0$1 });
  29655. /**
  29656. * Current injector value used by `inject`.
  29657. * - `undefined`: it is an error to call `inject`
  29658. * - `null`: `inject` can be called but there is no injector (limp-mode).
  29659. * - Injector instance: Use the injector for resolution.
  29660. */
  29661. var _currentInjector = undefined;
  29662. function setCurrentInjector(injector) {
  29663. var former = _currentInjector;
  29664. _currentInjector = injector;
  29665. return former;
  29666. }
  29667. /**
  29668. * Current implementation of inject.
  29669. *
  29670. * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
  29671. * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
  29672. * way for two reasons:
  29673. * 1. `Injector` should not depend on ivy logic.
  29674. * 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
  29675. */
  29676. var _injectImplementation;
  29677. /**
  29678. * Sets the current inject implementation.
  29679. */
  29680. function setInjectImplementation(impl) {
  29681. var previous = _injectImplementation;
  29682. _injectImplementation = impl;
  29683. return previous;
  29684. }
  29685. function injectInjectorOnly(token, flags) {
  29686. if (flags === void 0) { flags = InjectFlags.Default; }
  29687. if (_currentInjector === undefined) {
  29688. throw new Error("inject() must be called from an injection context");
  29689. }
  29690. else if (_currentInjector === null) {
  29691. return injectRootLimpMode(token, undefined, flags);
  29692. }
  29693. else {
  29694. return _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
  29695. }
  29696. }
  29697. function ɵɵinject(token, flags) {
  29698. if (flags === void 0) { flags = InjectFlags.Default; }
  29699. return (_injectImplementation || injectInjectorOnly)(token, flags);
  29700. }
  29701. /**
  29702. * Injects `root` tokens in limp mode.
  29703. *
  29704. * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
  29705. * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
  29706. * `InjectableDef`.
  29707. */
  29708. function injectRootLimpMode(token, notFoundValue, flags) {
  29709. var injectableDef = getInjectableDef(token);
  29710. if (injectableDef && injectableDef.providedIn == 'root') {
  29711. return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() :
  29712. injectableDef.value;
  29713. }
  29714. if (flags & InjectFlags.Optional)
  29715. return null;
  29716. if (notFoundValue !== undefined)
  29717. return notFoundValue;
  29718. throw new Error("Injector: NOT_FOUND [" + stringify$1(token) + "]");
  29719. }
  29720. function injectArgs(types) {
  29721. var args = [];
  29722. for (var i = 0; i < types.length; i++) {
  29723. var arg = resolveForwardRef$1(types[i]);
  29724. if (Array.isArray(arg)) {
  29725. if (arg.length === 0) {
  29726. throw new Error('Arguments array must have arguments.');
  29727. }
  29728. var type = undefined;
  29729. var flags = InjectFlags.Default;
  29730. for (var j = 0; j < arg.length; j++) {
  29731. var meta = arg[j];
  29732. if (meta instanceof Optional || meta.ngMetadataName === 'Optional' || meta === Optional) {
  29733. flags |= InjectFlags.Optional;
  29734. }
  29735. else if (meta instanceof SkipSelf || meta.ngMetadataName === 'SkipSelf' || meta === SkipSelf) {
  29736. flags |= InjectFlags.SkipSelf;
  29737. }
  29738. else if (meta instanceof Self || meta.ngMetadataName === 'Self' || meta === Self) {
  29739. flags |= InjectFlags.Self;
  29740. }
  29741. else if (meta instanceof Inject || meta === Inject) {
  29742. type = meta.token;
  29743. }
  29744. else {
  29745. type = meta;
  29746. }
  29747. }
  29748. args.push(ɵɵinject(type, flags));
  29749. }
  29750. else {
  29751. args.push(ɵɵinject(arg));
  29752. }
  29753. }
  29754. return args;
  29755. }
  29756. var NullInjector = /** @class */ (function () {
  29757. function NullInjector() {
  29758. }
  29759. NullInjector.prototype.get = function (token, notFoundValue) {
  29760. if (notFoundValue === void 0) { notFoundValue = THROW_IF_NOT_FOUND; }
  29761. if (notFoundValue === THROW_IF_NOT_FOUND) {
  29762. // Intentionally left behind: With dev tools open the debugger will stop here. There is no
  29763. // reason why correctly written application should cause this exception.
  29764. // TODO(misko): uncomment the next line once `ngDevMode` works with closure.
  29765. // if(ngDevMode) debugger;
  29766. var error = new Error("NullInjectorError: No provider for " + stringify$1(token) + "!");
  29767. error.name = 'NullInjectorError';
  29768. throw error;
  29769. }
  29770. return notFoundValue;
  29771. };
  29772. return NullInjector;
  29773. }());
  29774. function catchInjectorError(e, token, injectorErrorName, source) {
  29775. var tokenPath = e[NG_TEMP_TOKEN_PATH];
  29776. if (token[SOURCE]) {
  29777. tokenPath.unshift(token[SOURCE]);
  29778. }
  29779. e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
  29780. e[NG_TOKEN_PATH] = tokenPath;
  29781. e[NG_TEMP_TOKEN_PATH] = null;
  29782. throw e;
  29783. }
  29784. function formatError(text, obj, injectorErrorName, source) {
  29785. if (source === void 0) { source = null; }
  29786. text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text;
  29787. var context = stringify$1(obj);
  29788. if (obj instanceof Array) {
  29789. context = obj.map(stringify$1).join(' -> ');
  29790. }
  29791. else if (typeof obj === 'object') {
  29792. var parts = [];
  29793. for (var key in obj) {
  29794. if (obj.hasOwnProperty(key)) {
  29795. var value = obj[key];
  29796. parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify$1(value)));
  29797. }
  29798. }
  29799. context = "{" + parts.join(', ') + "}";
  29800. }
  29801. return "" + injectorErrorName + (source ? '(' + source + ')' : '') + "[" + context + "]: " + text.replace(NEW_LINE, '\n ');
  29802. }
  29803. /**
  29804. * @license
  29805. * Copyright Google Inc. All Rights Reserved.
  29806. *
  29807. * Use of this source code is governed by an MIT-style license that can be
  29808. * found in the LICENSE file at https://angular.io/license
  29809. */
  29810. /**
  29811. * @license
  29812. * Copyright Google Inc. All Rights Reserved.
  29813. *
  29814. * Use of this source code is governed by an MIT-style license that can be
  29815. * found in the LICENSE file at https://angular.io/license
  29816. */
  29817. /**
  29818. * @description
  29819. *
  29820. * Represents a type that a Component or other object is instances of.
  29821. *
  29822. * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
  29823. * the `MyCustomComponent` constructor function.
  29824. *
  29825. * @publicApi
  29826. */
  29827. var Type$2 = Function;
  29828. function isType(v) {
  29829. return typeof v === 'function';
  29830. }
  29831. /**
  29832. * @license
  29833. * Copyright Google Inc. All Rights Reserved.
  29834. *
  29835. * Use of this source code is governed by an MIT-style license that can be
  29836. * found in the LICENSE file at https://angular.io/license
  29837. */
  29838. /**
  29839. * Attention: These regex has to hold even if the code is minified!
  29840. */
  29841. var DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/;
  29842. var INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
  29843. var INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
  29844. var INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{\s+super\(\.\.\.arguments\)/;
  29845. /**
  29846. * Determine whether a stringified type is a class which delegates its constructor
  29847. * to its parent.
  29848. *
  29849. * This is not trivial since compiled code can actually contain a constructor function
  29850. * even if the original source code did not. For instance, when the child class contains
  29851. * an initialized instance property.
  29852. */
  29853. function isDelegateCtor(typeStr) {
  29854. return DELEGATE_CTOR.test(typeStr) || INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
  29855. (INHERITED_CLASS.test(typeStr) && !INHERITED_CLASS_WITH_CTOR.test(typeStr));
  29856. }
  29857. var ReflectionCapabilities = /** @class */ (function () {
  29858. function ReflectionCapabilities(reflect) {
  29859. this._reflect = reflect || _global$1['Reflect'];
  29860. }
  29861. ReflectionCapabilities.prototype.isReflectionEnabled = function () { return true; };
  29862. ReflectionCapabilities.prototype.factory = function (t) { return function () {
  29863. var args = [];
  29864. for (var _i = 0; _i < arguments.length; _i++) {
  29865. args[_i] = arguments[_i];
  29866. }
  29867. return new (t.bind.apply(t, __spread([void 0], args)))();
  29868. }; };
  29869. /** @internal */
  29870. ReflectionCapabilities.prototype._zipTypesAndAnnotations = function (paramTypes, paramAnnotations) {
  29871. var result;
  29872. if (typeof paramTypes === 'undefined') {
  29873. result = new Array(paramAnnotations.length);
  29874. }
  29875. else {
  29876. result = new Array(paramTypes.length);
  29877. }
  29878. for (var i = 0; i < result.length; i++) {
  29879. // TS outputs Object for parameters without types, while Traceur omits
  29880. // the annotations. For now we preserve the Traceur behavior to aid
  29881. // migration, but this can be revisited.
  29882. if (typeof paramTypes === 'undefined') {
  29883. result[i] = [];
  29884. }
  29885. else if (paramTypes[i] && paramTypes[i] != Object) {
  29886. result[i] = [paramTypes[i]];
  29887. }
  29888. else {
  29889. result[i] = [];
  29890. }
  29891. if (paramAnnotations && paramAnnotations[i] != null) {
  29892. result[i] = result[i].concat(paramAnnotations[i]);
  29893. }
  29894. }
  29895. return result;
  29896. };
  29897. ReflectionCapabilities.prototype._ownParameters = function (type, parentCtor) {
  29898. var typeStr = type.toString();
  29899. // If we have no decorators, we only have function.length as metadata.
  29900. // In that case, to detect whether a child class declared an own constructor or not,
  29901. // we need to look inside of that constructor to check whether it is
  29902. // just calling the parent.
  29903. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
  29904. // that sets 'design:paramtypes' to []
  29905. // if a class inherits from another class but has no ctor declared itself.
  29906. if (isDelegateCtor(typeStr)) {
  29907. return null;
  29908. }
  29909. // Prefer the direct API.
  29910. if (type.parameters && type.parameters !== parentCtor.parameters) {
  29911. return type.parameters;
  29912. }
  29913. // API of tsickle for lowering decorators to properties on the class.
  29914. var tsickleCtorParams = type.ctorParameters;
  29915. if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
  29916. // Newer tsickle uses a function closure
  29917. // Retain the non-function case for compatibility with older tsickle
  29918. var ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
  29919. var paramTypes_1 = ctorParameters.map(function (ctorParam) { return ctorParam && ctorParam.type; });
  29920. var paramAnnotations_1 = ctorParameters.map(function (ctorParam) {
  29921. return ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators);
  29922. });
  29923. return this._zipTypesAndAnnotations(paramTypes_1, paramAnnotations_1);
  29924. }
  29925. // API for metadata created by invoking the decorators.
  29926. var paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
  29927. var paramTypes = this._reflect && this._reflect.getOwnMetadata &&
  29928. this._reflect.getOwnMetadata('design:paramtypes', type);
  29929. if (paramTypes || paramAnnotations) {
  29930. return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
  29931. }
  29932. // If a class has no decorators, at least create metadata
  29933. // based on function.length.
  29934. // Note: We know that this is a real constructor as we checked
  29935. // the content of the constructor above.
  29936. return new Array(type.length).fill(undefined);
  29937. };
  29938. ReflectionCapabilities.prototype.parameters = function (type) {
  29939. // Note: only report metadata if we have at least one class decorator
  29940. // to stay in sync with the static reflector.
  29941. if (!isType(type)) {
  29942. return [];
  29943. }
  29944. var parentCtor = getParentCtor(type);
  29945. var parameters = this._ownParameters(type, parentCtor);
  29946. if (!parameters && parentCtor !== Object) {
  29947. parameters = this.parameters(parentCtor);
  29948. }
  29949. return parameters || [];
  29950. };
  29951. ReflectionCapabilities.prototype._ownAnnotations = function (typeOrFunc, parentCtor) {
  29952. // Prefer the direct API.
  29953. if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
  29954. var annotations = typeOrFunc.annotations;
  29955. if (typeof annotations === 'function' && annotations.annotations) {
  29956. annotations = annotations.annotations;
  29957. }
  29958. return annotations;
  29959. }
  29960. // API of tsickle for lowering decorators to properties on the class.
  29961. if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
  29962. return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
  29963. }
  29964. // API for metadata created by invoking the decorators.
  29965. if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
  29966. return typeOrFunc[ANNOTATIONS];
  29967. }
  29968. return null;
  29969. };
  29970. ReflectionCapabilities.prototype.annotations = function (typeOrFunc) {
  29971. if (!isType(typeOrFunc)) {
  29972. return [];
  29973. }
  29974. var parentCtor = getParentCtor(typeOrFunc);
  29975. var ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
  29976. var parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
  29977. return parentAnnotations.concat(ownAnnotations);
  29978. };
  29979. ReflectionCapabilities.prototype._ownPropMetadata = function (typeOrFunc, parentCtor) {
  29980. // Prefer the direct API.
  29981. if (typeOrFunc.propMetadata &&
  29982. typeOrFunc.propMetadata !== parentCtor.propMetadata) {
  29983. var propMetadata = typeOrFunc.propMetadata;
  29984. if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
  29985. propMetadata = propMetadata.propMetadata;
  29986. }
  29987. return propMetadata;
  29988. }
  29989. // API of tsickle for lowering decorators to properties on the class.
  29990. if (typeOrFunc.propDecorators &&
  29991. typeOrFunc.propDecorators !== parentCtor.propDecorators) {
  29992. var propDecorators_1 = typeOrFunc.propDecorators;
  29993. var propMetadata_1 = {};
  29994. Object.keys(propDecorators_1).forEach(function (prop) {
  29995. propMetadata_1[prop] = convertTsickleDecoratorIntoMetadata(propDecorators_1[prop]);
  29996. });
  29997. return propMetadata_1;
  29998. }
  29999. // API for metadata created by invoking the decorators.
  30000. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
  30001. return typeOrFunc[PROP_METADATA];
  30002. }
  30003. return null;
  30004. };
  30005. ReflectionCapabilities.prototype.propMetadata = function (typeOrFunc) {
  30006. if (!isType(typeOrFunc)) {
  30007. return {};
  30008. }
  30009. var parentCtor = getParentCtor(typeOrFunc);
  30010. var propMetadata = {};
  30011. if (parentCtor !== Object) {
  30012. var parentPropMetadata_1 = this.propMetadata(parentCtor);
  30013. Object.keys(parentPropMetadata_1).forEach(function (propName) {
  30014. propMetadata[propName] = parentPropMetadata_1[propName];
  30015. });
  30016. }
  30017. var ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
  30018. if (ownPropMetadata) {
  30019. Object.keys(ownPropMetadata).forEach(function (propName) {
  30020. var decorators = [];
  30021. if (propMetadata.hasOwnProperty(propName)) {
  30022. decorators.push.apply(decorators, __spread(propMetadata[propName]));
  30023. }
  30024. decorators.push.apply(decorators, __spread(ownPropMetadata[propName]));
  30025. propMetadata[propName] = decorators;
  30026. });
  30027. }
  30028. return propMetadata;
  30029. };
  30030. ReflectionCapabilities.prototype.ownPropMetadata = function (typeOrFunc) {
  30031. if (!isType(typeOrFunc)) {
  30032. return {};
  30033. }
  30034. return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
  30035. };
  30036. ReflectionCapabilities.prototype.hasLifecycleHook = function (type, lcProperty) {
  30037. return type instanceof Type$2 && lcProperty in type.prototype;
  30038. };
  30039. ReflectionCapabilities.prototype.guards = function (type) { return {}; };
  30040. ReflectionCapabilities.prototype.getter = function (name) { return new Function('o', 'return o.' + name + ';'); };
  30041. ReflectionCapabilities.prototype.setter = function (name) {
  30042. return new Function('o', 'v', 'return o.' + name + ' = v;');
  30043. };
  30044. ReflectionCapabilities.prototype.method = function (name) {
  30045. var functionBody = "if (!o." + name + ") throw new Error('\"" + name + "\" is undefined');\n return o." + name + ".apply(o, args);";
  30046. return new Function('o', 'args', functionBody);
  30047. };
  30048. // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
  30049. ReflectionCapabilities.prototype.importUri = function (type) {
  30050. // StaticSymbol
  30051. if (typeof type === 'object' && type['filePath']) {
  30052. return type['filePath'];
  30053. }
  30054. // Runtime type
  30055. return "./" + stringify$1(type);
  30056. };
  30057. ReflectionCapabilities.prototype.resourceUri = function (type) { return "./" + stringify$1(type); };
  30058. ReflectionCapabilities.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
  30059. return runtime;
  30060. };
  30061. ReflectionCapabilities.prototype.resolveEnum = function (enumIdentifier, name) { return enumIdentifier[name]; };
  30062. return ReflectionCapabilities;
  30063. }());
  30064. function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
  30065. if (!decoratorInvocations) {
  30066. return [];
  30067. }
  30068. return decoratorInvocations.map(function (decoratorInvocation) {
  30069. var decoratorType = decoratorInvocation.type;
  30070. var annotationCls = decoratorType.annotationCls;
  30071. var annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
  30072. return new (annotationCls.bind.apply(annotationCls, __spread([void 0], annotationArgs)))();
  30073. });
  30074. }
  30075. function getParentCtor(ctor) {
  30076. var parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
  30077. var parentCtor = parentProto ? parentProto.constructor : null;
  30078. // Note: We always use `Object` as the null value
  30079. // to simplify checking later on.
  30080. return parentCtor || Object;
  30081. }
  30082. /**
  30083. * @license
  30084. * Copyright Google Inc. All Rights Reserved.
  30085. *
  30086. * Use of this source code is governed by an MIT-style license that can be
  30087. * found in the LICENSE file at https://angular.io/license
  30088. */
  30089. /**
  30090. * @license
  30091. * Copyright Google Inc. All Rights Reserved.
  30092. *
  30093. * Use of this source code is governed by an MIT-style license that can be
  30094. * found in the LICENSE file at https://angular.io/license
  30095. */
  30096. var ɵ0$2 = getClosureSafeProperty;
  30097. var USE_VALUE$3 = getClosureSafeProperty({ provide: String, useValue: ɵ0$2 });
  30098. /**
  30099. * @license
  30100. * Copyright Google Inc. All Rights Reserved.
  30101. *
  30102. * Use of this source code is governed by an MIT-style license that can be
  30103. * found in the LICENSE file at https://angular.io/license
  30104. */
  30105. var ɵ0$3 = getClosureSafeProperty;
  30106. var USE_VALUE$4 = getClosureSafeProperty({ provide: String, useValue: ɵ0$3 });
  30107. var EMPTY_ARRAY$1 = [];
  30108. function convertInjectableProviderToFactory(type, provider) {
  30109. if (!provider) {
  30110. var reflectionCapabilities = new ReflectionCapabilities();
  30111. var deps_1 = reflectionCapabilities.parameters(type);
  30112. // TODO - convert to flags.
  30113. return function () { return new (type.bind.apply(type, __spread([void 0], injectArgs(deps_1))))(); };
  30114. }
  30115. if (USE_VALUE$4 in provider) {
  30116. var valueProvider_1 = provider;
  30117. return function () { return valueProvider_1.useValue; };
  30118. }
  30119. else if (provider.useExisting) {
  30120. var existingProvider_1 = provider;
  30121. return function () { return ɵɵinject(existingProvider_1.useExisting); };
  30122. }
  30123. else if (provider.useFactory) {
  30124. var factoryProvider_1 = provider;
  30125. return function () { return factoryProvider_1.useFactory.apply(factoryProvider_1, __spread(injectArgs(factoryProvider_1.deps || EMPTY_ARRAY$1))); };
  30126. }
  30127. else if (provider.useClass) {
  30128. var classProvider_1 = provider;
  30129. var deps_2 = provider.deps;
  30130. if (!deps_2) {
  30131. var reflectionCapabilities = new ReflectionCapabilities();
  30132. deps_2 = reflectionCapabilities.parameters(type);
  30133. }
  30134. return function () {
  30135. var _a;
  30136. return new ((_a = classProvider_1.useClass).bind.apply(_a, __spread([void 0], injectArgs(deps_2))))();
  30137. };
  30138. }
  30139. else {
  30140. var deps_3 = provider.deps;
  30141. if (!deps_3) {
  30142. var reflectionCapabilities = new ReflectionCapabilities();
  30143. deps_3 = reflectionCapabilities.parameters(type);
  30144. }
  30145. return function () { return new (type.bind.apply(type, __spread([void 0], injectArgs(deps_3))))(); };
  30146. }
  30147. }
  30148. /**
  30149. * @license
  30150. * Copyright Google Inc. All Rights Reserved.
  30151. *
  30152. * Use of this source code is governed by an MIT-style license that can be
  30153. * found in the LICENSE file at https://angular.io/license
  30154. */
  30155. var ɵ0$4 = function (type, meta) { return SWITCH_COMPILE_INJECTABLE(type, meta); };
  30156. /**
  30157. * Injectable decorator and metadata.
  30158. *
  30159. * @Annotation
  30160. * @publicApi
  30161. */
  30162. var Injectable = makeDecorator('Injectable', undefined, undefined, undefined, ɵ0$4);
  30163. /**
  30164. * Supports @Injectable() in JIT mode for Render2.
  30165. */
  30166. function render2CompileInjectable(injectableType, options) {
  30167. if (options && options.providedIn !== undefined && !getInjectableDef(injectableType)) {
  30168. injectableType.ngInjectableDef = ɵɵdefineInjectable({
  30169. token: injectableType,
  30170. providedIn: options.providedIn,
  30171. factory: convertInjectableProviderToFactory(injectableType, options),
  30172. });
  30173. }
  30174. }
  30175. var SWITCH_COMPILE_INJECTABLE__PRE_R3__ = render2CompileInjectable;
  30176. var SWITCH_COMPILE_INJECTABLE = SWITCH_COMPILE_INJECTABLE__PRE_R3__;
  30177. /**
  30178. * @license
  30179. * Copyright Google Inc. All Rights Reserved.
  30180. *
  30181. * Use of this source code is governed by an MIT-style license that can be
  30182. * found in the LICENSE file at https://angular.io/license
  30183. */
  30184. function ngDevModeResetPerfCounters() {
  30185. var locationString = typeof location !== 'undefined' ? location.toString() : '';
  30186. var newCounters = {
  30187. namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,
  30188. firstTemplatePass: 0,
  30189. tNode: 0,
  30190. tView: 0,
  30191. rendererCreateTextNode: 0,
  30192. rendererSetText: 0,
  30193. rendererCreateElement: 0,
  30194. rendererAddEventListener: 0,
  30195. rendererSetAttribute: 0,
  30196. rendererRemoveAttribute: 0,
  30197. rendererSetProperty: 0,
  30198. rendererSetClassName: 0,
  30199. rendererAddClass: 0,
  30200. rendererRemoveClass: 0,
  30201. rendererSetStyle: 0,
  30202. rendererRemoveStyle: 0,
  30203. rendererDestroy: 0,
  30204. rendererDestroyNode: 0,
  30205. rendererMoveNode: 0,
  30206. rendererRemoveNode: 0,
  30207. rendererAppendChild: 0,
  30208. rendererInsertBefore: 0,
  30209. rendererCreateComment: 0,
  30210. styleMap: 0,
  30211. styleMapCacheMiss: 0,
  30212. classMap: 0,
  30213. classMapCacheMiss: 0,
  30214. stylingProp: 0,
  30215. stylingPropCacheMiss: 0,
  30216. stylingApply: 0,
  30217. stylingApplyCacheMiss: 0,
  30218. };
  30219. // Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
  30220. var allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;
  30221. _global$1['ngDevMode'] = allowNgDevModeTrue && newCounters;
  30222. return newCounters;
  30223. }
  30224. /**
  30225. * This checks to see if the `ngDevMode` has been set. If yes,
  30226. * then we honor it, otherwise we default to dev mode with additional checks.
  30227. *
  30228. * The idea is that unless we are doing production build where we explicitly
  30229. * set `ngDevMode == false` we should be helping the developer by providing
  30230. * as much early warning and errors as possible.
  30231. *
  30232. * NOTE: changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.
  30233. */
  30234. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  30235. ngDevModeResetPerfCounters();
  30236. }
  30237. /** Called when directives inject each other (creating a circular dependency) */
  30238. function throwCyclicDependencyError(token) {
  30239. throw new Error("Cannot instantiate cyclic dependency! " + token);
  30240. }
  30241. function throwMixedMultiProviderError() {
  30242. throw new Error("Cannot mix multi providers and regular providers");
  30243. }
  30244. function throwInvalidProviderError(ngModuleType, providers, provider) {
  30245. var ngModuleDetail = '';
  30246. if (ngModuleType && providers) {
  30247. var providerDetail = providers.map(function (v) { return v == provider ? '?' + provider + '?' : '...'; });
  30248. ngModuleDetail =
  30249. " - only instances of Provider and Type are allowed, got: [" + providerDetail.join(', ') + "]";
  30250. }
  30251. throw new Error("Invalid provider for the NgModule '" + stringify$1(ngModuleType) + "'" + ngModuleDetail);
  30252. }
  30253. /**
  30254. * @license
  30255. * Copyright Google Inc. All Rights Reserved.
  30256. *
  30257. * Use of this source code is governed by an MIT-style license that can be
  30258. * found in the LICENSE file at https://angular.io/license
  30259. */
  30260. /**
  30261. * An internal token whose presence in an injector indicates that the injector should treat itself
  30262. * as a root scoped injector when processing requests for unknown tokens which may indicate
  30263. * they are provided in the root scope.
  30264. */
  30265. var APP_ROOT = new InjectionToken('The presence of this token marks an injector as being the root injector.');
  30266. /**
  30267. * @license
  30268. * Copyright Google Inc. All Rights Reserved.
  30269. *
  30270. * Use of this source code is governed by an MIT-style license that can be
  30271. * found in the LICENSE file at https://angular.io/license
  30272. */
  30273. /**
  30274. * Marker which indicates that a value has not yet been created from the factory function.
  30275. */
  30276. var NOT_YET = {};
  30277. /**
  30278. * Marker which indicates that the factory function for a token is in the process of being called.
  30279. *
  30280. * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
  30281. * injection of a dependency has recursively attempted to inject the original token, and there is
  30282. * a circular dependency among the providers.
  30283. */
  30284. var CIRCULAR = {};
  30285. var EMPTY_ARRAY$2 = [];
  30286. /**
  30287. * A lazily initialized NullInjector.
  30288. */
  30289. var NULL_INJECTOR = undefined;
  30290. function getNullInjector() {
  30291. if (NULL_INJECTOR === undefined) {
  30292. NULL_INJECTOR = new NullInjector();
  30293. }
  30294. return NULL_INJECTOR;
  30295. }
  30296. /**
  30297. * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
  30298. *
  30299. * @publicApi
  30300. */
  30301. function createInjector(defType, parent, additionalProviders, name) {
  30302. if (parent === void 0) { parent = null; }
  30303. if (additionalProviders === void 0) { additionalProviders = null; }
  30304. parent = parent || getNullInjector();
  30305. return new R3Injector(defType, additionalProviders, parent, name);
  30306. }
  30307. var R3Injector = /** @class */ (function () {
  30308. function R3Injector(def, additionalProviders, parent, source) {
  30309. var _this = this;
  30310. if (source === void 0) { source = null; }
  30311. this.parent = parent;
  30312. /**
  30313. * Map of tokens to records which contain the instances of those tokens.
  30314. */
  30315. this.records = new Map();
  30316. /**
  30317. * The transitive set of `InjectorType`s which define this injector.
  30318. */
  30319. this.injectorDefTypes = new Set();
  30320. /**
  30321. * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
  30322. */
  30323. this.onDestroy = new Set();
  30324. this._destroyed = false;
  30325. // Start off by creating Records for every provider declared in every InjectorType
  30326. // included transitively in `def`.
  30327. var dedupStack = [];
  30328. deepForEach([def], function (injectorDef) { return _this.processInjectorType(injectorDef, [], dedupStack); });
  30329. additionalProviders && deepForEach(additionalProviders, function (provider) { return _this.processProvider(provider, def, additionalProviders); });
  30330. // Make sure the INJECTOR token provides this injector.
  30331. this.records.set(INJECTOR, makeRecord(undefined, this));
  30332. // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
  30333. // any injectable scoped to APP_ROOT_SCOPE.
  30334. this.isRootInjector = this.records.has(APP_ROOT);
  30335. // Eagerly instantiate the InjectorType classes themselves.
  30336. this.injectorDefTypes.forEach(function (defType) { return _this.get(defType); });
  30337. // Source name, used for debugging
  30338. this.source = source || (typeof def === 'object' ? null : stringify$1(def));
  30339. }
  30340. Object.defineProperty(R3Injector.prototype, "destroyed", {
  30341. /**
  30342. * Flag indicating that this injector was previously destroyed.
  30343. */
  30344. get: function () { return this._destroyed; },
  30345. enumerable: true,
  30346. configurable: true
  30347. });
  30348. /**
  30349. * Destroy the injector and release references to every instance or provider associated with it.
  30350. *
  30351. * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
  30352. * hook was found.
  30353. */
  30354. R3Injector.prototype.destroy = function () {
  30355. this.assertNotDestroyed();
  30356. // Set destroyed = true first, in case lifecycle hooks re-enter destroy().
  30357. this._destroyed = true;
  30358. try {
  30359. // Call all the lifecycle hooks.
  30360. this.onDestroy.forEach(function (service) { return service.ngOnDestroy(); });
  30361. }
  30362. finally {
  30363. // Release all references.
  30364. this.records.clear();
  30365. this.onDestroy.clear();
  30366. this.injectorDefTypes.clear();
  30367. }
  30368. };
  30369. R3Injector.prototype.get = function (token, notFoundValue, flags) {
  30370. if (notFoundValue === void 0) { notFoundValue = THROW_IF_NOT_FOUND; }
  30371. if (flags === void 0) { flags = InjectFlags.Default; }
  30372. this.assertNotDestroyed();
  30373. // Set the injection context.
  30374. var previousInjector = setCurrentInjector(this);
  30375. try {
  30376. // Check for the SkipSelf flag.
  30377. if (!(flags & InjectFlags.SkipSelf)) {
  30378. // SkipSelf isn't set, check if the record belongs to this injector.
  30379. var record = this.records.get(token);
  30380. if (record === undefined) {
  30381. // No record, but maybe the token is scoped to this injector. Look for an ngInjectableDef
  30382. // with a scope matching this injector.
  30383. var def = couldBeInjectableType(token) && getInjectableDef(token);
  30384. if (def && this.injectableDefInScope(def)) {
  30385. // Found an ngInjectableDef and it's scoped to this injector. Pretend as if it was here
  30386. // all along.
  30387. record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
  30388. this.records.set(token, record);
  30389. }
  30390. }
  30391. // If a record was found, get the instance for it and return it.
  30392. if (record !== undefined) {
  30393. return this.hydrate(token, record);
  30394. }
  30395. }
  30396. // Select the next injector based on the Self flag - if self is set, the next injector is
  30397. // the NullInjector, otherwise it's the parent.
  30398. var nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
  30399. return nextInjector.get(token, flags & InjectFlags.Optional ? null : notFoundValue);
  30400. }
  30401. catch (e) {
  30402. if (e.name === 'NullInjectorError') {
  30403. var path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
  30404. path.unshift(stringify$1(token));
  30405. if (previousInjector) {
  30406. // We still have a parent injector, keep throwing
  30407. throw e;
  30408. }
  30409. else {
  30410. // Format & throw the final error message when we don't have any previous injector
  30411. return catchInjectorError(e, token, 'R3InjectorError', this.source);
  30412. }
  30413. }
  30414. else {
  30415. throw e;
  30416. }
  30417. }
  30418. finally {
  30419. // Lastly, clean up the state by restoring the previous injector.
  30420. setCurrentInjector(previousInjector);
  30421. }
  30422. };
  30423. R3Injector.prototype.toString = function () {
  30424. var tokens = [], records = this.records;
  30425. records.forEach(function (v, token) { return tokens.push(stringify$1(token)); });
  30426. return "R3Injector[" + tokens.join(', ') + "]";
  30427. };
  30428. R3Injector.prototype.assertNotDestroyed = function () {
  30429. if (this._destroyed) {
  30430. throw new Error('Injector has already been destroyed.');
  30431. }
  30432. };
  30433. /**
  30434. * Add an `InjectorType` or `InjectorTypeWithProviders` and all of its transitive providers
  30435. * to this injector.
  30436. *
  30437. * If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
  30438. * the function will return "true" to indicate that the providers of the type definition need
  30439. * to be processed. This allows us to process providers of injector types after all imports of
  30440. * an injector definition are processed. (following View Engine semantics: see FW-1349)
  30441. */
  30442. R3Injector.prototype.processInjectorType = function (defOrWrappedDef, parents, dedupStack) {
  30443. var _this = this;
  30444. defOrWrappedDef = resolveForwardRef$1(defOrWrappedDef);
  30445. if (!defOrWrappedDef)
  30446. return false;
  30447. // Either the defOrWrappedDef is an InjectorType (with ngInjectorDef) or an
  30448. // InjectorDefTypeWithProviders (aka ModuleWithProviders). Detecting either is a megamorphic
  30449. // read, so care is taken to only do the read once.
  30450. // First attempt to read the ngInjectorDef.
  30451. var def = getInjectorDef(defOrWrappedDef);
  30452. // If that's not present, then attempt to read ngModule from the InjectorDefTypeWithProviders.
  30453. var ngModule = (def == null) && defOrWrappedDef.ngModule || undefined;
  30454. // Determine the InjectorType. In the case where `defOrWrappedDef` is an `InjectorType`,
  30455. // then this is easy. In the case of an InjectorDefTypeWithProviders, then the definition type
  30456. // is the `ngModule`.
  30457. var defType = (ngModule === undefined) ? defOrWrappedDef : ngModule;
  30458. // Check for circular dependencies.
  30459. if (ngDevMode && parents.indexOf(defType) !== -1) {
  30460. var defName = stringify$1(defType);
  30461. throw new Error("Circular dependency in DI detected for type " + defName + ". Dependency path: " + parents.map(function (defType) { return stringify$1(defType); }).join(' > ') + " > " + defName + ".");
  30462. }
  30463. // Check for multiple imports of the same module
  30464. var isDuplicate = dedupStack.indexOf(defType) !== -1;
  30465. // Finally, if defOrWrappedType was an `InjectorDefTypeWithProviders`, then the actual
  30466. // `InjectorDef` is on its `ngModule`.
  30467. if (ngModule !== undefined) {
  30468. def = getInjectorDef(ngModule);
  30469. }
  30470. // If no definition was found, it might be from exports. Remove it.
  30471. if (def == null) {
  30472. return false;
  30473. }
  30474. // Track the InjectorType and add a provider for it.
  30475. this.injectorDefTypes.add(defType);
  30476. this.records.set(defType, makeRecord(def.factory, NOT_YET));
  30477. // Add providers in the same way that @NgModule resolution did:
  30478. // First, include providers from any imports.
  30479. if (def.imports != null && !isDuplicate) {
  30480. // Before processing defType's imports, add it to the set of parents. This way, if it ends
  30481. // up deeply importing itself, this can be detected.
  30482. ngDevMode && parents.push(defType);
  30483. // Add it to the set of dedups. This way we can detect multiple imports of the same module
  30484. dedupStack.push(defType);
  30485. var importTypesWithProviders_1;
  30486. try {
  30487. deepForEach(def.imports, function (imported) {
  30488. if (_this.processInjectorType(imported, parents, dedupStack)) {
  30489. if (importTypesWithProviders_1 === undefined)
  30490. importTypesWithProviders_1 = [];
  30491. // If the processed import is an injector type with providers, we store it in the
  30492. // list of import types with providers, so that we can process those afterwards.
  30493. importTypesWithProviders_1.push(imported);
  30494. }
  30495. });
  30496. }
  30497. finally {
  30498. // Remove it from the parents set when finished.
  30499. ngDevMode && parents.pop();
  30500. }
  30501. // Imports which are declared with providers (TypeWithProviders) need to be processed
  30502. // after all imported modules are processed. This is similar to how View Engine
  30503. // processes/merges module imports in the metadata resolver. See: FW-1349.
  30504. if (importTypesWithProviders_1 !== undefined) {
  30505. var _loop_1 = function (i) {
  30506. var _a = importTypesWithProviders_1[i], ngModule_1 = _a.ngModule, providers = _a.providers;
  30507. deepForEach(providers, function (provider) { return _this.processProvider(provider, ngModule_1, providers || EMPTY_ARRAY$2); });
  30508. };
  30509. for (var i = 0; i < importTypesWithProviders_1.length; i++) {
  30510. _loop_1(i);
  30511. }
  30512. }
  30513. }
  30514. // Next, include providers listed on the definition itself.
  30515. var defProviders = def.providers;
  30516. if (defProviders != null && !isDuplicate) {
  30517. var injectorType_1 = defOrWrappedDef;
  30518. deepForEach(defProviders, function (provider) { return _this.processProvider(provider, injectorType_1, defProviders); });
  30519. }
  30520. return (ngModule !== undefined &&
  30521. defOrWrappedDef.providers !== undefined);
  30522. };
  30523. /**
  30524. * Process a `SingleProvider` and add it.
  30525. */
  30526. R3Injector.prototype.processProvider = function (provider, ngModuleType, providers) {
  30527. // Determine the token from the provider. Either it's its own token, or has a {provide: ...}
  30528. // property.
  30529. provider = resolveForwardRef$1(provider);
  30530. var token = isTypeProvider(provider) ? provider : resolveForwardRef$1(provider && provider.provide);
  30531. // Construct a `Record` for the provider.
  30532. var record = providerToRecord(provider, ngModuleType, providers);
  30533. if (!isTypeProvider(provider) && provider.multi === true) {
  30534. // If the provider indicates that it's a multi-provider, process it specially.
  30535. // First check whether it's been defined already.
  30536. var multiRecord_1 = this.records.get(token);
  30537. if (multiRecord_1) {
  30538. // It has. Throw a nice error if
  30539. if (multiRecord_1.multi === undefined) {
  30540. throwMixedMultiProviderError();
  30541. }
  30542. }
  30543. else {
  30544. multiRecord_1 = makeRecord(undefined, NOT_YET, true);
  30545. multiRecord_1.factory = function () { return injectArgs(multiRecord_1.multi); };
  30546. this.records.set(token, multiRecord_1);
  30547. }
  30548. token = provider;
  30549. multiRecord_1.multi.push(provider);
  30550. }
  30551. else {
  30552. var existing = this.records.get(token);
  30553. if (existing && existing.multi !== undefined) {
  30554. throwMixedMultiProviderError();
  30555. }
  30556. }
  30557. this.records.set(token, record);
  30558. };
  30559. R3Injector.prototype.hydrate = function (token, record) {
  30560. if (record.value === CIRCULAR) {
  30561. throwCyclicDependencyError(stringify$1(token));
  30562. }
  30563. else if (record.value === NOT_YET) {
  30564. record.value = CIRCULAR;
  30565. record.value = record.factory();
  30566. }
  30567. if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
  30568. this.onDestroy.add(record.value);
  30569. }
  30570. return record.value;
  30571. };
  30572. R3Injector.prototype.injectableDefInScope = function (def) {
  30573. if (!def.providedIn) {
  30574. return false;
  30575. }
  30576. else if (typeof def.providedIn === 'string') {
  30577. return def.providedIn === 'any' || (def.providedIn === 'root' && this.isRootInjector);
  30578. }
  30579. else {
  30580. return this.injectorDefTypes.has(def.providedIn);
  30581. }
  30582. };
  30583. return R3Injector;
  30584. }());
  30585. function injectableDefOrInjectorDefFactory(token) {
  30586. // Most tokens will have an ngInjectableDef directly on them, which specifies a factory directly.
  30587. var injectableDef = getInjectableDef(token);
  30588. if (injectableDef !== null) {
  30589. return injectableDef.factory;
  30590. }
  30591. // If the token is an NgModule, it's also injectable but the factory is on its ngInjectorDef.
  30592. var injectorDef = getInjectorDef(token);
  30593. if (injectorDef !== null) {
  30594. return injectorDef.factory;
  30595. }
  30596. // InjectionTokens should have an ngInjectableDef and thus should be handled above.
  30597. // If it's missing that, it's an error.
  30598. if (token instanceof InjectionToken) {
  30599. throw new Error("Token " + stringify$1(token) + " is missing an ngInjectableDef definition.");
  30600. }
  30601. // Undecorated types can sometimes be created if they have no constructor arguments.
  30602. if (token instanceof Function) {
  30603. return getUndecoratedInjectableFactory(token);
  30604. }
  30605. // There was no way to resolve a factory for this token.
  30606. throw new Error('unreachable');
  30607. }
  30608. function getUndecoratedInjectableFactory(token) {
  30609. // If the token has parameters then it has dependencies that we cannot resolve implicitly.
  30610. var paramLength = token.length;
  30611. if (paramLength > 0) {
  30612. var args = new Array(paramLength).fill('?');
  30613. throw new Error("Can't resolve all parameters for " + stringify$1(token) + ": (" + args.join(', ') + ").");
  30614. }
  30615. // The constructor function appears to have no parameters.
  30616. // This might be because it inherits from a super-class. In which case, use an ngInjectableDef
  30617. // from an ancestor if there is one.
  30618. // Otherwise this really is a simple class with no dependencies, so return a factory that
  30619. // just instantiates the zero-arg constructor.
  30620. var inheritedInjectableDef = getInheritedInjectableDef(token);
  30621. if (inheritedInjectableDef !== null) {
  30622. return function () { return inheritedInjectableDef.factory(token); };
  30623. }
  30624. else {
  30625. return function () { return new token(); };
  30626. }
  30627. }
  30628. function providerToRecord(provider, ngModuleType, providers) {
  30629. var factory = providerToFactory(provider, ngModuleType, providers);
  30630. if (isValueProvider(provider)) {
  30631. return makeRecord(undefined, provider.useValue);
  30632. }
  30633. else {
  30634. return makeRecord(factory, NOT_YET);
  30635. }
  30636. }
  30637. /**
  30638. * Converts a `SingleProvider` into a factory function.
  30639. *
  30640. * @param provider provider to convert to factory
  30641. */
  30642. function providerToFactory(provider, ngModuleType, providers) {
  30643. var factory = undefined;
  30644. if (isTypeProvider(provider)) {
  30645. return injectableDefOrInjectorDefFactory(resolveForwardRef$1(provider));
  30646. }
  30647. else {
  30648. if (isValueProvider(provider)) {
  30649. factory = function () { return resolveForwardRef$1(provider.useValue); };
  30650. }
  30651. else if (isExistingProvider(provider)) {
  30652. factory = function () { return ɵɵinject(resolveForwardRef$1(provider.useExisting)); };
  30653. }
  30654. else if (isFactoryProvider(provider)) {
  30655. factory = function () { return provider.useFactory.apply(provider, __spread(injectArgs(provider.deps || []))); };
  30656. }
  30657. else {
  30658. var classRef_1 = resolveForwardRef$1(provider &&
  30659. (provider.useClass || provider.provide));
  30660. if (!classRef_1) {
  30661. throwInvalidProviderError(ngModuleType, providers, provider);
  30662. }
  30663. if (hasDeps(provider)) {
  30664. factory = function () { return new ((classRef_1).bind.apply((classRef_1), __spread([void 0], injectArgs(provider.deps))))(); };
  30665. }
  30666. else {
  30667. return injectableDefOrInjectorDefFactory(classRef_1);
  30668. }
  30669. }
  30670. }
  30671. return factory;
  30672. }
  30673. function makeRecord(factory, value, multi) {
  30674. if (multi === void 0) { multi = false; }
  30675. return {
  30676. factory: factory,
  30677. value: value,
  30678. multi: multi ? [] : undefined,
  30679. };
  30680. }
  30681. function deepForEach(input, fn) {
  30682. input.forEach(function (value) { return Array.isArray(value) ? deepForEach(value, fn) : fn(value); });
  30683. }
  30684. function isValueProvider(value) {
  30685. return value !== null && typeof value == 'object' && USE_VALUE$2 in value;
  30686. }
  30687. function isExistingProvider(value) {
  30688. return !!(value && value.useExisting);
  30689. }
  30690. function isFactoryProvider(value) {
  30691. return !!(value && value.useFactory);
  30692. }
  30693. function isTypeProvider(value) {
  30694. return typeof value === 'function';
  30695. }
  30696. function hasDeps(value) {
  30697. return !!value.deps;
  30698. }
  30699. function hasOnDestroy(value) {
  30700. return value !== null && typeof value === 'object' &&
  30701. typeof value.ngOnDestroy === 'function';
  30702. }
  30703. function couldBeInjectableType(value) {
  30704. return (typeof value === 'function') ||
  30705. (typeof value === 'object' && value instanceof InjectionToken);
  30706. }
  30707. /**
  30708. * @license
  30709. * Copyright Google Inc. All Rights Reserved.
  30710. *
  30711. * Use of this source code is governed by an MIT-style license that can be
  30712. * found in the LICENSE file at https://angular.io/license
  30713. */
  30714. function INJECTOR_IMPL__PRE_R3__(providers, parent, name) {
  30715. return new StaticInjector(providers, parent, name);
  30716. }
  30717. var INJECTOR_IMPL = INJECTOR_IMPL__PRE_R3__;
  30718. /**
  30719. * Concrete injectors implement this interface.
  30720. *
  30721. * For more details, see the ["Dependency Injection Guide"](guide/dependency-injection).
  30722. *
  30723. * @usageNotes
  30724. * ### Example
  30725. *
  30726. * {@example core/di/ts/injector_spec.ts region='Injector'}
  30727. *
  30728. * `Injector` returns itself when given `Injector` as a token:
  30729. *
  30730. * {@example core/di/ts/injector_spec.ts region='injectInjector'}
  30731. *
  30732. * @publicApi
  30733. */
  30734. var Injector = /** @class */ (function () {
  30735. function Injector() {
  30736. }
  30737. /**
  30738. * Create a new Injector which is configure using `StaticProvider`s.
  30739. *
  30740. * @usageNotes
  30741. * ### Example
  30742. *
  30743. * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
  30744. */
  30745. Injector.create = function (options, parent) {
  30746. if (Array.isArray(options)) {
  30747. return INJECTOR_IMPL(options, parent, '');
  30748. }
  30749. else {
  30750. return INJECTOR_IMPL(options.providers, options.parent, options.name || '');
  30751. }
  30752. };
  30753. Injector.THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
  30754. Injector.NULL = new NullInjector();
  30755. /** @nocollapse */
  30756. Injector.ngInjectableDef = ɵɵdefineInjectable({
  30757. token: Injector,
  30758. providedIn: 'any',
  30759. factory: function () { return ɵɵinject(INJECTOR); },
  30760. });
  30761. /**
  30762. * @internal
  30763. * @nocollapse
  30764. */
  30765. Injector.__NG_ELEMENT_ID__ = -1;
  30766. return Injector;
  30767. }());
  30768. var IDENT = function (value) {
  30769. return value;
  30770. };
  30771. var EMPTY = [];
  30772. var CIRCULAR$1 = IDENT;
  30773. var MULTI_PROVIDER_FN = function () {
  30774. return Array.prototype.slice.call(arguments);
  30775. };
  30776. var NO_NEW_LINE$1 = 'ɵ';
  30777. var StaticInjector = /** @class */ (function () {
  30778. function StaticInjector(providers, parent, source) {
  30779. if (parent === void 0) { parent = Injector.NULL; }
  30780. if (source === void 0) { source = null; }
  30781. this.parent = parent;
  30782. this.source = source;
  30783. var records = this._records = new Map();
  30784. records.set(Injector, { token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false });
  30785. records.set(INJECTOR, { token: INJECTOR, fn: IDENT, deps: EMPTY, value: this, useNew: false });
  30786. recursivelyProcessProviders(records, providers);
  30787. }
  30788. StaticInjector.prototype.get = function (token, notFoundValue, flags) {
  30789. if (flags === void 0) { flags = InjectFlags.Default; }
  30790. var record = this._records.get(token);
  30791. try {
  30792. return tryResolveToken(token, record, this._records, this.parent, notFoundValue, flags);
  30793. }
  30794. catch (e) {
  30795. return catchInjectorError(e, token, 'StaticInjectorError', this.source);
  30796. }
  30797. };
  30798. StaticInjector.prototype.toString = function () {
  30799. var tokens = [], records = this._records;
  30800. records.forEach(function (v, token) { return tokens.push(stringify$1(token)); });
  30801. return "StaticInjector[" + tokens.join(', ') + "]";
  30802. };
  30803. return StaticInjector;
  30804. }());
  30805. function resolveProvider(provider) {
  30806. var deps = computeDeps(provider);
  30807. var fn = IDENT;
  30808. var value = EMPTY;
  30809. var useNew = false;
  30810. var provide = resolveForwardRef$1(provider.provide);
  30811. if (USE_VALUE$2 in provider) {
  30812. // We need to use USE_VALUE in provider since provider.useValue could be defined as undefined.
  30813. value = provider.useValue;
  30814. }
  30815. else if (provider.useFactory) {
  30816. fn = provider.useFactory;
  30817. }
  30818. else if (provider.useExisting) ;
  30819. else if (provider.useClass) {
  30820. useNew = true;
  30821. fn = resolveForwardRef$1(provider.useClass);
  30822. }
  30823. else if (typeof provide == 'function') {
  30824. useNew = true;
  30825. fn = provide;
  30826. }
  30827. else {
  30828. throw staticError('StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable', provider);
  30829. }
  30830. return { deps: deps, fn: fn, useNew: useNew, value: value };
  30831. }
  30832. function multiProviderMixError(token) {
  30833. return staticError('Cannot mix multi providers and regular providers', token);
  30834. }
  30835. function recursivelyProcessProviders(records, provider) {
  30836. if (provider) {
  30837. provider = resolveForwardRef$1(provider);
  30838. if (provider instanceof Array) {
  30839. // if we have an array recurse into the array
  30840. for (var i = 0; i < provider.length; i++) {
  30841. recursivelyProcessProviders(records, provider[i]);
  30842. }
  30843. }
  30844. else if (typeof provider === 'function') {
  30845. // Functions were supported in ReflectiveInjector, but are not here. For safety give useful
  30846. // error messages
  30847. throw staticError('Function/Class not supported', provider);
  30848. }
  30849. else if (provider && typeof provider === 'object' && provider.provide) {
  30850. // At this point we have what looks like a provider: {provide: ?, ....}
  30851. var token = resolveForwardRef$1(provider.provide);
  30852. var resolvedProvider = resolveProvider(provider);
  30853. if (provider.multi === true) {
  30854. // This is a multi provider.
  30855. var multiProvider = records.get(token);
  30856. if (multiProvider) {
  30857. if (multiProvider.fn !== MULTI_PROVIDER_FN) {
  30858. throw multiProviderMixError(token);
  30859. }
  30860. }
  30861. else {
  30862. // Create a placeholder factory which will look up the constituents of the multi provider.
  30863. records.set(token, multiProvider = {
  30864. token: provider.provide,
  30865. deps: [],
  30866. useNew: false,
  30867. fn: MULTI_PROVIDER_FN,
  30868. value: EMPTY
  30869. });
  30870. }
  30871. // Treat the provider as the token.
  30872. token = provider;
  30873. multiProvider.deps.push({ token: token, options: 6 /* Default */ });
  30874. }
  30875. var record = records.get(token);
  30876. if (record && record.fn == MULTI_PROVIDER_FN) {
  30877. throw multiProviderMixError(token);
  30878. }
  30879. records.set(token, resolvedProvider);
  30880. }
  30881. else {
  30882. throw staticError('Unexpected provider', provider);
  30883. }
  30884. }
  30885. }
  30886. function tryResolveToken(token, record, records, parent, notFoundValue, flags) {
  30887. try {
  30888. return resolveToken(token, record, records, parent, notFoundValue, flags);
  30889. }
  30890. catch (e) {
  30891. // ensure that 'e' is of type Error.
  30892. if (!(e instanceof Error)) {
  30893. e = new Error(e);
  30894. }
  30895. var path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
  30896. path.unshift(token);
  30897. if (record && record.value == CIRCULAR$1) {
  30898. // Reset the Circular flag.
  30899. record.value = EMPTY;
  30900. }
  30901. throw e;
  30902. }
  30903. }
  30904. function resolveToken(token, record, records, parent, notFoundValue, flags) {
  30905. var _a;
  30906. var value;
  30907. if (record && !(flags & InjectFlags.SkipSelf)) {
  30908. // If we don't have a record, this implies that we don't own the provider hence don't know how
  30909. // to resolve it.
  30910. value = record.value;
  30911. if (value == CIRCULAR$1) {
  30912. throw Error(NO_NEW_LINE$1 + 'Circular dependency');
  30913. }
  30914. else if (value === EMPTY) {
  30915. record.value = CIRCULAR$1;
  30916. var obj = undefined;
  30917. var useNew = record.useNew;
  30918. var fn = record.fn;
  30919. var depRecords = record.deps;
  30920. var deps = EMPTY;
  30921. if (depRecords.length) {
  30922. deps = [];
  30923. for (var i = 0; i < depRecords.length; i++) {
  30924. var depRecord = depRecords[i];
  30925. var options = depRecord.options;
  30926. var childRecord = options & 2 /* CheckSelf */ ? records.get(depRecord.token) : undefined;
  30927. deps.push(tryResolveToken(
  30928. // Current Token to resolve
  30929. depRecord.token,
  30930. // A record which describes how to resolve the token.
  30931. // If undefined, this means we don't have such a record
  30932. childRecord,
  30933. // Other records we know about.
  30934. records,
  30935. // If we don't know how to resolve dependency and we should not check parent for it,
  30936. // than pass in Null injector.
  30937. !childRecord && !(options & 4 /* CheckParent */) ? Injector.NULL : parent, options & 1 /* Optional */ ? null : Injector.THROW_IF_NOT_FOUND, InjectFlags.Default));
  30938. }
  30939. }
  30940. record.value = value = useNew ? new ((_a = fn).bind.apply(_a, __spread([void 0], deps)))() : fn.apply(obj, deps);
  30941. }
  30942. }
  30943. else if (!(flags & InjectFlags.Self)) {
  30944. value = parent.get(token, notFoundValue, InjectFlags.Default);
  30945. }
  30946. return value;
  30947. }
  30948. function computeDeps(provider) {
  30949. var deps = EMPTY;
  30950. var providerDeps = provider.deps;
  30951. if (providerDeps && providerDeps.length) {
  30952. deps = [];
  30953. for (var i = 0; i < providerDeps.length; i++) {
  30954. var options = 6 /* Default */;
  30955. var token = resolveForwardRef$1(providerDeps[i]);
  30956. if (token instanceof Array) {
  30957. for (var j = 0, annotations = token; j < annotations.length; j++) {
  30958. var annotation = annotations[j];
  30959. if (annotation instanceof Optional || annotation == Optional) {
  30960. options = options | 1 /* Optional */;
  30961. }
  30962. else if (annotation instanceof SkipSelf || annotation == SkipSelf) {
  30963. options = options & ~2 /* CheckSelf */;
  30964. }
  30965. else if (annotation instanceof Self || annotation == Self) {
  30966. options = options & ~4 /* CheckParent */;
  30967. }
  30968. else if (annotation instanceof Inject) {
  30969. token = annotation.token;
  30970. }
  30971. else {
  30972. token = resolveForwardRef$1(annotation);
  30973. }
  30974. }
  30975. }
  30976. deps.push({ token: token, options: options });
  30977. }
  30978. }
  30979. else if (provider.useExisting) {
  30980. var token = resolveForwardRef$1(provider.useExisting);
  30981. deps = [{ token: token, options: 6 /* Default */ }];
  30982. }
  30983. else if (!providerDeps && !(USE_VALUE$2 in provider)) {
  30984. // useValue & useExisting are the only ones which are exempt from deps all others need it.
  30985. throw staticError('\'deps\' required', provider);
  30986. }
  30987. return deps;
  30988. }
  30989. function staticError(text, obj) {
  30990. return new Error(formatError(text, obj, 'StaticInjectorError'));
  30991. }
  30992. /**
  30993. * @license
  30994. * Copyright Google Inc. All Rights Reserved.
  30995. *
  30996. * Use of this source code is governed by an MIT-style license that can be
  30997. * found in the LICENSE file at https://angular.io/license
  30998. */
  30999. var ERROR_DEBUG_CONTEXT = 'ngDebugContext';
  31000. var ERROR_ORIGINAL_ERROR = 'ngOriginalError';
  31001. var ERROR_LOGGER = 'ngErrorLogger';
  31002. function wrappedError(message, originalError) {
  31003. var msg = message + " caused by: " + (originalError instanceof Error ? originalError.message : originalError);
  31004. var error = Error(msg);
  31005. error[ERROR_ORIGINAL_ERROR] = originalError;
  31006. return error;
  31007. }
  31008. /**
  31009. * @license
  31010. * Copyright Google Inc. All Rights Reserved.
  31011. *
  31012. * Use of this source code is governed by an MIT-style license that can be
  31013. * found in the LICENSE file at https://angular.io/license
  31014. */
  31015. function findFirstClosedCycle(keys) {
  31016. var res = [];
  31017. for (var i = 0; i < keys.length; ++i) {
  31018. if (res.indexOf(keys[i]) > -1) {
  31019. res.push(keys[i]);
  31020. return res;
  31021. }
  31022. res.push(keys[i]);
  31023. }
  31024. return res;
  31025. }
  31026. function constructResolvingPath(keys) {
  31027. if (keys.length > 1) {
  31028. var reversed = findFirstClosedCycle(keys.slice().reverse());
  31029. var tokenStrs = reversed.map(function (k) { return stringify$1(k.token); });
  31030. return ' (' + tokenStrs.join(' -> ') + ')';
  31031. }
  31032. return '';
  31033. }
  31034. function injectionError(injector, key, constructResolvingMessage, originalError) {
  31035. var keys = [key];
  31036. var errMsg = constructResolvingMessage(keys);
  31037. var error = (originalError ? wrappedError(errMsg, originalError) : Error(errMsg));
  31038. error.addKey = addKey;
  31039. error.keys = keys;
  31040. error.injectors = [injector];
  31041. error.constructResolvingMessage = constructResolvingMessage;
  31042. error[ERROR_ORIGINAL_ERROR] = originalError;
  31043. return error;
  31044. }
  31045. function addKey(injector, key) {
  31046. this.injectors.push(injector);
  31047. this.keys.push(key);
  31048. // Note: This updated message won't be reflected in the `.stack` property
  31049. this.message = this.constructResolvingMessage(this.keys);
  31050. }
  31051. /**
  31052. * Thrown when trying to retrieve a dependency by key from {@link Injector}, but the
  31053. * {@link Injector} does not have a {@link Provider} for the given key.
  31054. *
  31055. * @usageNotes
  31056. * ### Example
  31057. *
  31058. * ```typescript
  31059. * class A {
  31060. * constructor(b:B) {}
  31061. * }
  31062. *
  31063. * expect(() => Injector.resolveAndCreate([A])).toThrowError();
  31064. * ```
  31065. */
  31066. function noProviderError(injector, key) {
  31067. return injectionError(injector, key, function (keys) {
  31068. var first = stringify$1(keys[0].token);
  31069. return "No provider for " + first + "!" + constructResolvingPath(keys);
  31070. });
  31071. }
  31072. /**
  31073. * Thrown when dependencies form a cycle.
  31074. *
  31075. * @usageNotes
  31076. * ### Example
  31077. *
  31078. * ```typescript
  31079. * var injector = Injector.resolveAndCreate([
  31080. * {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
  31081. * {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
  31082. * ]);
  31083. *
  31084. * expect(() => injector.get("one")).toThrowError();
  31085. * ```
  31086. *
  31087. * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
  31088. */
  31089. function cyclicDependencyError(injector, key) {
  31090. return injectionError(injector, key, function (keys) {
  31091. return "Cannot instantiate cyclic dependency!" + constructResolvingPath(keys);
  31092. });
  31093. }
  31094. /**
  31095. * Thrown when a constructing type returns with an Error.
  31096. *
  31097. * The `InstantiationError` class contains the original error plus the dependency graph which caused
  31098. * this object to be instantiated.
  31099. *
  31100. * @usageNotes
  31101. * ### Example
  31102. *
  31103. * ```typescript
  31104. * class A {
  31105. * constructor() {
  31106. * throw new Error('message');
  31107. * }
  31108. * }
  31109. *
  31110. * var injector = Injector.resolveAndCreate([A]);
  31111. * try {
  31112. * injector.get(A);
  31113. * } catch (e) {
  31114. * expect(e instanceof InstantiationError).toBe(true);
  31115. * expect(e.originalException.message).toEqual("message");
  31116. * expect(e.originalStack).toBeDefined();
  31117. * }
  31118. * ```
  31119. */
  31120. function instantiationError(injector, originalException, originalStack, key) {
  31121. return injectionError(injector, key, function (keys) {
  31122. var first = stringify$1(keys[0].token);
  31123. return originalException.message + ": Error during instantiation of " + first + "!" + constructResolvingPath(keys) + ".";
  31124. }, originalException);
  31125. }
  31126. /**
  31127. * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
  31128. * creation.
  31129. *
  31130. * @usageNotes
  31131. * ### Example
  31132. *
  31133. * ```typescript
  31134. * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
  31135. * ```
  31136. */
  31137. function invalidProviderError(provider) {
  31138. return Error("Invalid provider - only instances of Provider and Type are allowed, got: " + provider);
  31139. }
  31140. /**
  31141. * Thrown when the class has no annotation information.
  31142. *
  31143. * Lack of annotation information prevents the {@link Injector} from determining which dependencies
  31144. * need to be injected into the constructor.
  31145. *
  31146. * @usageNotes
  31147. * ### Example
  31148. *
  31149. * ```typescript
  31150. * class A {
  31151. * constructor(b) {}
  31152. * }
  31153. *
  31154. * expect(() => Injector.resolveAndCreate([A])).toThrowError();
  31155. * ```
  31156. *
  31157. * This error is also thrown when the class not marked with {@link Injectable} has parameter types.
  31158. *
  31159. * ```typescript
  31160. * class B {}
  31161. *
  31162. * class A {
  31163. * constructor(b:B) {} // no information about the parameter types of A is available at runtime.
  31164. * }
  31165. *
  31166. * expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
  31167. * ```
  31168. *
  31169. */
  31170. function noAnnotationError(typeOrFunc, params) {
  31171. var signature = [];
  31172. for (var i = 0, ii = params.length; i < ii; i++) {
  31173. var parameter = params[i];
  31174. if (!parameter || parameter.length == 0) {
  31175. signature.push('?');
  31176. }
  31177. else {
  31178. signature.push(parameter.map(stringify$1).join(' '));
  31179. }
  31180. }
  31181. return Error('Cannot resolve all parameters for \'' + stringify$1(typeOrFunc) + '\'(' +
  31182. signature.join(', ') + '). ' +
  31183. 'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' +
  31184. stringify$1(typeOrFunc) + '\' is decorated with Injectable.');
  31185. }
  31186. /**
  31187. * Thrown when getting an object by index.
  31188. *
  31189. * @usageNotes
  31190. * ### Example
  31191. *
  31192. * ```typescript
  31193. * class A {}
  31194. *
  31195. * var injector = Injector.resolveAndCreate([A]);
  31196. *
  31197. * expect(() => injector.getAt(100)).toThrowError();
  31198. * ```
  31199. *
  31200. */
  31201. function outOfBoundsError(index) {
  31202. return Error("Index " + index + " is out-of-bounds.");
  31203. }
  31204. // TODO: add a working example after alpha38 is released
  31205. /**
  31206. * Thrown when a multi provider and a regular provider are bound to the same token.
  31207. *
  31208. * @usageNotes
  31209. * ### Example
  31210. *
  31211. * ```typescript
  31212. * expect(() => Injector.resolveAndCreate([
  31213. * { provide: "Strings", useValue: "string1", multi: true},
  31214. * { provide: "Strings", useValue: "string2", multi: false}
  31215. * ])).toThrowError();
  31216. * ```
  31217. */
  31218. function mixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
  31219. return Error("Cannot mix multi providers and regular providers, got: " + provider1 + " " + provider2);
  31220. }
  31221. /**
  31222. * @license
  31223. * Copyright Google Inc. All Rights Reserved.
  31224. *
  31225. * Use of this source code is governed by an MIT-style license that can be
  31226. * found in the LICENSE file at https://angular.io/license
  31227. */
  31228. /**
  31229. * A unique object used for retrieving items from the {@link ReflectiveInjector}.
  31230. *
  31231. * Keys have:
  31232. * - a system-wide unique `id`.
  31233. * - a `token`.
  31234. *
  31235. * `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows
  31236. * the
  31237. * injector to store created objects in a more efficient way.
  31238. *
  31239. * `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when
  31240. * resolving
  31241. * providers.
  31242. *
  31243. * @deprecated No replacement
  31244. * @publicApi
  31245. */
  31246. var ReflectiveKey = /** @class */ (function () {
  31247. /**
  31248. * Private
  31249. */
  31250. function ReflectiveKey(token, id) {
  31251. this.token = token;
  31252. this.id = id;
  31253. if (!token) {
  31254. throw new Error('Token must be defined!');
  31255. }
  31256. this.displayName = stringify$1(this.token);
  31257. }
  31258. /**
  31259. * Retrieves a `Key` for a token.
  31260. */
  31261. ReflectiveKey.get = function (token) {
  31262. return _globalKeyRegistry.get(resolveForwardRef$1(token));
  31263. };
  31264. Object.defineProperty(ReflectiveKey, "numberOfKeys", {
  31265. /**
  31266. * @returns the number of keys registered in the system.
  31267. */
  31268. get: function () { return _globalKeyRegistry.numberOfKeys; },
  31269. enumerable: true,
  31270. configurable: true
  31271. });
  31272. return ReflectiveKey;
  31273. }());
  31274. var KeyRegistry = /** @class */ (function () {
  31275. function KeyRegistry() {
  31276. this._allKeys = new Map();
  31277. }
  31278. KeyRegistry.prototype.get = function (token) {
  31279. if (token instanceof ReflectiveKey)
  31280. return token;
  31281. if (this._allKeys.has(token)) {
  31282. return this._allKeys.get(token);
  31283. }
  31284. var newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
  31285. this._allKeys.set(token, newKey);
  31286. return newKey;
  31287. };
  31288. Object.defineProperty(KeyRegistry.prototype, "numberOfKeys", {
  31289. get: function () { return this._allKeys.size; },
  31290. enumerable: true,
  31291. configurable: true
  31292. });
  31293. return KeyRegistry;
  31294. }());
  31295. var _globalKeyRegistry = new KeyRegistry();
  31296. /**
  31297. * @license
  31298. * Copyright Google Inc. All Rights Reserved.
  31299. *
  31300. * Use of this source code is governed by an MIT-style license that can be
  31301. * found in the LICENSE file at https://angular.io/license
  31302. */
  31303. /**
  31304. * Provides access to reflection data about symbols. Used internally by Angular
  31305. * to power dependency injection and compilation.
  31306. */
  31307. var Reflector = /** @class */ (function () {
  31308. function Reflector(reflectionCapabilities) {
  31309. this.reflectionCapabilities = reflectionCapabilities;
  31310. }
  31311. Reflector.prototype.updateCapabilities = function (caps) { this.reflectionCapabilities = caps; };
  31312. Reflector.prototype.factory = function (type) { return this.reflectionCapabilities.factory(type); };
  31313. Reflector.prototype.parameters = function (typeOrFunc) {
  31314. return this.reflectionCapabilities.parameters(typeOrFunc);
  31315. };
  31316. Reflector.prototype.annotations = function (typeOrFunc) {
  31317. return this.reflectionCapabilities.annotations(typeOrFunc);
  31318. };
  31319. Reflector.prototype.propMetadata = function (typeOrFunc) {
  31320. return this.reflectionCapabilities.propMetadata(typeOrFunc);
  31321. };
  31322. Reflector.prototype.hasLifecycleHook = function (type, lcProperty) {
  31323. return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
  31324. };
  31325. Reflector.prototype.getter = function (name) { return this.reflectionCapabilities.getter(name); };
  31326. Reflector.prototype.setter = function (name) { return this.reflectionCapabilities.setter(name); };
  31327. Reflector.prototype.method = function (name) { return this.reflectionCapabilities.method(name); };
  31328. Reflector.prototype.importUri = function (type) { return this.reflectionCapabilities.importUri(type); };
  31329. Reflector.prototype.resourceUri = function (type) { return this.reflectionCapabilities.resourceUri(type); };
  31330. Reflector.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
  31331. return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime);
  31332. };
  31333. Reflector.prototype.resolveEnum = function (identifier, name) {
  31334. return this.reflectionCapabilities.resolveEnum(identifier, name);
  31335. };
  31336. return Reflector;
  31337. }());
  31338. /**
  31339. * @license
  31340. * Copyright Google Inc. All Rights Reserved.
  31341. *
  31342. * Use of this source code is governed by an MIT-style license that can be
  31343. * found in the LICENSE file at https://angular.io/license
  31344. */
  31345. /**
  31346. * The {@link Reflector} used internally in Angular to access metadata
  31347. * about symbols.
  31348. */
  31349. var reflector = new Reflector(new ReflectionCapabilities());
  31350. /**
  31351. * @license
  31352. * Copyright Google Inc. All Rights Reserved.
  31353. *
  31354. * Use of this source code is governed by an MIT-style license that can be
  31355. * found in the LICENSE file at https://angular.io/license
  31356. */
  31357. /**
  31358. * `Dependency` is used by the framework to extend DI.
  31359. * This is internal to Angular and should not be used directly.
  31360. */
  31361. var ReflectiveDependency = /** @class */ (function () {
  31362. function ReflectiveDependency(key, optional, visibility) {
  31363. this.key = key;
  31364. this.optional = optional;
  31365. this.visibility = visibility;
  31366. }
  31367. ReflectiveDependency.fromKey = function (key) {
  31368. return new ReflectiveDependency(key, false, null);
  31369. };
  31370. return ReflectiveDependency;
  31371. }());
  31372. var _EMPTY_LIST = [];
  31373. var ResolvedReflectiveProvider_ = /** @class */ (function () {
  31374. function ResolvedReflectiveProvider_(key, resolvedFactories, multiProvider) {
  31375. this.key = key;
  31376. this.resolvedFactories = resolvedFactories;
  31377. this.multiProvider = multiProvider;
  31378. this.resolvedFactory = this.resolvedFactories[0];
  31379. }
  31380. return ResolvedReflectiveProvider_;
  31381. }());
  31382. /**
  31383. * An internal resolved representation of a factory function created by resolving `Provider`.
  31384. * @publicApi
  31385. */
  31386. var ResolvedReflectiveFactory = /** @class */ (function () {
  31387. function ResolvedReflectiveFactory(
  31388. /**
  31389. * Factory function which can return an instance of an object represented by a key.
  31390. */
  31391. factory,
  31392. /**
  31393. * Arguments (dependencies) to the `factory` function.
  31394. */
  31395. dependencies) {
  31396. this.factory = factory;
  31397. this.dependencies = dependencies;
  31398. }
  31399. return ResolvedReflectiveFactory;
  31400. }());
  31401. /**
  31402. * Resolve a single provider.
  31403. */
  31404. function resolveReflectiveFactory(provider) {
  31405. var factoryFn;
  31406. var resolvedDeps;
  31407. if (provider.useClass) {
  31408. var useClass = resolveForwardRef$1(provider.useClass);
  31409. factoryFn = reflector.factory(useClass);
  31410. resolvedDeps = _dependenciesFor(useClass);
  31411. }
  31412. else if (provider.useExisting) {
  31413. factoryFn = function (aliasInstance) { return aliasInstance; };
  31414. resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
  31415. }
  31416. else if (provider.useFactory) {
  31417. factoryFn = provider.useFactory;
  31418. resolvedDeps = constructDependencies(provider.useFactory, provider.deps);
  31419. }
  31420. else {
  31421. factoryFn = function () { return provider.useValue; };
  31422. resolvedDeps = _EMPTY_LIST;
  31423. }
  31424. return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
  31425. }
  31426. /**
  31427. * Converts the `Provider` into `ResolvedProvider`.
  31428. *
  31429. * `Injector` internally only uses `ResolvedProvider`, `Provider` contains convenience provider
  31430. * syntax.
  31431. */
  31432. function resolveReflectiveProvider(provider) {
  31433. return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false);
  31434. }
  31435. /**
  31436. * Resolve a list of Providers.
  31437. */
  31438. function resolveReflectiveProviders(providers) {
  31439. var normalized = _normalizeProviders(providers, []);
  31440. var resolved = normalized.map(resolveReflectiveProvider);
  31441. var resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map());
  31442. return Array.from(resolvedProviderMap.values());
  31443. }
  31444. /**
  31445. * Merges a list of ResolvedProviders into a list where each key is contained exactly once and
  31446. * multi providers have been merged.
  31447. */
  31448. function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
  31449. for (var i = 0; i < providers.length; i++) {
  31450. var provider = providers[i];
  31451. var existing = normalizedProvidersMap.get(provider.key.id);
  31452. if (existing) {
  31453. if (provider.multiProvider !== existing.multiProvider) {
  31454. throw mixingMultiProvidersWithRegularProvidersError(existing, provider);
  31455. }
  31456. if (provider.multiProvider) {
  31457. for (var j = 0; j < provider.resolvedFactories.length; j++) {
  31458. existing.resolvedFactories.push(provider.resolvedFactories[j]);
  31459. }
  31460. }
  31461. else {
  31462. normalizedProvidersMap.set(provider.key.id, provider);
  31463. }
  31464. }
  31465. else {
  31466. var resolvedProvider = void 0;
  31467. if (provider.multiProvider) {
  31468. resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
  31469. }
  31470. else {
  31471. resolvedProvider = provider;
  31472. }
  31473. normalizedProvidersMap.set(provider.key.id, resolvedProvider);
  31474. }
  31475. }
  31476. return normalizedProvidersMap;
  31477. }
  31478. function _normalizeProviders(providers, res) {
  31479. providers.forEach(function (b) {
  31480. if (b instanceof Type$2) {
  31481. res.push({ provide: b, useClass: b });
  31482. }
  31483. else if (b && typeof b == 'object' && b.provide !== undefined) {
  31484. res.push(b);
  31485. }
  31486. else if (b instanceof Array) {
  31487. _normalizeProviders(b, res);
  31488. }
  31489. else {
  31490. throw invalidProviderError(b);
  31491. }
  31492. });
  31493. return res;
  31494. }
  31495. function constructDependencies(typeOrFunc, dependencies) {
  31496. if (!dependencies) {
  31497. return _dependenciesFor(typeOrFunc);
  31498. }
  31499. else {
  31500. var params_1 = dependencies.map(function (t) { return [t]; });
  31501. return dependencies.map(function (t) { return _extractToken(typeOrFunc, t, params_1); });
  31502. }
  31503. }
  31504. function _dependenciesFor(typeOrFunc) {
  31505. var params = reflector.parameters(typeOrFunc);
  31506. if (!params)
  31507. return [];
  31508. if (params.some(function (p) { return p == null; })) {
  31509. throw noAnnotationError(typeOrFunc, params);
  31510. }
  31511. return params.map(function (p) { return _extractToken(typeOrFunc, p, params); });
  31512. }
  31513. function _extractToken(typeOrFunc, metadata, params) {
  31514. var token = null;
  31515. var optional = false;
  31516. if (!Array.isArray(metadata)) {
  31517. if (metadata instanceof Inject) {
  31518. return _createDependency(metadata.token, optional, null);
  31519. }
  31520. else {
  31521. return _createDependency(metadata, optional, null);
  31522. }
  31523. }
  31524. var visibility = null;
  31525. for (var i = 0; i < metadata.length; ++i) {
  31526. var paramMetadata = metadata[i];
  31527. if (paramMetadata instanceof Type$2) {
  31528. token = paramMetadata;
  31529. }
  31530. else if (paramMetadata instanceof Inject) {
  31531. token = paramMetadata.token;
  31532. }
  31533. else if (paramMetadata instanceof Optional) {
  31534. optional = true;
  31535. }
  31536. else if (paramMetadata instanceof Self || paramMetadata instanceof SkipSelf) {
  31537. visibility = paramMetadata;
  31538. }
  31539. else if (paramMetadata instanceof InjectionToken) {
  31540. token = paramMetadata;
  31541. }
  31542. }
  31543. token = resolveForwardRef$1(token);
  31544. if (token != null) {
  31545. return _createDependency(token, optional, visibility);
  31546. }
  31547. else {
  31548. throw noAnnotationError(typeOrFunc, params);
  31549. }
  31550. }
  31551. function _createDependency(token, optional, visibility) {
  31552. return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility);
  31553. }
  31554. /**
  31555. * @license
  31556. * Copyright Google Inc. All Rights Reserved.
  31557. *
  31558. * Use of this source code is governed by an MIT-style license that can be
  31559. * found in the LICENSE file at https://angular.io/license
  31560. */
  31561. // Threshold for the dynamic version
  31562. var UNDEFINED = new Object();
  31563. /**
  31564. * A ReflectiveDependency injection container used for instantiating objects and resolving
  31565. * dependencies.
  31566. *
  31567. * An `Injector` is a replacement for a `new` operator, which can automatically resolve the
  31568. * constructor dependencies.
  31569. *
  31570. * In typical use, application code asks for the dependencies in the constructor and they are
  31571. * resolved by the `Injector`.
  31572. *
  31573. * @usageNotes
  31574. * ### Example
  31575. *
  31576. * The following example creates an `Injector` configured to create `Engine` and `Car`.
  31577. *
  31578. * ```typescript
  31579. * @Injectable()
  31580. * class Engine {
  31581. * }
  31582. *
  31583. * @Injectable()
  31584. * class Car {
  31585. * constructor(public engine:Engine) {}
  31586. * }
  31587. *
  31588. * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
  31589. * var car = injector.get(Car);
  31590. * expect(car instanceof Car).toBe(true);
  31591. * expect(car.engine instanceof Engine).toBe(true);
  31592. * ```
  31593. *
  31594. * Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
  31595. * resolve all of the object's dependencies automatically.
  31596. *
  31597. * @deprecated from v5 - slow and brings in a lot of code, Use `Injector.create` instead.
  31598. * @publicApi
  31599. */
  31600. var ReflectiveInjector = /** @class */ (function () {
  31601. function ReflectiveInjector() {
  31602. }
  31603. /**
  31604. * Turns an array of provider definitions into an array of resolved providers.
  31605. *
  31606. * A resolution is a process of flattening multiple nested arrays and converting individual
  31607. * providers into an array of `ResolvedReflectiveProvider`s.
  31608. *
  31609. * @usageNotes
  31610. * ### Example
  31611. *
  31612. * ```typescript
  31613. * @Injectable()
  31614. * class Engine {
  31615. * }
  31616. *
  31617. * @Injectable()
  31618. * class Car {
  31619. * constructor(public engine:Engine) {}
  31620. * }
  31621. *
  31622. * var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
  31623. *
  31624. * expect(providers.length).toEqual(2);
  31625. *
  31626. * expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
  31627. * expect(providers[0].key.displayName).toBe("Car");
  31628. * expect(providers[0].dependencies.length).toEqual(1);
  31629. * expect(providers[0].factory).toBeDefined();
  31630. *
  31631. * expect(providers[1].key.displayName).toBe("Engine");
  31632. * });
  31633. * ```
  31634. *
  31635. */
  31636. ReflectiveInjector.resolve = function (providers) {
  31637. return resolveReflectiveProviders(providers);
  31638. };
  31639. /**
  31640. * Resolves an array of providers and creates an injector from those providers.
  31641. *
  31642. * The passed-in providers can be an array of `Type`, `Provider`,
  31643. * or a recursive array of more providers.
  31644. *
  31645. * @usageNotes
  31646. * ### Example
  31647. *
  31648. * ```typescript
  31649. * @Injectable()
  31650. * class Engine {
  31651. * }
  31652. *
  31653. * @Injectable()
  31654. * class Car {
  31655. * constructor(public engine:Engine) {}
  31656. * }
  31657. *
  31658. * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
  31659. * expect(injector.get(Car) instanceof Car).toBe(true);
  31660. * ```
  31661. */
  31662. ReflectiveInjector.resolveAndCreate = function (providers, parent) {
  31663. var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
  31664. return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
  31665. };
  31666. /**
  31667. * Creates an injector from previously resolved providers.
  31668. *
  31669. * This API is the recommended way to construct injectors in performance-sensitive parts.
  31670. *
  31671. * @usageNotes
  31672. * ### Example
  31673. *
  31674. * ```typescript
  31675. * @Injectable()
  31676. * class Engine {
  31677. * }
  31678. *
  31679. * @Injectable()
  31680. * class Car {
  31681. * constructor(public engine:Engine) {}
  31682. * }
  31683. *
  31684. * var providers = ReflectiveInjector.resolve([Car, Engine]);
  31685. * var injector = ReflectiveInjector.fromResolvedProviders(providers);
  31686. * expect(injector.get(Car) instanceof Car).toBe(true);
  31687. * ```
  31688. */
  31689. ReflectiveInjector.fromResolvedProviders = function (providers, parent) {
  31690. return new ReflectiveInjector_(providers, parent);
  31691. };
  31692. return ReflectiveInjector;
  31693. }());
  31694. var ReflectiveInjector_ = /** @class */ (function () {
  31695. /**
  31696. * Private
  31697. */
  31698. function ReflectiveInjector_(_providers, _parent) {
  31699. /** @internal */
  31700. this._constructionCounter = 0;
  31701. this._providers = _providers;
  31702. this.parent = _parent || null;
  31703. var len = _providers.length;
  31704. this.keyIds = new Array(len);
  31705. this.objs = new Array(len);
  31706. for (var i = 0; i < len; i++) {
  31707. this.keyIds[i] = _providers[i].key.id;
  31708. this.objs[i] = UNDEFINED;
  31709. }
  31710. }
  31711. ReflectiveInjector_.prototype.get = function (token, notFoundValue) {
  31712. if (notFoundValue === void 0) { notFoundValue = THROW_IF_NOT_FOUND; }
  31713. return this._getByKey(ReflectiveKey.get(token), null, notFoundValue);
  31714. };
  31715. ReflectiveInjector_.prototype.resolveAndCreateChild = function (providers) {
  31716. var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
  31717. return this.createChildFromResolved(ResolvedReflectiveProviders);
  31718. };
  31719. ReflectiveInjector_.prototype.createChildFromResolved = function (providers) {
  31720. var inj = new ReflectiveInjector_(providers);
  31721. inj.parent = this;
  31722. return inj;
  31723. };
  31724. ReflectiveInjector_.prototype.resolveAndInstantiate = function (provider) {
  31725. return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
  31726. };
  31727. ReflectiveInjector_.prototype.instantiateResolved = function (provider) {
  31728. return this._instantiateProvider(provider);
  31729. };
  31730. ReflectiveInjector_.prototype.getProviderAtIndex = function (index) {
  31731. if (index < 0 || index >= this._providers.length) {
  31732. throw outOfBoundsError(index);
  31733. }
  31734. return this._providers[index];
  31735. };
  31736. /** @internal */
  31737. ReflectiveInjector_.prototype._new = function (provider) {
  31738. if (this._constructionCounter++ > this._getMaxNumberOfObjects()) {
  31739. throw cyclicDependencyError(this, provider.key);
  31740. }
  31741. return this._instantiateProvider(provider);
  31742. };
  31743. ReflectiveInjector_.prototype._getMaxNumberOfObjects = function () { return this.objs.length; };
  31744. ReflectiveInjector_.prototype._instantiateProvider = function (provider) {
  31745. if (provider.multiProvider) {
  31746. var res = new Array(provider.resolvedFactories.length);
  31747. for (var i = 0; i < provider.resolvedFactories.length; ++i) {
  31748. res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
  31749. }
  31750. return res;
  31751. }
  31752. else {
  31753. return this._instantiate(provider, provider.resolvedFactories[0]);
  31754. }
  31755. };
  31756. ReflectiveInjector_.prototype._instantiate = function (provider, ResolvedReflectiveFactory) {
  31757. var _this = this;
  31758. var factory = ResolvedReflectiveFactory.factory;
  31759. var deps;
  31760. try {
  31761. deps =
  31762. ResolvedReflectiveFactory.dependencies.map(function (dep) { return _this._getByReflectiveDependency(dep); });
  31763. }
  31764. catch (e) {
  31765. if (e.addKey) {
  31766. e.addKey(this, provider.key);
  31767. }
  31768. throw e;
  31769. }
  31770. var obj;
  31771. try {
  31772. obj = factory.apply(void 0, __spread(deps));
  31773. }
  31774. catch (e) {
  31775. throw instantiationError(this, e, e.stack, provider.key);
  31776. }
  31777. return obj;
  31778. };
  31779. ReflectiveInjector_.prototype._getByReflectiveDependency = function (dep) {
  31780. return this._getByKey(dep.key, dep.visibility, dep.optional ? null : THROW_IF_NOT_FOUND);
  31781. };
  31782. ReflectiveInjector_.prototype._getByKey = function (key, visibility, notFoundValue) {
  31783. if (key === ReflectiveInjector_.INJECTOR_KEY) {
  31784. return this;
  31785. }
  31786. if (visibility instanceof Self) {
  31787. return this._getByKeySelf(key, notFoundValue);
  31788. }
  31789. else {
  31790. return this._getByKeyDefault(key, notFoundValue, visibility);
  31791. }
  31792. };
  31793. ReflectiveInjector_.prototype._getObjByKeyId = function (keyId) {
  31794. for (var i = 0; i < this.keyIds.length; i++) {
  31795. if (this.keyIds[i] === keyId) {
  31796. if (this.objs[i] === UNDEFINED) {
  31797. this.objs[i] = this._new(this._providers[i]);
  31798. }
  31799. return this.objs[i];
  31800. }
  31801. }
  31802. return UNDEFINED;
  31803. };
  31804. /** @internal */
  31805. ReflectiveInjector_.prototype._throwOrNull = function (key, notFoundValue) {
  31806. if (notFoundValue !== THROW_IF_NOT_FOUND) {
  31807. return notFoundValue;
  31808. }
  31809. else {
  31810. throw noProviderError(this, key);
  31811. }
  31812. };
  31813. /** @internal */
  31814. ReflectiveInjector_.prototype._getByKeySelf = function (key, notFoundValue) {
  31815. var obj = this._getObjByKeyId(key.id);
  31816. return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, notFoundValue);
  31817. };
  31818. /** @internal */
  31819. ReflectiveInjector_.prototype._getByKeyDefault = function (key, notFoundValue, visibility) {
  31820. var inj;
  31821. if (visibility instanceof SkipSelf) {
  31822. inj = this.parent;
  31823. }
  31824. else {
  31825. inj = this;
  31826. }
  31827. while (inj instanceof ReflectiveInjector_) {
  31828. var inj_ = inj;
  31829. var obj = inj_._getObjByKeyId(key.id);
  31830. if (obj !== UNDEFINED)
  31831. return obj;
  31832. inj = inj_.parent;
  31833. }
  31834. if (inj !== null) {
  31835. return inj.get(key.token, notFoundValue);
  31836. }
  31837. else {
  31838. return this._throwOrNull(key, notFoundValue);
  31839. }
  31840. };
  31841. Object.defineProperty(ReflectiveInjector_.prototype, "displayName", {
  31842. get: function () {
  31843. var providers = _mapProviders(this, function (b) { return ' "' + b.key.displayName + '" '; })
  31844. .join(', ');
  31845. return "ReflectiveInjector(providers: [" + providers + "])";
  31846. },
  31847. enumerable: true,
  31848. configurable: true
  31849. });
  31850. ReflectiveInjector_.prototype.toString = function () { return this.displayName; };
  31851. ReflectiveInjector_.INJECTOR_KEY = ReflectiveKey.get(Injector);
  31852. return ReflectiveInjector_;
  31853. }());
  31854. function _mapProviders(injector, fn) {
  31855. var res = new Array(injector._providers.length);
  31856. for (var i = 0; i < injector._providers.length; ++i) {
  31857. res[i] = fn(injector.getProviderAtIndex(i));
  31858. }
  31859. return res;
  31860. }
  31861. /**
  31862. * @license
  31863. * Copyright Google Inc. All Rights Reserved.
  31864. *
  31865. * Use of this source code is governed by an MIT-style license that can be
  31866. * found in the LICENSE file at https://angular.io/license
  31867. */
  31868. /**
  31869. * @license
  31870. * Copyright Google Inc. All Rights Reserved.
  31871. *
  31872. * Use of this source code is governed by an MIT-style license that can be
  31873. * found in the LICENSE file at https://angular.io/license
  31874. */
  31875. /**
  31876. * @license
  31877. * Copyright Google Inc. All Rights Reserved.
  31878. *
  31879. * Use of this source code is governed by an MIT-style license that can be
  31880. * found in the LICENSE file at https://angular.io/license
  31881. */
  31882. /**
  31883. * A DI token that you can use to create a virtual [provider](guide/glossary#provider)
  31884. * that will populate the `entryComponents` field of components and NgModules
  31885. * based on its `useValue` property value.
  31886. * All components that are referenced in the `useValue` value (either directly
  31887. * or in a nested array or map) are added to the `entryComponents` property.
  31888. *
  31889. * @usageNotes
  31890. *
  31891. * The following example shows how the router can populate the `entryComponents`
  31892. * field of an NgModule based on a router configuration that refers
  31893. * to components.
  31894. *
  31895. * ```typescript
  31896. * // helper function inside the router
  31897. * function provideRoutes(routes) {
  31898. * return [
  31899. * {provide: ROUTES, useValue: routes},
  31900. * {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: routes, multi: true}
  31901. * ];
  31902. * }
  31903. *
  31904. * // user code
  31905. * let routes = [
  31906. * {path: '/root', component: RootComp},
  31907. * {path: '/teams', component: TeamsComp}
  31908. * ];
  31909. *
  31910. * @NgModule({
  31911. * providers: [provideRoutes(routes)]
  31912. * })
  31913. * class ModuleWithRoutes {}
  31914. * ```
  31915. *
  31916. * @publicApi
  31917. */
  31918. var ANALYZE_FOR_ENTRY_COMPONENTS = new InjectionToken('AnalyzeForEntryComponents');
  31919. /**
  31920. * Base class for query metadata.
  31921. *
  31922. * @see `ContentChildren`.
  31923. * @see `ContentChild`.
  31924. * @see `ViewChildren`.
  31925. * @see `ViewChild`.
  31926. *
  31927. * @publicApi
  31928. */
  31929. var Query = /** @class */ (function () {
  31930. function Query() {
  31931. }
  31932. return Query;
  31933. }());
  31934. var ɵ0$5 = function (selector, data) {
  31935. if (data === void 0) { data = {}; }
  31936. return (__assign({ selector: selector, first: false, isViewQuery: false, descendants: false }, data));
  31937. };
  31938. /**
  31939. * ContentChildren decorator and metadata.
  31940. *
  31941. *
  31942. * @Annotation
  31943. * @publicApi
  31944. */
  31945. var ContentChildren = makePropDecorator('ContentChildren', ɵ0$5, Query);
  31946. var ɵ1$1 = function (selector, data) {
  31947. if (data === void 0) { data = {}; }
  31948. return (__assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data));
  31949. };
  31950. /**
  31951. * ContentChild decorator and metadata.
  31952. *
  31953. *
  31954. * @Annotation
  31955. *
  31956. * @publicApi
  31957. */
  31958. var ContentChild = makePropDecorator('ContentChild', ɵ1$1, Query);
  31959. var ɵ2 = function (selector, data) {
  31960. if (data === void 0) { data = {}; }
  31961. return (__assign({ selector: selector, first: false, isViewQuery: true, descendants: true }, data));
  31962. };
  31963. /**
  31964. * ViewChildren decorator and metadata.
  31965. *
  31966. * @Annotation
  31967. * @publicApi
  31968. */
  31969. var ViewChildren = makePropDecorator('ViewChildren', ɵ2, Query);
  31970. var ɵ3 = function (selector, data) {
  31971. return (__assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data));
  31972. };
  31973. /**
  31974. * ViewChild decorator and metadata.
  31975. *
  31976. * @Annotation
  31977. * @publicApi
  31978. */
  31979. var ViewChild = makePropDecorator('ViewChild', ɵ3, Query);
  31980. /**
  31981. * @license
  31982. * Copyright Google Inc. All Rights Reserved.
  31983. *
  31984. * Use of this source code is governed by an MIT-style license that can be
  31985. * found in the LICENSE file at https://angular.io/license
  31986. */
  31987. /**
  31988. * The strategy that the default change detector uses to detect changes.
  31989. * When set, takes effect the next time change detection is triggered.
  31990. *
  31991. * @publicApi
  31992. */
  31993. var ChangeDetectionStrategy$1;
  31994. (function (ChangeDetectionStrategy) {
  31995. /**
  31996. * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated
  31997. * until reactivated by setting the strategy to `Default` (`CheckAlways`).
  31998. * Change detection can still be explicitly invoked.
  31999. * This strategy applies to all child directives and cannot be overridden.
  32000. */
  32001. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  32002. /**
  32003. * Use the default `CheckAlways` strategy, in which change detection is automatic until
  32004. * explicitly deactivated.
  32005. */
  32006. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  32007. })(ChangeDetectionStrategy$1 || (ChangeDetectionStrategy$1 = {}));
  32008. /**
  32009. * Defines the possible states of the default change detector.
  32010. * @see `ChangeDetectorRef`
  32011. */
  32012. var ChangeDetectorStatus;
  32013. (function (ChangeDetectorStatus) {
  32014. /**
  32015. * A state in which, after calling `detectChanges()`, the change detector
  32016. * state becomes `Checked`, and must be explicitly invoked or reactivated.
  32017. */
  32018. ChangeDetectorStatus[ChangeDetectorStatus["CheckOnce"] = 0] = "CheckOnce";
  32019. /**
  32020. * A state in which change detection is skipped until the change detector mode
  32021. * becomes `CheckOnce`.
  32022. */
  32023. ChangeDetectorStatus[ChangeDetectorStatus["Checked"] = 1] = "Checked";
  32024. /**
  32025. * A state in which change detection continues automatically until explicitly
  32026. * deactivated.
  32027. */
  32028. ChangeDetectorStatus[ChangeDetectorStatus["CheckAlways"] = 2] = "CheckAlways";
  32029. /**
  32030. * A state in which a change detector sub tree is not a part of the main tree and
  32031. * should be skipped.
  32032. */
  32033. ChangeDetectorStatus[ChangeDetectorStatus["Detached"] = 3] = "Detached";
  32034. /**
  32035. * Indicates that the change detector encountered an error checking a binding
  32036. * or calling a directive lifecycle method and is now in an inconsistent state. Change
  32037. * detectors in this state do not detect changes.
  32038. */
  32039. ChangeDetectorStatus[ChangeDetectorStatus["Errored"] = 4] = "Errored";
  32040. /**
  32041. * Indicates that the change detector has been destroyed.
  32042. */
  32043. ChangeDetectorStatus[ChangeDetectorStatus["Destroyed"] = 5] = "Destroyed";
  32044. })(ChangeDetectorStatus || (ChangeDetectorStatus = {}));
  32045. /**
  32046. * @license
  32047. * Copyright Google Inc. All Rights Reserved.
  32048. *
  32049. * Use of this source code is governed by an MIT-style license that can be
  32050. * found in the LICENSE file at https://angular.io/license
  32051. */
  32052. /**
  32053. * @license
  32054. * Copyright Google Inc. All Rights Reserved.
  32055. *
  32056. * Use of this source code is governed by an MIT-style license that can be
  32057. * found in the LICENSE file at https://angular.io/license
  32058. */
  32059. /**
  32060. * Defines template and style encapsulation options available for Component's {@link Component}.
  32061. *
  32062. * See {@link Component#encapsulation encapsulation}.
  32063. *
  32064. * @usageNotes
  32065. * ### Example
  32066. *
  32067. * {@example core/ts/metadata/encapsulation.ts region='longform'}
  32068. *
  32069. * @publicApi
  32070. */
  32071. var ViewEncapsulation$1;
  32072. (function (ViewEncapsulation) {
  32073. /**
  32074. * Emulate `Native` scoping of styles by adding an attribute containing surrogate id to the Host
  32075. * Element and pre-processing the style rules provided via {@link Component#styles styles} or
  32076. * {@link Component#styleUrls styleUrls}, and adding the new Host Element attribute to all
  32077. * selectors.
  32078. *
  32079. * This is the default option.
  32080. */
  32081. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  32082. /**
  32083. * @deprecated v6.1.0 - use {ViewEncapsulation.ShadowDom} instead.
  32084. * Use the native encapsulation mechanism of the renderer.
  32085. *
  32086. * For the DOM this means using the deprecated [Shadow DOM
  32087. * v0](https://w3c.github.io/webcomponents/spec/shadow/) and
  32088. * creating a ShadowRoot for Component's Host Element.
  32089. */
  32090. ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
  32091. /**
  32092. * Don't provide any template or style encapsulation.
  32093. */
  32094. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  32095. /**
  32096. * Use Shadow DOM to encapsulate styles.
  32097. *
  32098. * For the DOM this means using modern [Shadow
  32099. * DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
  32100. * creating a ShadowRoot for Component's Host Element.
  32101. */
  32102. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  32103. })(ViewEncapsulation$1 || (ViewEncapsulation$1 = {}));
  32104. /**
  32105. * @license
  32106. * Copyright Google Inc. All Rights Reserved.
  32107. *
  32108. * Use of this source code is governed by an MIT-style license that can be
  32109. * found in the LICENSE file at https://angular.io/license
  32110. */
  32111. /**
  32112. * @license
  32113. * Copyright Google Inc. All Rights Reserved.
  32114. *
  32115. * Use of this source code is governed by an MIT-style license that can be
  32116. * found in the LICENSE file at https://angular.io/license
  32117. */
  32118. /**
  32119. * This file contains reuseable "empty" symbols that can be used as default return values
  32120. * in different parts of the rendering code. Because the same symbols are returned, this
  32121. * allows for identity checks against these values to be consistently used by the framework
  32122. * code.
  32123. */
  32124. var EMPTY_OBJ = {};
  32125. var EMPTY_ARRAY$3 = [];
  32126. // freezing the values prevents any code from accidentally inserting new values in
  32127. if (typeof ngDevMode !== 'undefined' && ngDevMode) {
  32128. // These property accesses can be ignored because ngDevMode will be set to false
  32129. // when optimizing code and the whole if statement will be dropped.
  32130. // tslint:disable-next-line:no-toplevel-property-access
  32131. Object.freeze(EMPTY_OBJ);
  32132. // tslint:disable-next-line:no-toplevel-property-access
  32133. Object.freeze(EMPTY_ARRAY$3);
  32134. }
  32135. /**
  32136. * @license
  32137. * Copyright Google Inc. All Rights Reserved.
  32138. *
  32139. * Use of this source code is governed by an MIT-style license that can be
  32140. * found in the LICENSE file at https://angular.io/license
  32141. */
  32142. var NG_COMPONENT_DEF = getClosureSafeProperty({ ngComponentDef: getClosureSafeProperty });
  32143. var NG_DIRECTIVE_DEF = getClosureSafeProperty({ ngDirectiveDef: getClosureSafeProperty });
  32144. var NG_PIPE_DEF = getClosureSafeProperty({ ngPipeDef: getClosureSafeProperty });
  32145. var NG_MODULE_DEF = getClosureSafeProperty({ ngModuleDef: getClosureSafeProperty });
  32146. var NG_LOCALE_ID_DEF = getClosureSafeProperty({ ngLocaleIdDef: getClosureSafeProperty });
  32147. var NG_BASE_DEF = getClosureSafeProperty({ ngBaseDef: getClosureSafeProperty });
  32148. /**
  32149. * If a directive is diPublic, bloomAdd sets a property on the type with this constant as
  32150. * the key and the directive's unique ID as the value. This allows us to map directives to their
  32151. * bloom filter bit for DI.
  32152. */
  32153. // TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.
  32154. var NG_ELEMENT_ID = getClosureSafeProperty({ __NG_ELEMENT_ID__: getClosureSafeProperty });
  32155. /**
  32156. * @license
  32157. * Copyright Google Inc. All Rights Reserved.
  32158. *
  32159. * Use of this source code is governed by an MIT-style license that can be
  32160. * found in the LICENSE file at https://angular.io/license
  32161. */
  32162. /**
  32163. * The following getter methods retrieve the definition form the type. Currently the retrieval
  32164. * honors inheritance, but in the future we may change the rule to require that definitions are
  32165. * explicit. This would require some sort of migration strategy.
  32166. */
  32167. function getComponentDef(type) {
  32168. return type[NG_COMPONENT_DEF] || null;
  32169. }
  32170. function getNgModuleDef(type, throwNotFound) {
  32171. var ngModuleDef = type[NG_MODULE_DEF] || null;
  32172. if (!ngModuleDef && throwNotFound === true) {
  32173. throw new Error("Type " + stringify$1(type) + " does not have 'ngModuleDef' property.");
  32174. }
  32175. return ngModuleDef;
  32176. }
  32177. function getNgLocaleIdDef(type) {
  32178. return type[NG_LOCALE_ID_DEF] || null;
  32179. }
  32180. /**
  32181. * @license
  32182. * Copyright Google Inc. All Rights Reserved.
  32183. *
  32184. * Use of this source code is governed by an MIT-style license that can be
  32185. * found in the LICENSE file at https://angular.io/license
  32186. */
  32187. /**
  32188. * Used for stringify render output in Ivy.
  32189. * Important! This function is very performance-sensitive and we should
  32190. * be extra careful not to introduce megamorphic reads in it.
  32191. */
  32192. function renderStringify(value) {
  32193. if (typeof value === 'string')
  32194. return value;
  32195. if (value == null)
  32196. return '';
  32197. return '' + value;
  32198. }
  32199. /**
  32200. * Used to stringify a value so that it can be displayed in an error message.
  32201. * Important! This function contains a megamorphic read and should only be
  32202. * used for error messages.
  32203. */
  32204. function stringifyForError(value) {
  32205. if (typeof value === 'function')
  32206. return value.name || value.toString();
  32207. if (typeof value === 'object' && value != null && typeof value.type === 'function') {
  32208. return value.type.name || value.type.toString();
  32209. }
  32210. return renderStringify(value);
  32211. }
  32212. var ɵ0$6 = function () {
  32213. return (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame || // browser only
  32214. setTimeout // everything else
  32215. ).bind(_global$1);
  32216. };
  32217. var defaultScheduler = (ɵ0$6)();
  32218. /**
  32219. * The special delimiter we use to separate property names, prefixes, and suffixes
  32220. * in property binding metadata. See storeBindingMetadata().
  32221. *
  32222. * We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
  32223. * because it is a very uncommon character that is unlikely to be part of a user's
  32224. * property names or interpolation strings. If it is in fact used in a property
  32225. * binding, DebugElement.properties will not return the correct value for that
  32226. * binding. However, there should be no runtime effect for real applications.
  32227. *
  32228. * This character is typically rendered as a question mark inside of a diamond.
  32229. * See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
  32230. *
  32231. */
  32232. var INTERPOLATION_DELIMITER = "\uFFFD";
  32233. /**
  32234. * Determines whether or not the given string is a property metadata string.
  32235. * See storeBindingMetadata().
  32236. */
  32237. function isPropMetadataString(str) {
  32238. return str.indexOf(INTERPOLATION_DELIMITER) >= 0;
  32239. }
  32240. /**
  32241. * Unwrap a value which might be behind a closure (for forward declaration reasons).
  32242. */
  32243. function maybeUnwrapFn(value) {
  32244. if (value instanceof Function) {
  32245. return value();
  32246. }
  32247. else {
  32248. return value;
  32249. }
  32250. }
  32251. /**
  32252. * @license
  32253. * Copyright Google Inc. All Rights Reserved.
  32254. *
  32255. * Use of this source code is governed by an MIT-style license that can be
  32256. * found in the LICENSE file at https://angular.io/license
  32257. */
  32258. // Below are constants for LView indices to help us look up LView members
  32259. // without having to remember the specific indices.
  32260. // Uglify will inline these when minifying so there shouldn't be a cost.
  32261. var HOST = 0;
  32262. var TVIEW = 1;
  32263. var FLAGS = 2;
  32264. var PARENT = 3;
  32265. var NEXT = 4;
  32266. var QUERIES = 5;
  32267. var T_HOST = 6;
  32268. var BINDING_INDEX = 7;
  32269. var CLEANUP = 8;
  32270. var CONTEXT = 9;
  32271. var INJECTOR$1 = 10;
  32272. var RENDERER_FACTORY = 11;
  32273. var RENDERER = 12;
  32274. var SANITIZER = 13;
  32275. var CHILD_HEAD = 14;
  32276. var CHILD_TAIL = 15;
  32277. var CONTENT_QUERIES = 16;
  32278. var DECLARATION_VIEW = 17;
  32279. var PREORDER_HOOK_FLAGS = 18;
  32280. /** Size of LView's header. Necessary to adjust for it when setting slots. */
  32281. var HEADER_OFFSET = 20;
  32282. /**
  32283. * @license
  32284. * Copyright Google Inc. All Rights Reserved.
  32285. *
  32286. * Use of this source code is governed by an MIT-style license that can be
  32287. * found in the LICENSE file at https://angular.io/license
  32288. */
  32289. function assertEqual(actual, expected, msg) {
  32290. if (actual != expected) {
  32291. throwError(msg);
  32292. }
  32293. }
  32294. function assertNotEqual(actual, expected, msg) {
  32295. if (actual == expected) {
  32296. throwError(msg);
  32297. }
  32298. }
  32299. function assertLessThan(actual, expected, msg) {
  32300. if (actual >= expected) {
  32301. throwError(msg);
  32302. }
  32303. }
  32304. function assertGreaterThan(actual, expected, msg) {
  32305. if (actual <= expected) {
  32306. throwError(msg);
  32307. }
  32308. }
  32309. function assertDefined(actual, msg) {
  32310. if (actual == null) {
  32311. throwError(msg);
  32312. }
  32313. }
  32314. function throwError(msg) {
  32315. // tslint:disable-next-line
  32316. debugger; // Left intentionally for better debugger experience.
  32317. throw new Error("ASSERTION ERROR: " + msg);
  32318. }
  32319. function assertDomNode(node) {
  32320. // If we're in a worker, `Node` will not be defined.
  32321. assertEqual((typeof Node !== 'undefined' && node instanceof Node) ||
  32322. (typeof node === 'object' && node.constructor.name === 'WebWorkerRenderNode'), true, "The provided value must be an instance of a DOM Node but got " + stringify$1(node));
  32323. }
  32324. function assertDataInRange(arr, index) {
  32325. var maxLen = arr ? arr.length : 0;
  32326. assertLessThan(index, maxLen, "Index expected to be less than " + maxLen + " but got " + index);
  32327. }
  32328. /**
  32329. * @license
  32330. * Copyright Google Inc. All Rights Reserved.
  32331. *
  32332. * Use of this source code is governed by an MIT-style license that can be
  32333. * found in the LICENSE file at https://angular.io/license
  32334. */
  32335. /**
  32336. * Special location which allows easy identification of type. If we have an array which was
  32337. * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is
  32338. * `LContainer`.
  32339. */
  32340. var TYPE = 1;
  32341. /**
  32342. * Below are constants for LContainer indices to help us look up LContainer members
  32343. * without having to remember the specific indices.
  32344. * Uglify will inline these when minifying so there shouldn't be a cost.
  32345. */
  32346. var ACTIVE_INDEX = 2;
  32347. // PARENT, NEXT, QUERIES and T_HOST are indices 3, 4, 5 and 6.
  32348. // As we already have these constants in LView, we don't need to re-create them.
  32349. var NATIVE = 7;
  32350. /**
  32351. * Size of LContainer's header. Represents the index after which all views in the
  32352. * container will be inserted. We need to keep a record of current views so we know
  32353. * which views are already in the DOM (and don't need to be re-added) and so we can
  32354. * remove views from the DOM when they are no longer required.
  32355. */
  32356. var CONTAINER_HEADER_OFFSET = 9;
  32357. /**
  32358. * @license
  32359. * Copyright Google Inc. All Rights Reserved.
  32360. *
  32361. * Use of this source code is governed by an MIT-style license that can be
  32362. * found in the LICENSE file at https://angular.io/license
  32363. */
  32364. /**
  32365. * This property will be monkey-patched on elements, components and directives
  32366. */
  32367. var MONKEY_PATCH_KEY_NAME = '__ngContext__';
  32368. /**
  32369. * @license
  32370. * Copyright Google Inc. All Rights Reserved.
  32371. *
  32372. * Use of this source code is governed by an MIT-style license that can be
  32373. * found in the LICENSE file at https://angular.io/license
  32374. */
  32375. /**
  32376. * For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`,
  32377. * `StylingContext`) in same location in `LView`. This is because we don't want to pre-allocate
  32378. * space for it because the storage is sparse. This file contains utilities for dealing with such
  32379. * data types.
  32380. *
  32381. * How do we know what is stored at a given location in `LView`.
  32382. * - `Array.isArray(value) === false` => `RNode` (The normal storage value)
  32383. * - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
  32384. * - `typeof value[TYPE] === 'object'` => `LView`
  32385. * - This happens when we have a component at a given location
  32386. * - `typeof value[TYPE] === 'number'` => `StylingContext`
  32387. * - This happens when we have style/class binding at a given location.
  32388. * - `typeof value[TYPE] === true` => `LContainer`
  32389. * - This happens when we have `LContainer` binding at a given location.
  32390. *
  32391. *
  32392. * NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
  32393. */
  32394. /**
  32395. * Returns `RNode`.
  32396. * @param value wrapped value of `RNode`, `LView`, `LContainer`, `StylingContext`
  32397. */
  32398. function unwrapRNode(value) {
  32399. while (Array.isArray(value)) {
  32400. value = value[HOST];
  32401. }
  32402. return value;
  32403. }
  32404. /**
  32405. * True if `value` is `LView`.
  32406. * @param value wrapped value of `RNode`, `LView`, `LContainer`, `StylingContext`
  32407. */
  32408. function isLView(value) {
  32409. return Array.isArray(value) && typeof value[TYPE] === 'object';
  32410. }
  32411. /**
  32412. * True if `value` is `LContainer`.
  32413. * @param value wrapped value of `RNode`, `LView`, `LContainer`, `StylingContext`
  32414. */
  32415. function isLContainer(value) {
  32416. return Array.isArray(value) && value[TYPE] === true;
  32417. }
  32418. /**
  32419. * True if `value` is `StylingContext`.
  32420. * @param value wrapped value of `RNode`, `LView`, `LContainer`, `StylingContext`
  32421. */
  32422. function isStylingContext(value) {
  32423. return Array.isArray(value) && typeof value[TYPE] === 'number';
  32424. }
  32425. function getNativeByTNode(tNode, hostView) {
  32426. return unwrapRNode(hostView[tNode.index]);
  32427. }
  32428. function getTNode(index, view) {
  32429. ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
  32430. ngDevMode && assertLessThan(index, view[TVIEW].data.length, 'wrong index for TNode');
  32431. return view[TVIEW].data[index + HEADER_OFFSET];
  32432. }
  32433. function getComponentViewByIndex(nodeIndex, hostView) {
  32434. // Could be an LView or an LContainer. If LContainer, unwrap to find LView.
  32435. var slotValue = hostView[nodeIndex];
  32436. var lView = isLView(slotValue) ? slotValue : slotValue[HOST];
  32437. return lView;
  32438. }
  32439. function isComponent(tNode) {
  32440. return (tNode.flags & 1 /* isComponent */) === 1 /* isComponent */;
  32441. }
  32442. function isComponentDef(def) {
  32443. return def.template !== null;
  32444. }
  32445. function isRootView(target) {
  32446. return (target[FLAGS] & 512 /* IsRoot */) !== 0;
  32447. }
  32448. /**
  32449. * Returns the monkey-patch value data present on the target (which could be
  32450. * a component, directive or a DOM node).
  32451. */
  32452. function readPatchedData(target) {
  32453. ngDevMode && assertDefined(target, 'Target expected');
  32454. return target[MONKEY_PATCH_KEY_NAME];
  32455. }
  32456. function readPatchedLView(target) {
  32457. var value = readPatchedData(target);
  32458. if (value) {
  32459. return Array.isArray(value) ? value : value.lView;
  32460. }
  32461. return null;
  32462. }
  32463. /**
  32464. * Returns a boolean for whether the view is attached to the change detection tree.
  32465. *
  32466. * Note: This determines whether a view should be checked, not whether it's inserted
  32467. * into a container. For that, you'll want `viewAttachedToContainer` below.
  32468. */
  32469. function viewAttachedToChangeDetector(view) {
  32470. return (view[FLAGS] & 128 /* Attached */) === 128 /* Attached */;
  32471. }
  32472. /** Returns a boolean for whether the view is attached to a container. */
  32473. function viewAttachedToContainer(view) {
  32474. return isLContainer(view[PARENT]);
  32475. }
  32476. /**
  32477. * Resets the pre-order hook flags of the view.
  32478. * @param lView the LView on which the flags are reset
  32479. */
  32480. function resetPreOrderHookFlags(lView) {
  32481. lView[PREORDER_HOOK_FLAGS] = 0;
  32482. }
  32483. /**
  32484. * @license
  32485. * Copyright Google Inc. All Rights Reserved.
  32486. *
  32487. * Use of this source code is governed by an MIT-style license that can be
  32488. * found in the LICENSE file at https://angular.io/license
  32489. */
  32490. function assertComponentType(actual, msg) {
  32491. if (msg === void 0) { msg = 'Type passed in is not ComponentType, it does not have \'ngComponentDef\' property.'; }
  32492. if (!getComponentDef(actual)) {
  32493. throwError(msg);
  32494. }
  32495. }
  32496. function assertPreviousIsParent(isParent) {
  32497. assertEqual(isParent, true, 'previousOrParentTNode should be a parent');
  32498. }
  32499. function assertLContainer(value) {
  32500. assertDefined(value, 'LContainer must be defined');
  32501. assertEqual(isLContainer(value), true, 'Expecting LContainer');
  32502. }
  32503. function assertLViewOrUndefined(value) {
  32504. value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');
  32505. }
  32506. function assertLView(value) {
  32507. assertDefined(value, 'LView must be defined');
  32508. assertEqual(isLView(value), true, 'Expecting LView');
  32509. }
  32510. /**
  32511. * @license
  32512. * Copyright Google Inc. All Rights Reserved.
  32513. *
  32514. * Use of this source code is governed by an MIT-style license that can be
  32515. * found in the LICENSE file at https://angular.io/license
  32516. */
  32517. /**
  32518. * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.
  32519. *
  32520. * Must be run *only* on the first template pass.
  32521. *
  32522. * Sets up the pre-order hooks on the provided `tView`,
  32523. * see {@link HookData} for details about the data structure.
  32524. *
  32525. * @param directiveIndex The index of the directive in LView
  32526. * @param directiveDef The definition containing the hooks to setup in tView
  32527. * @param tView The current TView
  32528. * @param nodeIndex The index of the node to which the directive is attached
  32529. * @param initialPreOrderHooksLength the number of pre-order hooks already registered before the
  32530. * current process, used to know if the node index has to be added to the array. If it is -1,
  32531. * the node index is never added.
  32532. * @param initialPreOrderCheckHooksLength same as previous for pre-order check hooks
  32533. */
  32534. function registerPreOrderHooks(directiveIndex, directiveDef, tView, nodeIndex, initialPreOrderHooksLength, initialPreOrderCheckHooksLength) {
  32535. ngDevMode &&
  32536. assertEqual(tView.firstTemplatePass, true, 'Should only be called on first template pass');
  32537. var onChanges = directiveDef.onChanges, onInit = directiveDef.onInit, doCheck = directiveDef.doCheck;
  32538. if (initialPreOrderHooksLength >= 0 &&
  32539. (!tView.preOrderHooks || initialPreOrderHooksLength === tView.preOrderHooks.length) &&
  32540. (onChanges || onInit || doCheck)) {
  32541. (tView.preOrderHooks || (tView.preOrderHooks = [])).push(nodeIndex);
  32542. }
  32543. if (initialPreOrderCheckHooksLength >= 0 &&
  32544. (!tView.preOrderCheckHooks ||
  32545. initialPreOrderCheckHooksLength === tView.preOrderCheckHooks.length) &&
  32546. (onChanges || doCheck)) {
  32547. (tView.preOrderCheckHooks || (tView.preOrderCheckHooks = [])).push(nodeIndex);
  32548. }
  32549. if (onChanges) {
  32550. (tView.preOrderHooks || (tView.preOrderHooks = [])).push(directiveIndex, onChanges);
  32551. (tView.preOrderCheckHooks || (tView.preOrderCheckHooks = [])).push(directiveIndex, onChanges);
  32552. }
  32553. if (onInit) {
  32554. (tView.preOrderHooks || (tView.preOrderHooks = [])).push(-directiveIndex, onInit);
  32555. }
  32556. if (doCheck) {
  32557. (tView.preOrderHooks || (tView.preOrderHooks = [])).push(directiveIndex, doCheck);
  32558. (tView.preOrderCheckHooks || (tView.preOrderCheckHooks = [])).push(directiveIndex, doCheck);
  32559. }
  32560. }
  32561. /**
  32562. *
  32563. * Loops through the directives on the provided `tNode` and queues hooks to be
  32564. * run that are not initialization hooks.
  32565. *
  32566. * Should be executed during `elementEnd()` and similar to
  32567. * preserve hook execution order. Content, view, and destroy hooks for projected
  32568. * components and directives must be called *before* their hosts.
  32569. *
  32570. * Sets up the content, view, and destroy hooks on the provided `tView`,
  32571. * see {@link HookData} for details about the data structure.
  32572. *
  32573. * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up
  32574. * separately at `elementStart`.
  32575. *
  32576. * @param tView The current TView
  32577. * @param tNode The TNode whose directives are to be searched for hooks to queue
  32578. */
  32579. function registerPostOrderHooks(tView, tNode) {
  32580. if (tView.firstTemplatePass) {
  32581. // It's necessary to loop through the directives at elementEnd() (rather than processing in
  32582. // directiveCreate) so we can preserve the current hook order. Content, view, and destroy
  32583. // hooks for projected components and directives must be called *before* their hosts.
  32584. for (var i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {
  32585. var directiveDef = tView.data[i];
  32586. if (directiveDef.afterContentInit) {
  32587. (tView.contentHooks || (tView.contentHooks = [])).push(-i, directiveDef.afterContentInit);
  32588. }
  32589. if (directiveDef.afterContentChecked) {
  32590. (tView.contentHooks || (tView.contentHooks = [])).push(i, directiveDef.afterContentChecked);
  32591. (tView.contentCheckHooks || (tView.contentCheckHooks = [])).push(i, directiveDef.afterContentChecked);
  32592. }
  32593. if (directiveDef.afterViewInit) {
  32594. (tView.viewHooks || (tView.viewHooks = [])).push(-i, directiveDef.afterViewInit);
  32595. }
  32596. if (directiveDef.afterViewChecked) {
  32597. (tView.viewHooks || (tView.viewHooks = [])).push(i, directiveDef.afterViewChecked);
  32598. (tView.viewCheckHooks || (tView.viewCheckHooks = [])).push(i, directiveDef.afterViewChecked);
  32599. }
  32600. if (directiveDef.onDestroy != null) {
  32601. (tView.destroyHooks || (tView.destroyHooks = [])).push(i, directiveDef.onDestroy);
  32602. }
  32603. }
  32604. }
  32605. }
  32606. /**
  32607. * Executing hooks requires complex logic as we need to deal with 2 constraints.
  32608. *
  32609. * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only
  32610. * once, across many change detection cycles. This must be true even if some hooks throw, or if
  32611. * some recursively trigger a change detection cycle.
  32612. * To solve that, it is required to track the state of the execution of these init hooks.
  32613. * This is done by storing and maintaining flags in the view: the {@link InitPhaseState},
  32614. * and the index within that phase. They can be seen as a cursor in the following structure:
  32615. * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]
  32616. * They are are stored as flags in LView[FLAGS].
  32617. *
  32618. * 2. Pre-order hooks can be executed in batches, because of the select instruction.
  32619. * To be able to pause and resume their execution, we also need some state about the hook's array
  32620. * that is being processed:
  32621. * - the index of the next hook to be executed
  32622. * - the number of init hooks already found in the processed part of the array
  32623. * They are are stored as flags in LView[PREORDER_HOOK_FLAGS].
  32624. */
  32625. /**
  32626. * Executes necessary hooks at the start of executing a template.
  32627. *
  32628. * Executes hooks that are to be run during the initialization of a directive such
  32629. * as `onChanges`, `onInit`, and `doCheck`.
  32630. *
  32631. * @param lView The current view
  32632. * @param tView Static data for the view containing the hooks to be executed
  32633. * @param checkNoChangesMode Whether or not we're in checkNoChanges mode.
  32634. * @param @param currentNodeIndex 2 cases depending the the value:
  32635. * - undefined: execute hooks only from the saved index until the end of the array (pre-order case,
  32636. * when flushing the remaining hooks)
  32637. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  32638. * case, when executing select(number))
  32639. */
  32640. function executePreOrderHooks(currentView, tView, checkNoChangesMode, currentNodeIndex) {
  32641. if (!checkNoChangesMode) {
  32642. executeHooks(currentView, tView.preOrderHooks, tView.preOrderCheckHooks, checkNoChangesMode, 0 /* OnInitHooksToBeRun */, currentNodeIndex !== undefined ? currentNodeIndex : null);
  32643. }
  32644. }
  32645. /**
  32646. * Executes hooks against the given `LView` based off of whether or not
  32647. * This is the first pass.
  32648. *
  32649. * @param currentView The view instance data to run the hooks against
  32650. * @param firstPassHooks An array of hooks to run if we're in the first view pass
  32651. * @param checkHooks An Array of hooks to run if we're not in the first view pass.
  32652. * @param checkNoChangesMode Whether or not we're in no changes mode.
  32653. * @param initPhaseState the current state of the init phase
  32654. * @param currentNodeIndex 3 cases depending the the value:
  32655. * - undefined: all hooks from the array should be executed (post-order case)
  32656. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  32657. * flushing the remaining hooks)
  32658. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  32659. * case, when executing select(number))
  32660. */
  32661. function executeHooks(currentView, firstPassHooks, checkHooks, checkNoChangesMode, initPhaseState, currentNodeIndex) {
  32662. if (checkNoChangesMode)
  32663. return;
  32664. var hooksToCall = (currentView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhaseState ?
  32665. firstPassHooks :
  32666. checkHooks;
  32667. if (hooksToCall) {
  32668. callHooks(currentView, hooksToCall, initPhaseState, currentNodeIndex);
  32669. }
  32670. // The init phase state must be always checked here as it may have been recursively updated
  32671. if (currentNodeIndex == null &&
  32672. (currentView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhaseState &&
  32673. initPhaseState !== 3 /* InitPhaseCompleted */) {
  32674. currentView[FLAGS] &= 1023 /* IndexWithinInitPhaseReset */;
  32675. currentView[FLAGS] += 1 /* InitPhaseStateIncrementer */;
  32676. }
  32677. }
  32678. /**
  32679. * Calls lifecycle hooks with their contexts, skipping init hooks if it's not
  32680. * the first LView pass
  32681. *
  32682. * @param currentView The current view
  32683. * @param arr The array in which the hooks are found
  32684. * @param initPhaseState the current state of the init phase
  32685. * @param currentNodeIndex 3 cases depending the the value:
  32686. * - undefined: all hooks from the array should be executed (post-order case)
  32687. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  32688. * flushing the remaining hooks)
  32689. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  32690. * case, when executing select(number))
  32691. */
  32692. function callHooks(currentView, arr, initPhase, currentNodeIndex) {
  32693. var startIndex = currentNodeIndex !== undefined ?
  32694. (currentView[PREORDER_HOOK_FLAGS] & 65535 /* IndexOfTheNextPreOrderHookMaskMask */) :
  32695. 0;
  32696. var nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;
  32697. var lastNodeIndexFound = 0;
  32698. for (var i = startIndex; i < arr.length; i++) {
  32699. var hook = arr[i + 1];
  32700. if (typeof hook === 'number') {
  32701. lastNodeIndexFound = arr[i];
  32702. if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {
  32703. break;
  32704. }
  32705. }
  32706. else {
  32707. var isInitHook = arr[i] < 0;
  32708. if (isInitHook)
  32709. currentView[PREORDER_HOOK_FLAGS] += 65536 /* NumberOfInitHooksCalledIncrementer */;
  32710. if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {
  32711. callHook(currentView, initPhase, arr, i);
  32712. currentView[PREORDER_HOOK_FLAGS] =
  32713. (currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* NumberOfInitHooksCalledMask */) + i +
  32714. 2;
  32715. }
  32716. i++;
  32717. }
  32718. }
  32719. }
  32720. /**
  32721. * Execute one hook against the current `LView`.
  32722. *
  32723. * @param currentView The current view
  32724. * @param initPhaseState the current state of the init phase
  32725. * @param arr The array in which the hooks are found
  32726. * @param i The current index within the hook data array
  32727. */
  32728. function callHook(currentView, initPhase, arr, i) {
  32729. var isInitHook = arr[i] < 0;
  32730. var hook = arr[i + 1];
  32731. var directiveIndex = isInitHook ? -arr[i] : arr[i];
  32732. var directive = currentView[directiveIndex];
  32733. if (isInitHook) {
  32734. var indexWithintInitPhase = currentView[FLAGS] >> 10 /* IndexWithinInitPhaseShift */;
  32735. // The init phase state must be always checked here as it may have been recursively
  32736. // updated
  32737. if (indexWithintInitPhase <
  32738. (currentView[PREORDER_HOOK_FLAGS] >> 16 /* NumberOfInitHooksCalledShift */) &&
  32739. (currentView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhase) {
  32740. currentView[FLAGS] += 1024 /* IndexWithinInitPhaseIncrementer */;
  32741. hook.call(directive);
  32742. }
  32743. }
  32744. else {
  32745. hook.call(directive);
  32746. }
  32747. }
  32748. /**
  32749. * @license
  32750. * Copyright Google Inc. All Rights Reserved.
  32751. *
  32752. * Use of this source code is governed by an MIT-style license that can be
  32753. * found in the LICENSE file at https://angular.io/license
  32754. */
  32755. function getLView() {
  32756. return lView;
  32757. }
  32758. /** Used to set the parent property when nodes are created and track query results. */
  32759. var previousOrParentTNode;
  32760. function getPreviousOrParentTNode() {
  32761. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  32762. return previousOrParentTNode;
  32763. }
  32764. function setPreviousOrParentTNode(tNode, _isParent) {
  32765. previousOrParentTNode = tNode;
  32766. isParent = _isParent;
  32767. }
  32768. function setTNodeAndViewData(tNode, view) {
  32769. ngDevMode && assertLViewOrUndefined(view);
  32770. previousOrParentTNode = tNode;
  32771. lView = view;
  32772. }
  32773. /**
  32774. * If `isParent` is:
  32775. * - `true`: then `previousOrParentTNode` points to a parent node.
  32776. * - `false`: then `previousOrParentTNode` points to previous node (sibling).
  32777. */
  32778. var isParent;
  32779. function getIsParent() {
  32780. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  32781. return isParent;
  32782. }
  32783. /** Checks whether a given view is in creation mode */
  32784. function isCreationMode(view) {
  32785. if (view === void 0) { view = lView; }
  32786. return (view[FLAGS] & 4 /* CreationMode */) === 4 /* CreationMode */;
  32787. }
  32788. /**
  32789. * State of the current view being processed.
  32790. *
  32791. * An array of nodes (text, element, container, etc), pipes, their bindings, and
  32792. * any local variables that need to be stored between invocations.
  32793. */
  32794. var lView;
  32795. /**
  32796. * The last viewData retrieved by nextContext().
  32797. * Allows building nextContext() and reference() calls.
  32798. *
  32799. * e.g. const inner = x().$implicit; const outer = x().$implicit;
  32800. */
  32801. var contextLView = null;
  32802. /**
  32803. * In this mode, any changes in bindings will throw an ExpressionChangedAfterChecked error.
  32804. *
  32805. * Necessary to support ChangeDetectorRef.checkNoChanges().
  32806. */
  32807. var checkNoChangesMode = false;
  32808. function getCheckNoChangesMode() {
  32809. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  32810. return checkNoChangesMode;
  32811. }
  32812. function setCheckNoChangesMode(mode) {
  32813. checkNoChangesMode = mode;
  32814. }
  32815. /**
  32816. * The root index from which pure function instructions should calculate their binding
  32817. * indices. In component views, this is TView.bindingStartIndex. In a host binding
  32818. * context, this is the TView.expandoStartIndex + any dirs/hostVars before the given dir.
  32819. */
  32820. var bindingRootIndex = -1;
  32821. function setBindingRoot(value) {
  32822. bindingRootIndex = value;
  32823. }
  32824. function setCurrentQueryIndex(value) {
  32825. }
  32826. /**
  32827. * Swap the current state with a new state.
  32828. *
  32829. * For performance reasons we store the state in the top level of the module.
  32830. * This way we minimize the number of properties to read. Whenever a new view
  32831. * is entered we have to store the state for later, and when the view is
  32832. * exited the state has to be restored
  32833. *
  32834. * @param newView New state to become active
  32835. * @param host Element to which the View is a child of
  32836. * @returns the previous state;
  32837. */
  32838. function enterView(newView, hostTNode) {
  32839. ngDevMode && assertLViewOrUndefined(newView);
  32840. var oldView = lView;
  32841. if (newView) {
  32842. var tView = newView[TVIEW];
  32843. bindingRootIndex = tView.bindingStartIndex;
  32844. }
  32845. previousOrParentTNode = hostTNode;
  32846. isParent = true;
  32847. lView = contextLView = newView;
  32848. return oldView;
  32849. }
  32850. /**
  32851. * Resets the application state.
  32852. */
  32853. function resetComponentState() {
  32854. isParent = false;
  32855. previousOrParentTNode = null;
  32856. }
  32857. /**
  32858. * Used in lieu of enterView to make it clear when we are exiting a child view. This makes
  32859. * the direction of traversal (up or down the view tree) a bit clearer.
  32860. *
  32861. * @param newView New state to become active
  32862. * @param safeToRunHooks Whether the runtime is in a state where running lifecycle hooks is valid.
  32863. * This is not always the case (for example, the application may have crashed and `leaveView` is
  32864. * being executed while unwinding the call stack).
  32865. */
  32866. function leaveView(newView, safeToRunHooks) {
  32867. var tView = lView[TVIEW];
  32868. if (isCreationMode(lView)) {
  32869. lView[FLAGS] &= ~4 /* CreationMode */;
  32870. }
  32871. else {
  32872. try {
  32873. resetPreOrderHookFlags(lView);
  32874. safeToRunHooks && executeHooks(lView, tView.viewHooks, tView.viewCheckHooks, checkNoChangesMode, 2 /* AfterViewInitHooksToBeRun */, undefined);
  32875. }
  32876. finally {
  32877. // Views are clean and in update mode after being checked, so these bits are cleared
  32878. lView[FLAGS] &= ~(64 /* Dirty */ | 8 /* FirstLViewPass */);
  32879. lView[BINDING_INDEX] = tView.bindingStartIndex;
  32880. }
  32881. }
  32882. enterView(newView, null);
  32883. }
  32884. var _currentNamespace = null;
  32885. /**
  32886. * Sets the namespace used to create elements no `null`, which forces element creation to use
  32887. * `createElement` rather than `createElementNS`.
  32888. *
  32889. * @codeGenApi
  32890. */
  32891. function ɵɵnamespaceHTML() {
  32892. _currentNamespace = null;
  32893. }
  32894. function getNamespace() {
  32895. return _currentNamespace;
  32896. }
  32897. /**
  32898. * @license
  32899. * Copyright Google Inc. All Rights Reserved.
  32900. *
  32901. * Use of this source code is governed by an MIT-style license that can be
  32902. * found in the LICENSE file at https://angular.io/license
  32903. */
  32904. /**
  32905. * @license
  32906. * Copyright Google Inc. All Rights Reserved.
  32907. *
  32908. * Use of this source code is governed by an MIT-style license that can be
  32909. * found in the LICENSE file at https://angular.io/license
  32910. */
  32911. /**
  32912. * This file is used to control if the default rendering pipeline should be `ViewEngine` or `Ivy`.
  32913. *
  32914. * For more information on how to run and debug tests with either Ivy or View Engine (legacy),
  32915. * please see [BAZEL.md](./docs/BAZEL.md).
  32916. */
  32917. var _devMode = true;
  32918. /**
  32919. * Returns whether Angular is in development mode. After called once,
  32920. * the value is locked and won't change any more.
  32921. *
  32922. * By default, this is true, unless a user calls `enableProdMode` before calling this.
  32923. *
  32924. * @publicApi
  32925. */
  32926. function isDevMode() {
  32927. return _devMode;
  32928. }
  32929. /**
  32930. * @license
  32931. * Copyright Google Inc. All Rights Reserved.
  32932. *
  32933. * Use of this source code is governed by an MIT-style license that can be
  32934. * found in the LICENSE file at https://angular.io/license
  32935. */
  32936. /**
  32937. * @license
  32938. * Copyright Google Inc. All Rights Reserved.
  32939. *
  32940. * Use of this source code is governed by an MIT-style license that can be
  32941. * found in the LICENSE file at https://angular.io/license
  32942. */
  32943. /**
  32944. * @license
  32945. * Copyright Google Inc. All Rights Reserved.
  32946. *
  32947. * Use of this source code is governed by an MIT-style license that can be
  32948. * found in the LICENSE file at https://angular.io/license
  32949. */
  32950. function tagSet(tags) {
  32951. var e_1, _a;
  32952. var res = {};
  32953. try {
  32954. for (var _b = __values(tags.split(',')), _c = _b.next(); !_c.done; _c = _b.next()) {
  32955. var t = _c.value;
  32956. res[t] = true;
  32957. }
  32958. }
  32959. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  32960. finally {
  32961. try {
  32962. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  32963. }
  32964. finally { if (e_1) throw e_1.error; }
  32965. }
  32966. return res;
  32967. }
  32968. function merge() {
  32969. var e_2, _a;
  32970. var sets = [];
  32971. for (var _i = 0; _i < arguments.length; _i++) {
  32972. sets[_i] = arguments[_i];
  32973. }
  32974. var res = {};
  32975. try {
  32976. for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
  32977. var s = sets_1_1.value;
  32978. for (var v in s) {
  32979. if (s.hasOwnProperty(v))
  32980. res[v] = true;
  32981. }
  32982. }
  32983. }
  32984. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  32985. finally {
  32986. try {
  32987. if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
  32988. }
  32989. finally { if (e_2) throw e_2.error; }
  32990. }
  32991. return res;
  32992. }
  32993. // Good source of info about elements and attributes
  32994. // http://dev.w3.org/html5/spec/Overview.html#semantics
  32995. // http://simon.html5.org/html-elements
  32996. // Safe Void Elements - HTML5
  32997. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  32998. var VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr');
  32999. // Elements that you can, intentionally, leave open (and which close themselves)
  33000. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  33001. var OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
  33002. var OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt');
  33003. var OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
  33004. // Safe Block Elements - HTML5
  33005. var BLOCK_ELEMENTS = merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet('address,article,' +
  33006. 'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
  33007. 'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
  33008. // Inline Elements - HTML5
  33009. var INLINE_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet('a,abbr,acronym,audio,b,' +
  33010. 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' +
  33011. 'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
  33012. var VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
  33013. // Attributes that have href and hence need to be sanitized
  33014. var URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
  33015. // Attributes that have special href set hence need to be sanitized
  33016. var SRCSET_ATTRS = tagSet('srcset');
  33017. var HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' +
  33018. 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +
  33019. 'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +
  33020. 'scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,' +
  33021. 'valign,value,vspace,width');
  33022. // Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018)
  33023. var ARIA_ATTRS = tagSet('aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' +
  33024. 'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' +
  33025. 'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' +
  33026. 'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' +
  33027. 'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' +
  33028. 'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' +
  33029. 'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext');
  33030. // NB: This currently consciously doesn't support SVG. SVG sanitization has had several security
  33031. // issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
  33032. // innerHTML is required, SVG attributes should be added here.
  33033. // NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
  33034. // can be sanitized, but they increase security surface area without a legitimate use case, so they
  33035. // are left out here.
  33036. var VALID_ATTRS = merge(URI_ATTRS, SRCSET_ATTRS, HTML_ATTRS, ARIA_ATTRS);
  33037. // Elements whose content should not be traversed/preserved, if the elements themselves are invalid.
  33038. //
  33039. // Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve)
  33040. // `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we
  33041. // don't want to preserve the content, if the elements themselves are going to be removed.
  33042. var SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = tagSet('script,style,template');
  33043. /**
  33044. * @license
  33045. * Copyright Google Inc. All Rights Reserved.
  33046. *
  33047. * Use of this source code is governed by an MIT-style license that can be
  33048. * found in the LICENSE file at https://angular.io/license
  33049. */
  33050. /**
  33051. * A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property
  33052. * like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly
  33053. * handled.
  33054. *
  33055. * See DomSanitizer for more details on security in Angular applications.
  33056. *
  33057. * @publicApi
  33058. */
  33059. var SecurityContext$1;
  33060. (function (SecurityContext) {
  33061. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  33062. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  33063. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  33064. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  33065. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  33066. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  33067. })(SecurityContext$1 || (SecurityContext$1 = {}));
  33068. /**
  33069. * Sanitizer is used by the views to sanitize potentially dangerous values.
  33070. *
  33071. * @publicApi
  33072. */
  33073. var Sanitizer = /** @class */ (function () {
  33074. function Sanitizer() {
  33075. }
  33076. return Sanitizer;
  33077. }());
  33078. /**
  33079. * @license
  33080. * Copyright Google Inc. All Rights Reserved.
  33081. *
  33082. * Use of this source code is governed by an MIT-style license that can be
  33083. * found in the LICENSE file at https://angular.io/license
  33084. */
  33085. /**
  33086. * @license
  33087. * Copyright Google Inc. All Rights Reserved.
  33088. *
  33089. * Use of this source code is governed by an MIT-style license that can be
  33090. * found in the LICENSE file at https://angular.io/license
  33091. */
  33092. /**
  33093. * @license
  33094. * Copyright Google Inc. All Rights Reserved.
  33095. *
  33096. * Use of this source code is governed by an MIT-style license that can be
  33097. * found in the LICENSE file at https://angular.io/license
  33098. */
  33099. var TNODE = 8;
  33100. var PARENT_INJECTOR = 8;
  33101. var INJECTOR_BLOOM_PARENT_SIZE = 9;
  33102. var NO_PARENT_INJECTOR = -1;
  33103. /**
  33104. * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in
  33105. * `TView.data`. This allows us to store information about the current node's tokens (which
  33106. * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be
  33107. * shared, so they live in `LView`).
  33108. *
  33109. * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter
  33110. * determines whether a directive is available on the associated node or not. This prevents us
  33111. * from searching the directives array at this level unless it's probable the directive is in it.
  33112. *
  33113. * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.
  33114. *
  33115. * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed
  33116. * using interfaces as they were previously. The start index of each `LInjector` and `TInjector`
  33117. * will differ based on where it is flattened into the main array, so it's not possible to know
  33118. * the indices ahead of time and save their types here. The interfaces are still included here
  33119. * for documentation purposes.
  33120. *
  33121. * export interface LInjector extends Array<any> {
  33122. *
  33123. * // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
  33124. * [0]: number;
  33125. *
  33126. * // Cumulative bloom for directive IDs 32-63
  33127. * [1]: number;
  33128. *
  33129. * // Cumulative bloom for directive IDs 64-95
  33130. * [2]: number;
  33131. *
  33132. * // Cumulative bloom for directive IDs 96-127
  33133. * [3]: number;
  33134. *
  33135. * // Cumulative bloom for directive IDs 128-159
  33136. * [4]: number;
  33137. *
  33138. * // Cumulative bloom for directive IDs 160 - 191
  33139. * [5]: number;
  33140. *
  33141. * // Cumulative bloom for directive IDs 192 - 223
  33142. * [6]: number;
  33143. *
  33144. * // Cumulative bloom for directive IDs 224 - 255
  33145. * [7]: number;
  33146. *
  33147. * // We need to store a reference to the injector's parent so DI can keep looking up
  33148. * // the injector tree until it finds the dependency it's looking for.
  33149. * [PARENT_INJECTOR]: number;
  33150. * }
  33151. *
  33152. * export interface TInjector extends Array<any> {
  33153. *
  33154. * // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
  33155. * [0]: number;
  33156. *
  33157. * // Shared node bloom for directive IDs 32-63
  33158. * [1]: number;
  33159. *
  33160. * // Shared node bloom for directive IDs 64-95
  33161. * [2]: number;
  33162. *
  33163. * // Shared node bloom for directive IDs 96-127
  33164. * [3]: number;
  33165. *
  33166. * // Shared node bloom for directive IDs 128-159
  33167. * [4]: number;
  33168. *
  33169. * // Shared node bloom for directive IDs 160 - 191
  33170. * [5]: number;
  33171. *
  33172. * // Shared node bloom for directive IDs 192 - 223
  33173. * [6]: number;
  33174. *
  33175. * // Shared node bloom for directive IDs 224 - 255
  33176. * [7]: number;
  33177. *
  33178. * // Necessary to find directive indices for a particular node.
  33179. * [TNODE]: TElementNode|TElementContainerNode|TContainerNode;
  33180. * }
  33181. */
  33182. /**
  33183. * Factory for creating instances of injectors in the NodeInjector.
  33184. *
  33185. * This factory is complicated by the fact that it can resolve `multi` factories as well.
  33186. *
  33187. * NOTE: Some of the fields are optional which means that this class has two hidden classes.
  33188. * - One without `multi` support (most common)
  33189. * - One with `multi` values, (rare).
  33190. *
  33191. * Since VMs can cache up to 4 inline hidden classes this is OK.
  33192. *
  33193. * - Single factory: Only `resolving` and `factory` is defined.
  33194. * - `providers` factory: `componentProviders` is a number and `index = -1`.
  33195. * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.
  33196. */
  33197. var NodeInjectorFactory = /** @class */ (function () {
  33198. function NodeInjectorFactory(
  33199. /**
  33200. * Factory to invoke in order to create a new instance.
  33201. */
  33202. factory,
  33203. /**
  33204. * Set to `true` if the token is declared in `viewProviders` (or if it is component).
  33205. */
  33206. isViewProvider, injectImplementation) {
  33207. this.factory = factory;
  33208. /**
  33209. * Marker set to true during factory invocation to see if we get into recursive loop.
  33210. * Recursive loop causes an error to be displayed.
  33211. */
  33212. this.resolving = false;
  33213. this.canSeeViewProviders = isViewProvider;
  33214. this.injectImpl = injectImplementation;
  33215. }
  33216. return NodeInjectorFactory;
  33217. }());
  33218. function isFactory(obj) {
  33219. // See: https://jsperf.com/instanceof-vs-getprototypeof
  33220. return obj !== null && typeof obj == 'object' &&
  33221. Object.getPrototypeOf(obj) == NodeInjectorFactory.prototype;
  33222. }
  33223. /**
  33224. * @license
  33225. * Copyright Google Inc. All Rights Reserved.
  33226. *
  33227. * Use of this source code is governed by an MIT-style license that can be
  33228. * found in the LICENSE file at https://angular.io/license
  33229. */
  33230. function assertNodeType(tNode, type) {
  33231. assertDefined(tNode, 'should be called with a TNode');
  33232. assertEqual(tNode.type, type, "should be a " + typeName(type));
  33233. }
  33234. function assertNodeOfPossibleTypes(tNode) {
  33235. var types = [];
  33236. for (var _i = 1; _i < arguments.length; _i++) {
  33237. types[_i - 1] = arguments[_i];
  33238. }
  33239. assertDefined(tNode, 'should be called with a TNode');
  33240. var found = types.some(function (type) { return tNode.type === type; });
  33241. assertEqual(found, true, "Should be one of " + types.map(typeName).join(', ') + " but got " + typeName(tNode.type));
  33242. }
  33243. function typeName(type) {
  33244. if (type == 1 /* Projection */)
  33245. return 'Projection';
  33246. if (type == 0 /* Container */)
  33247. return 'Container';
  33248. if (type == 2 /* View */)
  33249. return 'View';
  33250. if (type == 3 /* Element */)
  33251. return 'Element';
  33252. if (type == 4 /* ElementContainer */)
  33253. return 'ElementContainer';
  33254. return '<unknown>';
  33255. }
  33256. /**
  33257. * @license
  33258. * Copyright Google Inc. All Rights Reserved.
  33259. *
  33260. * Use of this source code is governed by an MIT-style license that can be
  33261. * found in the LICENSE file at https://angular.io/license
  33262. */
  33263. // TODO: cleanup once the code is merged in angular/angular
  33264. var RendererStyleFlags3;
  33265. (function (RendererStyleFlags3) {
  33266. RendererStyleFlags3[RendererStyleFlags3["Important"] = 1] = "Important";
  33267. RendererStyleFlags3[RendererStyleFlags3["DashCase"] = 2] = "DashCase";
  33268. })(RendererStyleFlags3 || (RendererStyleFlags3 = {}));
  33269. /** Returns whether the `renderer` is a `ProceduralRenderer3` */
  33270. function isProceduralRenderer(renderer) {
  33271. return !!(renderer.listen);
  33272. }
  33273. var ɵ0$7 = function (hostElement, rendererType) { return document; };
  33274. var domRendererFactory3 = {
  33275. createRenderer: ɵ0$7
  33276. };
  33277. /**
  33278. * @license
  33279. * Copyright Google Inc. All Rights Reserved.
  33280. *
  33281. * Use of this source code is governed by an MIT-style license that can be
  33282. * found in the LICENSE file at https://angular.io/license
  33283. */
  33284. /** Returns the matching `LContext` data for a given DOM node, directive or component instance.
  33285. *
  33286. * This function will examine the provided DOM element, component, or directive instance\'s
  33287. * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
  33288. * value will be that of the newly created `LContext`.
  33289. *
  33290. * If the monkey-patched value is the `LView` instance then the context value for that
  33291. * target will be created and the monkey-patch reference will be updated. Therefore when this
  33292. * function is called it may mutate the provided element\'s, component\'s or any of the associated
  33293. * directive\'s monkey-patch values.
  33294. *
  33295. * If the monkey-patch value is not detected then the code will walk up the DOM until an element
  33296. * is found which contains a monkey-patch reference. When that occurs then the provided element
  33297. * will be updated with a new context (which is then returned). If the monkey-patch value is not
  33298. * detected for a component/directive instance then it will throw an error (all components and
  33299. * directives should be automatically monkey-patched by ivy).
  33300. *
  33301. * @param target Component, Directive or DOM Node.
  33302. */
  33303. function getLContext(target) {
  33304. var mpValue = readPatchedData(target);
  33305. if (mpValue) {
  33306. // only when it's an array is it considered an LView instance
  33307. // ... otherwise it's an already constructed LContext instance
  33308. if (Array.isArray(mpValue)) {
  33309. var lView = mpValue;
  33310. var nodeIndex = void 0;
  33311. var component = undefined;
  33312. var directives = undefined;
  33313. if (isComponentInstance(target)) {
  33314. nodeIndex = findViaComponent(lView, target);
  33315. if (nodeIndex == -1) {
  33316. throw new Error('The provided component was not found in the application');
  33317. }
  33318. component = target;
  33319. }
  33320. else if (isDirectiveInstance(target)) {
  33321. nodeIndex = findViaDirective(lView, target);
  33322. if (nodeIndex == -1) {
  33323. throw new Error('The provided directive was not found in the application');
  33324. }
  33325. directives = getDirectivesAtNodeIndex(nodeIndex, lView, false);
  33326. }
  33327. else {
  33328. nodeIndex = findViaNativeElement(lView, target);
  33329. if (nodeIndex == -1) {
  33330. return null;
  33331. }
  33332. }
  33333. // the goal is not to fill the entire context full of data because the lookups
  33334. // are expensive. Instead, only the target data (the element, component, container, ICU
  33335. // expression or directive details) are filled into the context. If called multiple times
  33336. // with different target values then the missing target data will be filled in.
  33337. var native = unwrapRNode(lView[nodeIndex]);
  33338. var existingCtx = readPatchedData(native);
  33339. var context = (existingCtx && !Array.isArray(existingCtx)) ?
  33340. existingCtx :
  33341. createLContext(lView, nodeIndex, native);
  33342. // only when the component has been discovered then update the monkey-patch
  33343. if (component && context.component === undefined) {
  33344. context.component = component;
  33345. attachPatchData(context.component, context);
  33346. }
  33347. // only when the directives have been discovered then update the monkey-patch
  33348. if (directives && context.directives === undefined) {
  33349. context.directives = directives;
  33350. for (var i = 0; i < directives.length; i++) {
  33351. attachPatchData(directives[i], context);
  33352. }
  33353. }
  33354. attachPatchData(context.native, context);
  33355. mpValue = context;
  33356. }
  33357. }
  33358. else {
  33359. var rElement = target;
  33360. ngDevMode && assertDomNode(rElement);
  33361. // if the context is not found then we need to traverse upwards up the DOM
  33362. // to find the nearest element that has already been monkey patched with data
  33363. var parent_1 = rElement;
  33364. while (parent_1 = parent_1.parentNode) {
  33365. var parentContext = readPatchedData(parent_1);
  33366. if (parentContext) {
  33367. var lView = void 0;
  33368. if (Array.isArray(parentContext)) {
  33369. lView = parentContext;
  33370. }
  33371. else {
  33372. lView = parentContext.lView;
  33373. }
  33374. // the edge of the app was also reached here through another means
  33375. // (maybe because the DOM was changed manually).
  33376. if (!lView) {
  33377. return null;
  33378. }
  33379. var index = findViaNativeElement(lView, rElement);
  33380. if (index >= 0) {
  33381. var native = unwrapRNode(lView[index]);
  33382. var context = createLContext(lView, index, native);
  33383. attachPatchData(native, context);
  33384. mpValue = context;
  33385. break;
  33386. }
  33387. }
  33388. }
  33389. }
  33390. return mpValue || null;
  33391. }
  33392. /**
  33393. * Creates an empty instance of a `LContext` context
  33394. */
  33395. function createLContext(lView, nodeIndex, native) {
  33396. return {
  33397. lView: lView,
  33398. nodeIndex: nodeIndex,
  33399. native: native,
  33400. component: undefined,
  33401. directives: undefined,
  33402. localRefs: undefined,
  33403. };
  33404. }
  33405. /**
  33406. * Assigns the given data to the given target (which could be a component,
  33407. * directive or DOM node instance) using monkey-patching.
  33408. */
  33409. function attachPatchData(target, data) {
  33410. target[MONKEY_PATCH_KEY_NAME] = data;
  33411. }
  33412. function isComponentInstance(instance) {
  33413. return instance && instance.constructor && instance.constructor.ngComponentDef;
  33414. }
  33415. function isDirectiveInstance(instance) {
  33416. return instance && instance.constructor && instance.constructor.ngDirectiveDef;
  33417. }
  33418. /**
  33419. * Locates the element within the given LView and returns the matching index
  33420. */
  33421. function findViaNativeElement(lView, target) {
  33422. var tNode = lView[TVIEW].firstChild;
  33423. while (tNode) {
  33424. var native = getNativeByTNode(tNode, lView);
  33425. if (native === target) {
  33426. return tNode.index;
  33427. }
  33428. tNode = traverseNextElement(tNode);
  33429. }
  33430. return -1;
  33431. }
  33432. /**
  33433. * Locates the next tNode (child, sibling or parent).
  33434. */
  33435. function traverseNextElement(tNode) {
  33436. if (tNode.child) {
  33437. return tNode.child;
  33438. }
  33439. else if (tNode.next) {
  33440. return tNode.next;
  33441. }
  33442. else {
  33443. // Let's take the following template: <div><span>text</span></div><component/>
  33444. // After checking the text node, we need to find the next parent that has a "next" TNode,
  33445. // in this case the parent `div`, so that we can find the component.
  33446. while (tNode.parent && !tNode.parent.next) {
  33447. tNode = tNode.parent;
  33448. }
  33449. return tNode.parent && tNode.parent.next;
  33450. }
  33451. }
  33452. /**
  33453. * Locates the component within the given LView and returns the matching index
  33454. */
  33455. function findViaComponent(lView, componentInstance) {
  33456. var componentIndices = lView[TVIEW].components;
  33457. if (componentIndices) {
  33458. for (var i = 0; i < componentIndices.length; i++) {
  33459. var elementComponentIndex = componentIndices[i];
  33460. var componentView = getComponentViewByIndex(elementComponentIndex, lView);
  33461. if (componentView[CONTEXT] === componentInstance) {
  33462. return elementComponentIndex;
  33463. }
  33464. }
  33465. }
  33466. else {
  33467. var rootComponentView = getComponentViewByIndex(HEADER_OFFSET, lView);
  33468. var rootComponent = rootComponentView[CONTEXT];
  33469. if (rootComponent === componentInstance) {
  33470. // we are dealing with the root element here therefore we know that the
  33471. // element is the very first element after the HEADER data in the lView
  33472. return HEADER_OFFSET;
  33473. }
  33474. }
  33475. return -1;
  33476. }
  33477. /**
  33478. * Locates the directive within the given LView and returns the matching index
  33479. */
  33480. function findViaDirective(lView, directiveInstance) {
  33481. // if a directive is monkey patched then it will (by default)
  33482. // have a reference to the LView of the current view. The
  33483. // element bound to the directive being search lives somewhere
  33484. // in the view data. We loop through the nodes and check their
  33485. // list of directives for the instance.
  33486. var tNode = lView[TVIEW].firstChild;
  33487. while (tNode) {
  33488. var directiveIndexStart = tNode.directiveStart;
  33489. var directiveIndexEnd = tNode.directiveEnd;
  33490. for (var i = directiveIndexStart; i < directiveIndexEnd; i++) {
  33491. if (lView[i] === directiveInstance) {
  33492. return tNode.index;
  33493. }
  33494. }
  33495. tNode = traverseNextElement(tNode);
  33496. }
  33497. return -1;
  33498. }
  33499. /**
  33500. * Returns a list of directives extracted from the given view based on the
  33501. * provided list of directive index values.
  33502. *
  33503. * @param nodeIndex The node index
  33504. * @param lView The target view data
  33505. * @param includeComponents Whether or not to include components in returned directives
  33506. */
  33507. function getDirectivesAtNodeIndex(nodeIndex, lView, includeComponents) {
  33508. var tNode = lView[TVIEW].data[nodeIndex];
  33509. var directiveStartIndex = tNode.directiveStart;
  33510. if (directiveStartIndex == 0)
  33511. return EMPTY_ARRAY$3;
  33512. var directiveEndIndex = tNode.directiveEnd;
  33513. if (!includeComponents && tNode.flags & 1 /* isComponent */)
  33514. directiveStartIndex++;
  33515. return lView.slice(directiveStartIndex, directiveEndIndex);
  33516. }
  33517. function getComponentAtNodeIndex(nodeIndex, lView) {
  33518. var tNode = lView[TVIEW].data[nodeIndex];
  33519. var directiveStartIndex = tNode.directiveStart;
  33520. return tNode.flags & 1 /* isComponent */ ? lView[directiveStartIndex] : null;
  33521. }
  33522. /**
  33523. * Returns a map of local references (local reference name => element or directive instance) that
  33524. * exist on a given element.
  33525. */
  33526. function discoverLocalRefs(lView, nodeIndex) {
  33527. var tNode = lView[TVIEW].data[nodeIndex];
  33528. if (tNode && tNode.localNames) {
  33529. var result = {};
  33530. var localIndex = tNode.index + 1;
  33531. for (var i = 0; i < tNode.localNames.length; i += 2) {
  33532. result[tNode.localNames[i]] = lView[localIndex];
  33533. localIndex++;
  33534. }
  33535. return result;
  33536. }
  33537. return null;
  33538. }
  33539. /**
  33540. * @license
  33541. * Copyright Google Inc. All Rights Reserved.
  33542. *
  33543. * Use of this source code is governed by an MIT-style license that can be
  33544. * found in the LICENSE file at https://angular.io/license
  33545. */
  33546. /**
  33547. * The default directive styling index value for template-based bindings.
  33548. *
  33549. * All host-level bindings (e.g. `hostStyleProp` and `hostStyleMap`) are
  33550. * assigned a directive styling index value based on the current directive
  33551. * uniqueId and the directive super-class inheritance depth. But for template
  33552. * bindings they always have the same directive styling index value.
  33553. */
  33554. var DEFAULT_TEMPLATE_DIRECTIVE_INDEX = 0;
  33555. /**
  33556. * @license
  33557. * Copyright Google Inc. All Rights Reserved.
  33558. *
  33559. * Use of this source code is governed by an MIT-style license that can be
  33560. * found in the LICENSE file at https://angular.io/license
  33561. */
  33562. function createEmptyStylingContext(wrappedElement, sanitizer, initialStyles, initialClasses) {
  33563. var context = [
  33564. wrappedElement || null,
  33565. 0,
  33566. [],
  33567. initialStyles || [null, null],
  33568. initialClasses || [null, null],
  33569. [0, 0],
  33570. [0],
  33571. [0],
  33572. null,
  33573. null,
  33574. ];
  33575. // whenever a context is created there is always a `null` directive
  33576. // that is registered (which is a placeholder for the "template").
  33577. allocateOrUpdateDirectiveIntoContext(context, DEFAULT_TEMPLATE_DIRECTIVE_INDEX);
  33578. return context;
  33579. }
  33580. /**
  33581. * Allocates (registers) a directive into the directive registry within the provided styling
  33582. * context.
  33583. *
  33584. * For each and every `[style]`, `[style.prop]`, `[class]`, `[class.name]` binding
  33585. * (as well as static style and class attributes) a directive, component or template
  33586. * is marked as the owner. When an owner is determined (this happens when the template
  33587. * is first passed over) the directive owner is allocated into the styling context. When
  33588. * this happens, each owner gets its own index value. This then ensures that once any
  33589. * style and/or class binding are assigned into the context then they are marked to
  33590. * that directive's index value.
  33591. *
  33592. * @param context the target StylingContext
  33593. * @param directiveRef the directive that will be allocated into the context
  33594. * @returns the index where the directive was inserted into
  33595. */
  33596. function allocateOrUpdateDirectiveIntoContext(context, directiveIndex, singlePropValuesIndex, styleSanitizer) {
  33597. if (singlePropValuesIndex === void 0) { singlePropValuesIndex = -1; }
  33598. var directiveRegistry = context[2 /* DirectiveRegistryPosition */];
  33599. var index = directiveIndex * 2 /* Size */;
  33600. // we preemptively make space into the directives array and then
  33601. // assign values slot-by-slot to ensure that if the directive ordering
  33602. // changes then it will still function
  33603. var limit = index + 2 /* Size */;
  33604. for (var i = directiveRegistry.length; i < limit; i += 2 /* Size */) {
  33605. // -1 is used to signal that the directive has been allocated, but
  33606. // no actual style or class bindings have been registered yet...
  33607. directiveRegistry.push(-1, null);
  33608. }
  33609. var propValuesStartPosition = index + 0 /* SinglePropValuesIndexOffset */;
  33610. if (singlePropValuesIndex >= 0 && directiveRegistry[propValuesStartPosition] === -1) {
  33611. directiveRegistry[propValuesStartPosition] = singlePropValuesIndex;
  33612. directiveRegistry[index + 1 /* StyleSanitizerOffset */] =
  33613. styleSanitizer || null;
  33614. }
  33615. }
  33616. /**
  33617. * Used clone a copy of a pre-computed template of a styling context.
  33618. *
  33619. * A pre-computed template is designed to be computed once for a given element
  33620. * (instructions.ts has logic for caching this).
  33621. */
  33622. function allocStylingContext(element, templateStyleContext) {
  33623. // each instance gets a copy
  33624. var context = templateStyleContext.slice();
  33625. // the HEADER values contain arrays which also need
  33626. // to be copied over into the new context
  33627. for (var i = 0; i < 10 /* SingleStylesStartPosition */; i++) {
  33628. var value = templateStyleContext[i];
  33629. if (Array.isArray(value)) {
  33630. context[i] = value.slice();
  33631. }
  33632. }
  33633. context[0 /* ElementPosition */] = element;
  33634. // this will prevent any other directives from extending the context
  33635. context[1 /* MasterFlagPosition */] |= 16 /* BindingAllocationLocked */;
  33636. return context;
  33637. }
  33638. /**
  33639. * Retrieve the `StylingContext` at a given index.
  33640. *
  33641. * This method lazily creates the `StylingContext`. This is because in most cases
  33642. * we have styling without any bindings. Creating `StylingContext` eagerly would mean that
  33643. * every style declaration such as `<div style="color: red">` would result `StyleContext`
  33644. * which would create unnecessary memory pressure.
  33645. *
  33646. * @param index Index of the style allocation. See: `styling`.
  33647. * @param viewData The view to search for the styling context
  33648. */
  33649. function getStylingContextFromLView(index, viewData) {
  33650. var storageIndex = index;
  33651. var slotValue = viewData[storageIndex];
  33652. var wrapper = viewData;
  33653. while (Array.isArray(slotValue)) {
  33654. wrapper = slotValue;
  33655. slotValue = slotValue[HOST];
  33656. }
  33657. if (isStylingContext(wrapper)) {
  33658. return wrapper;
  33659. }
  33660. else {
  33661. // This is an LView or an LContainer
  33662. var stylingTemplate = getTNode(index - HEADER_OFFSET, viewData).stylingTemplate;
  33663. if (wrapper !== viewData) {
  33664. storageIndex = HOST;
  33665. }
  33666. return wrapper[storageIndex] = stylingTemplate ?
  33667. allocStylingContext(slotValue, stylingTemplate) :
  33668. createEmptyStylingContext(slotValue);
  33669. }
  33670. }
  33671. /**
  33672. * @license
  33673. * Copyright Google Inc. All Rights Reserved.
  33674. *
  33675. * Use of this source code is governed by an MIT-style license that can be
  33676. * found in the LICENSE file at https://angular.io/license
  33677. */
  33678. /// Parent Injector Utils ///////////////////////////////////////////////////////////////
  33679. function hasParentInjector(parentLocation) {
  33680. return parentLocation !== NO_PARENT_INJECTOR;
  33681. }
  33682. function getParentInjectorIndex(parentLocation) {
  33683. return parentLocation & 32767 /* InjectorIndexMask */;
  33684. }
  33685. function getParentInjectorViewOffset(parentLocation) {
  33686. return parentLocation >> 16 /* ViewOffsetShift */;
  33687. }
  33688. /**
  33689. * Unwraps a parent injector location number to find the view offset from the current injector,
  33690. * then walks up the declaration view tree until the view is found that contains the parent
  33691. * injector.
  33692. *
  33693. * @param location The location of the parent injector, which contains the view offset
  33694. * @param startView The LView instance from which to start walking up the view tree
  33695. * @returns The LView instance that contains the parent injector
  33696. */
  33697. function getParentInjectorView(location, startView) {
  33698. var viewOffset = getParentInjectorViewOffset(location);
  33699. var parentView = startView;
  33700. // For most cases, the parent injector can be found on the host node (e.g. for component
  33701. // or container), but we must keep the loop here to support the rarer case of deeply nested
  33702. // <ng-template> tags or inline views, where the parent injector might live many views
  33703. // above the child injector.
  33704. while (viewOffset > 0) {
  33705. parentView = parentView[DECLARATION_VIEW];
  33706. viewOffset--;
  33707. }
  33708. return parentView;
  33709. }
  33710. /**
  33711. * @license
  33712. * Copyright Google Inc. All Rights Reserved.
  33713. *
  33714. * Use of this source code is governed by an MIT-style license that can be
  33715. * found in the LICENSE file at https://angular.io/license
  33716. */
  33717. /**
  33718. * Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
  33719. * that LContainer, which is an LView
  33720. * @param lView the lView whose parent to get
  33721. */
  33722. function getLViewParent(lView) {
  33723. ngDevMode && assertLView(lView);
  33724. var parent = lView[PARENT];
  33725. return isLContainer(parent) ? parent[PARENT] : parent;
  33726. }
  33727. /**
  33728. * Retrieve the root view from any component or `LView` by walking the parent `LView` until
  33729. * reaching the root `LView`.
  33730. *
  33731. * @param componentOrLView any component or `LView`
  33732. */
  33733. function getRootView(componentOrLView) {
  33734. ngDevMode && assertDefined(componentOrLView, 'component');
  33735. var lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);
  33736. while (lView && !(lView[FLAGS] & 512 /* IsRoot */)) {
  33737. lView = getLViewParent(lView);
  33738. }
  33739. ngDevMode && assertLView(lView);
  33740. return lView;
  33741. }
  33742. /**
  33743. * Given an `LView`, find the closest declaration view which is not an embedded view.
  33744. *
  33745. * This method searches for the `LView` associated with the component which declared the `LView`.
  33746. *
  33747. * This function may return itself if the `LView` passed in is not an embedded `LView`. Otherwise
  33748. * it walks the declaration parents until it finds a component view (non-embedded-view.)
  33749. *
  33750. * @param lView LView for which we want a host element node
  33751. * @returns The host node
  33752. */
  33753. function findComponentView(lView) {
  33754. var rootTNode = lView[T_HOST];
  33755. while (rootTNode !== null && rootTNode.type === 2 /* View */) {
  33756. ngDevMode && assertDefined(lView[DECLARATION_VIEW], 'lView[DECLARATION_VIEW]');
  33757. lView = lView[DECLARATION_VIEW];
  33758. rootTNode = lView[T_HOST];
  33759. }
  33760. ngDevMode && assertLView(lView);
  33761. return lView;
  33762. }
  33763. /**
  33764. * Returns the `RootContext` instance that is associated with
  33765. * the application where the target is situated. It does this by walking the parent views until it
  33766. * gets to the root view, then getting the context off of that.
  33767. *
  33768. * @param viewOrComponent the `LView` or component to get the root context for.
  33769. */
  33770. function getRootContext(viewOrComponent) {
  33771. var rootView = getRootView(viewOrComponent);
  33772. ngDevMode &&
  33773. assertDefined(rootView[CONTEXT], 'RootView has no context. Perhaps it is disconnected?');
  33774. return rootView[CONTEXT];
  33775. }
  33776. /**
  33777. * @license
  33778. * Copyright Google Inc. All Rights Reserved.
  33779. *
  33780. * Use of this source code is governed by an MIT-style license that can be
  33781. * found in the LICENSE file at https://angular.io/license
  33782. */
  33783. /**
  33784. * Defines if the call to `inject` should include `viewProviders` in its resolution.
  33785. *
  33786. * This is set to true when we try to instantiate a component. This value is reset in
  33787. * `getNodeInjectable` to a value which matches the declaration location of the token about to be
  33788. * instantiated. This is done so that if we are injecting a token which was declared outside of
  33789. * `viewProviders` we don't accidentally pull `viewProviders` in.
  33790. *
  33791. * Example:
  33792. *
  33793. * ```
  33794. * @Injectable()
  33795. * class MyService {
  33796. * constructor(public value: String) {}
  33797. * }
  33798. *
  33799. * @Component({
  33800. * providers: [
  33801. * MyService,
  33802. * {provide: String, value: 'providers' }
  33803. * ]
  33804. * viewProviders: [
  33805. * {provide: String, value: 'viewProviders'}
  33806. * ]
  33807. * })
  33808. * class MyComponent {
  33809. * constructor(myService: MyService, value: String) {
  33810. * // We expect that Component can see into `viewProviders`.
  33811. * expect(value).toEqual('viewProviders');
  33812. * // `MyService` was not declared in `viewProviders` hence it can't see it.
  33813. * expect(myService.value).toEqual('providers');
  33814. * }
  33815. * }
  33816. *
  33817. * ```
  33818. */
  33819. var includeViewProviders = true;
  33820. function setIncludeViewProviders(v) {
  33821. var oldValue = includeViewProviders;
  33822. includeViewProviders = v;
  33823. return oldValue;
  33824. }
  33825. /**
  33826. * The number of slots in each bloom filter (used by DI). The larger this number, the fewer
  33827. * directives that will share slots, and thus, the fewer false positives when checking for
  33828. * the existence of a directive.
  33829. */
  33830. var BLOOM_SIZE = 256;
  33831. var BLOOM_MASK = BLOOM_SIZE - 1;
  33832. /** Counter used to generate unique IDs for directives. */
  33833. var nextNgElementId = 0;
  33834. /**
  33835. * Registers this directive as present in its node's injector by flipping the directive's
  33836. * corresponding bit in the injector's bloom filter.
  33837. *
  33838. * @param injectorIndex The index of the node injector where this token should be registered
  33839. * @param tView The TView for the injector's bloom filters
  33840. * @param type The directive token to register
  33841. */
  33842. function bloomAdd(injectorIndex, tView, type) {
  33843. ngDevMode && assertEqual(tView.firstTemplatePass, true, 'expected firstTemplatePass to be true');
  33844. var id = typeof type !== 'string' ? type[NG_ELEMENT_ID] : type.charCodeAt(0) || 0;
  33845. // Set a unique ID on the directive type, so if something tries to inject the directive,
  33846. // we can easily retrieve the ID and hash it into the bloom bit that should be checked.
  33847. if (id == null) {
  33848. id = type[NG_ELEMENT_ID] = nextNgElementId++;
  33849. }
  33850. // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
  33851. // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
  33852. var bloomBit = id & BLOOM_MASK;
  33853. // Create a mask that targets the specific bit associated with the directive.
  33854. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  33855. // to bit positions 0 - 31 in a 32 bit integer.
  33856. var mask = 1 << bloomBit;
  33857. // Use the raw bloomBit number to determine which bloom filter bucket we should check
  33858. // e.g: bf0 = [0 - 31], bf1 = [32 - 63], bf2 = [64 - 95], bf3 = [96 - 127], etc
  33859. var b7 = bloomBit & 0x80;
  33860. var b6 = bloomBit & 0x40;
  33861. var b5 = bloomBit & 0x20;
  33862. var tData = tView.data;
  33863. if (b7) {
  33864. b6 ? (b5 ? (tData[injectorIndex + 7] |= mask) : (tData[injectorIndex + 6] |= mask)) :
  33865. (b5 ? (tData[injectorIndex + 5] |= mask) : (tData[injectorIndex + 4] |= mask));
  33866. }
  33867. else {
  33868. b6 ? (b5 ? (tData[injectorIndex + 3] |= mask) : (tData[injectorIndex + 2] |= mask)) :
  33869. (b5 ? (tData[injectorIndex + 1] |= mask) : (tData[injectorIndex] |= mask));
  33870. }
  33871. }
  33872. /**
  33873. * Creates (or gets an existing) injector for a given element or container.
  33874. *
  33875. * @param tNode for which an injector should be retrieved / created.
  33876. * @param hostView View where the node is stored
  33877. * @returns Node injector
  33878. */
  33879. function getOrCreateNodeInjectorForNode(tNode, hostView) {
  33880. var existingInjectorIndex = getInjectorIndex(tNode, hostView);
  33881. if (existingInjectorIndex !== -1) {
  33882. return existingInjectorIndex;
  33883. }
  33884. var tView = hostView[TVIEW];
  33885. if (tView.firstTemplatePass) {
  33886. tNode.injectorIndex = hostView.length;
  33887. insertBloom(tView.data, tNode); // foundation for node bloom
  33888. insertBloom(hostView, null); // foundation for cumulative bloom
  33889. insertBloom(tView.blueprint, null);
  33890. ngDevMode && assertEqual(tNode.flags === 0 || tNode.flags === 1 /* isComponent */, true, 'expected tNode.flags to not be initialized');
  33891. }
  33892. var parentLoc = getParentInjectorLocation(tNode, hostView);
  33893. var parentIndex = getParentInjectorIndex(parentLoc);
  33894. var parentLView = getParentInjectorView(parentLoc, hostView);
  33895. var injectorIndex = tNode.injectorIndex;
  33896. // If a parent injector can't be found, its location is set to -1.
  33897. // In that case, we don't need to set up a cumulative bloom
  33898. if (hasParentInjector(parentLoc)) {
  33899. var parentData = parentLView[TVIEW].data;
  33900. // Creates a cumulative bloom filter that merges the parent's bloom filter
  33901. // and its own cumulative bloom (which contains tokens for all ancestors)
  33902. for (var i = 0; i < 8; i++) {
  33903. hostView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
  33904. }
  33905. }
  33906. hostView[injectorIndex + PARENT_INJECTOR] = parentLoc;
  33907. return injectorIndex;
  33908. }
  33909. function insertBloom(arr, footer) {
  33910. arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
  33911. }
  33912. function getInjectorIndex(tNode, hostView) {
  33913. if (tNode.injectorIndex === -1 ||
  33914. // If the injector index is the same as its parent's injector index, then the index has been
  33915. // copied down from the parent node. No injector has been created yet on this node.
  33916. (tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) ||
  33917. // After the first template pass, the injector index might exist but the parent values
  33918. // might not have been calculated yet for this instance
  33919. hostView[tNode.injectorIndex + PARENT_INJECTOR] == null) {
  33920. return -1;
  33921. }
  33922. else {
  33923. return tNode.injectorIndex;
  33924. }
  33925. }
  33926. /**
  33927. * Finds the index of the parent injector, with a view offset if applicable. Used to set the
  33928. * parent injector initially.
  33929. *
  33930. * Returns a combination of number of `ViewData` we have to go up and index in that `Viewdata`
  33931. */
  33932. function getParentInjectorLocation(tNode, view) {
  33933. if (tNode.parent && tNode.parent.injectorIndex !== -1) {
  33934. return tNode.parent.injectorIndex; // ViewOffset is 0
  33935. }
  33936. // For most cases, the parent injector index can be found on the host node (e.g. for component
  33937. // or container), so this loop will be skipped, but we must keep the loop here to support
  33938. // the rarer case of deeply nested <ng-template> tags or inline views.
  33939. var hostTNode = view[T_HOST];
  33940. var viewOffset = 1;
  33941. while (hostTNode && hostTNode.injectorIndex === -1) {
  33942. view = view[DECLARATION_VIEW];
  33943. hostTNode = view ? view[T_HOST] : null;
  33944. viewOffset++;
  33945. }
  33946. return hostTNode ?
  33947. hostTNode.injectorIndex | (viewOffset << 16 /* ViewOffsetShift */) :
  33948. -1;
  33949. }
  33950. /**
  33951. * Makes a type or an injection token public to the DI system by adding it to an
  33952. * injector's bloom filter.
  33953. *
  33954. * @param di The node injector in which a directive will be added
  33955. * @param token The type or the injection token to be made public
  33956. */
  33957. function diPublicInInjector(injectorIndex, view, token) {
  33958. bloomAdd(injectorIndex, view[TVIEW], token);
  33959. }
  33960. /**
  33961. * Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
  33962. *
  33963. * Look for the injector providing the token by walking up the node injector tree and then
  33964. * the module injector tree.
  33965. *
  33966. * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
  33967. * filter. Negative values are reserved for special objects.
  33968. * - `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
  33969. *
  33970. * @param tNode The Node where the search for the injector should start
  33971. * @param lView The `LView` that contains the `tNode`
  33972. * @param token The token to look for
  33973. * @param flags Injection flags
  33974. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  33975. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  33976. */
  33977. function getOrCreateInjectable(tNode, lView, token, flags, notFoundValue) {
  33978. if (flags === void 0) { flags = InjectFlags.Default; }
  33979. if (tNode) {
  33980. var bloomHash = bloomHashBitOrFactory(token);
  33981. // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
  33982. // so just call the factory function to create it.
  33983. if (typeof bloomHash === 'function') {
  33984. var savePreviousOrParentTNode = getPreviousOrParentTNode();
  33985. var saveLView = getLView();
  33986. setTNodeAndViewData(tNode, lView);
  33987. try {
  33988. var value = bloomHash();
  33989. if (value == null && !(flags & InjectFlags.Optional)) {
  33990. throw new Error("No provider for " + stringifyForError(token) + "!");
  33991. }
  33992. else {
  33993. return value;
  33994. }
  33995. }
  33996. finally {
  33997. setTNodeAndViewData(savePreviousOrParentTNode, saveLView);
  33998. }
  33999. }
  34000. else if (typeof bloomHash == 'number') {
  34001. if (bloomHash === -1) {
  34002. // `-1` is a special value used to identify `Injector` types.
  34003. return new NodeInjector(tNode, lView);
  34004. }
  34005. // If the token has a bloom hash, then it is a token which could be in NodeInjector.
  34006. // A reference to the previous injector TView that was found while climbing the element
  34007. // injector tree. This is used to know if viewProviders can be accessed on the current
  34008. // injector.
  34009. var previousTView = null;
  34010. var injectorIndex = getInjectorIndex(tNode, lView);
  34011. var parentLocation = NO_PARENT_INJECTOR;
  34012. var hostTElementNode = flags & InjectFlags.Host ? findComponentView(lView)[T_HOST] : null;
  34013. // If we should skip this injector, or if there is no injector on this node, start by
  34014. // searching
  34015. // the parent injector.
  34016. if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
  34017. parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) :
  34018. lView[injectorIndex + PARENT_INJECTOR];
  34019. if (!shouldSearchParent(flags, false)) {
  34020. injectorIndex = -1;
  34021. }
  34022. else {
  34023. previousTView = lView[TVIEW];
  34024. injectorIndex = getParentInjectorIndex(parentLocation);
  34025. lView = getParentInjectorView(parentLocation, lView);
  34026. }
  34027. }
  34028. // Traverse up the injector tree until we find a potential match or until we know there
  34029. // *isn't* a match.
  34030. while (injectorIndex !== -1) {
  34031. parentLocation = lView[injectorIndex + PARENT_INJECTOR];
  34032. // Check the current injector. If it matches, see if it contains token.
  34033. var tView = lView[TVIEW];
  34034. if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
  34035. // At this point, we have an injector which *may* contain the token, so we step through
  34036. // the providers and directives associated with the injector's corresponding node to get
  34037. // the instance.
  34038. var instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
  34039. if (instance !== NOT_FOUND) {
  34040. return instance;
  34041. }
  34042. }
  34043. if (shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + TNODE] === hostTElementNode) &&
  34044. bloomHasToken(bloomHash, injectorIndex, lView)) {
  34045. // The def wasn't found anywhere on this node, so it was a false positive.
  34046. // Traverse up the tree and continue searching.
  34047. previousTView = tView;
  34048. injectorIndex = getParentInjectorIndex(parentLocation);
  34049. lView = getParentInjectorView(parentLocation, lView);
  34050. }
  34051. else {
  34052. // If we should not search parent OR If the ancestor bloom filter value does not have the
  34053. // bit corresponding to the directive we can give up on traversing up to find the specific
  34054. // injector.
  34055. injectorIndex = -1;
  34056. }
  34057. }
  34058. }
  34059. }
  34060. if (flags & InjectFlags.Optional && notFoundValue === undefined) {
  34061. // This must be set or the NullInjector will throw for optional deps
  34062. notFoundValue = null;
  34063. }
  34064. if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
  34065. var moduleInjector = lView[INJECTOR$1];
  34066. // switch to `injectInjectorOnly` implementation for module injector, since module injector
  34067. // should not have access to Component/Directive DI scope (that may happen through
  34068. // `directiveInject` implementation)
  34069. var previousInjectImplementation = setInjectImplementation(undefined);
  34070. try {
  34071. if (moduleInjector) {
  34072. return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
  34073. }
  34074. else {
  34075. return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
  34076. }
  34077. }
  34078. finally {
  34079. setInjectImplementation(previousInjectImplementation);
  34080. }
  34081. }
  34082. if (flags & InjectFlags.Optional) {
  34083. return notFoundValue;
  34084. }
  34085. else {
  34086. throw new Error("NodeInjector: NOT_FOUND [" + stringifyForError(token) + "]");
  34087. }
  34088. }
  34089. var NOT_FOUND = {};
  34090. function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
  34091. var currentTView = lView[TVIEW];
  34092. var tNode = currentTView.data[injectorIndex + TNODE];
  34093. // First, we need to determine if view providers can be accessed by the starting element.
  34094. // There are two possibities
  34095. var canAccessViewProviders = previousTView == null ?
  34096. // 1) This is the first invocation `previousTView == null` which means that we are at the
  34097. // `TNode` of where injector is starting to look. In such a case the only time we are allowed
  34098. // to look into the ViewProviders is if:
  34099. // - we are on a component
  34100. // - AND the injector set `includeViewProviders` to true (implying that the token can see
  34101. // ViewProviders because it is the Component or a Service which itself was declared in
  34102. // ViewProviders)
  34103. (isComponent(tNode) && includeViewProviders) :
  34104. // 2) `previousTView != null` which means that we are now walking across the parent nodes.
  34105. // In such a case we are only allowed to look into the ViewProviders if:
  34106. // - We just crossed from child View to Parent View `previousTView != currentTView`
  34107. // - AND the parent TNode is an Element.
  34108. // This means that we just came from the Component's View and therefore are allowed to see
  34109. // into the ViewProviders.
  34110. (previousTView != currentTView && (tNode.type === 3 /* Element */));
  34111. // This special case happens when there is a @host on the inject and when we are searching
  34112. // on the host element node.
  34113. var isHostSpecialCase = (flags & InjectFlags.Host) && hostTElementNode === tNode;
  34114. var injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
  34115. if (injectableIdx !== null) {
  34116. return getNodeInjectable(currentTView.data, lView, injectableIdx, tNode);
  34117. }
  34118. else {
  34119. return NOT_FOUND;
  34120. }
  34121. }
  34122. /**
  34123. * Searches for the given token among the node's directives and providers.
  34124. *
  34125. * @param tNode TNode on which directives are present.
  34126. * @param tView The tView we are currently processing
  34127. * @param token Provider token or type of a directive to look for.
  34128. * @param canAccessViewProviders Whether view providers should be considered.
  34129. * @param isHostSpecialCase Whether the host special case applies.
  34130. * @returns Index of a found directive or provider, or null when none found.
  34131. */
  34132. function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
  34133. var nodeProviderIndexes = tNode.providerIndexes;
  34134. var tInjectables = tView.data;
  34135. var injectablesStart = nodeProviderIndexes & 65535 /* ProvidersStartIndexMask */;
  34136. var directivesStart = tNode.directiveStart;
  34137. var directiveEnd = tNode.directiveEnd;
  34138. var cptViewProvidersCount = nodeProviderIndexes >> 16 /* CptViewProvidersCountShift */;
  34139. var startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount;
  34140. // When the host special case applies, only the viewProviders and the component are visible
  34141. var endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
  34142. for (var i = startingIndex; i < endIndex; i++) {
  34143. var providerTokenOrDef = tInjectables[i];
  34144. if (i < directivesStart && token === providerTokenOrDef ||
  34145. i >= directivesStart && providerTokenOrDef.type === token) {
  34146. return i;
  34147. }
  34148. }
  34149. if (isHostSpecialCase) {
  34150. var dirDef = tInjectables[directivesStart];
  34151. if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
  34152. return directivesStart;
  34153. }
  34154. }
  34155. return null;
  34156. }
  34157. /**
  34158. * Retrieve or instantiate the injectable from the `lData` at particular `index`.
  34159. *
  34160. * This function checks to see if the value has already been instantiated and if so returns the
  34161. * cached `injectable`. Otherwise if it detects that the value is still a factory it
  34162. * instantiates the `injectable` and caches the value.
  34163. */
  34164. function getNodeInjectable(tData, lData, index, tNode) {
  34165. var value = lData[index];
  34166. if (isFactory(value)) {
  34167. var factory = value;
  34168. if (factory.resolving) {
  34169. throw new Error("Circular dep for " + stringifyForError(tData[index]));
  34170. }
  34171. var previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
  34172. factory.resolving = true;
  34173. var previousInjectImplementation = void 0;
  34174. if (factory.injectImpl) {
  34175. previousInjectImplementation = setInjectImplementation(factory.injectImpl);
  34176. }
  34177. var savePreviousOrParentTNode = getPreviousOrParentTNode();
  34178. var saveLView = getLView();
  34179. setTNodeAndViewData(tNode, lData);
  34180. try {
  34181. value = lData[index] = factory.factory(null, tData, lData, tNode);
  34182. }
  34183. finally {
  34184. if (factory.injectImpl)
  34185. setInjectImplementation(previousInjectImplementation);
  34186. setIncludeViewProviders(previousIncludeViewProviders);
  34187. factory.resolving = false;
  34188. setTNodeAndViewData(savePreviousOrParentTNode, saveLView);
  34189. }
  34190. }
  34191. return value;
  34192. }
  34193. /**
  34194. * Returns the bit in an injector's bloom filter that should be used to determine whether or not
  34195. * the directive might be provided by the injector.
  34196. *
  34197. * When a directive is public, it is added to the bloom filter and given a unique ID that can be
  34198. * retrieved on the Type. When the directive isn't public or the token is not a directive `null`
  34199. * is returned as the node injector can not possibly provide that token.
  34200. *
  34201. * @param token the injection token
  34202. * @returns the matching bit to check in the bloom filter or `null` if the token is not known.
  34203. * When the returned value is negative then it represents special values such as `Injector`.
  34204. */
  34205. function bloomHashBitOrFactory(token) {
  34206. ngDevMode && assertDefined(token, 'token must be defined');
  34207. if (typeof token === 'string') {
  34208. return token.charCodeAt(0) || 0;
  34209. }
  34210. var tokenId = token[NG_ELEMENT_ID];
  34211. // Negative token IDs are used for special objects such as `Injector`
  34212. return (typeof tokenId === 'number' && tokenId > 0) ? tokenId & BLOOM_MASK : tokenId;
  34213. }
  34214. function bloomHasToken(bloomHash, injectorIndex, injectorView) {
  34215. // Create a mask that targets the specific bit associated with the directive we're looking for.
  34216. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  34217. // to bit positions 0 - 31 in a 32 bit integer.
  34218. var mask = 1 << bloomHash;
  34219. var b7 = bloomHash & 0x80;
  34220. var b6 = bloomHash & 0x40;
  34221. var b5 = bloomHash & 0x20;
  34222. // Our bloom filter size is 256 bits, which is eight 32-bit bloom filter buckets:
  34223. // bf0 = [0 - 31], bf1 = [32 - 63], bf2 = [64 - 95], bf3 = [96 - 127], etc.
  34224. // Get the bloom filter value from the appropriate bucket based on the directive's bloomBit.
  34225. var value;
  34226. if (b7) {
  34227. value = b6 ? (b5 ? injectorView[injectorIndex + 7] : injectorView[injectorIndex + 6]) :
  34228. (b5 ? injectorView[injectorIndex + 5] : injectorView[injectorIndex + 4]);
  34229. }
  34230. else {
  34231. value = b6 ? (b5 ? injectorView[injectorIndex + 3] : injectorView[injectorIndex + 2]) :
  34232. (b5 ? injectorView[injectorIndex + 1] : injectorView[injectorIndex]);
  34233. }
  34234. // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
  34235. // this injector is a potential match.
  34236. return !!(value & mask);
  34237. }
  34238. /** Returns true if flags prevent parent injector from being searched for tokens */
  34239. function shouldSearchParent(flags, isFirstHostTNode) {
  34240. return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
  34241. }
  34242. var NodeInjector = /** @class */ (function () {
  34243. function NodeInjector(_tNode, _lView) {
  34244. this._tNode = _tNode;
  34245. this._lView = _lView;
  34246. }
  34247. NodeInjector.prototype.get = function (token, notFoundValue) {
  34248. return getOrCreateInjectable(this._tNode, this._lView, token, undefined, notFoundValue);
  34249. };
  34250. return NodeInjector;
  34251. }());
  34252. /**
  34253. * @license
  34254. * Copyright Google Inc. All Rights Reserved.
  34255. *
  34256. * Use of this source code is governed by an MIT-style license that can be
  34257. * found in the LICENSE file at https://angular.io/license
  34258. */
  34259. function getDebugContext(error) {
  34260. return error[ERROR_DEBUG_CONTEXT];
  34261. }
  34262. function getOriginalError(error) {
  34263. return error[ERROR_ORIGINAL_ERROR];
  34264. }
  34265. function getErrorLogger(error) {
  34266. return error[ERROR_LOGGER] || defaultErrorLogger;
  34267. }
  34268. function defaultErrorLogger(console) {
  34269. var values = [];
  34270. for (var _i = 1; _i < arguments.length; _i++) {
  34271. values[_i - 1] = arguments[_i];
  34272. }
  34273. console.error.apply(console, __spread(values));
  34274. }
  34275. /**
  34276. * @license
  34277. * Copyright Google Inc. All Rights Reserved.
  34278. *
  34279. * Use of this source code is governed by an MIT-style license that can be
  34280. * found in the LICENSE file at https://angular.io/license
  34281. */
  34282. /**
  34283. * Provides a hook for centralized exception handling.
  34284. *
  34285. * The default implementation of `ErrorHandler` prints error messages to the `console`. To
  34286. * intercept error handling, write a custom exception handler that replaces this default as
  34287. * appropriate for your app.
  34288. *
  34289. * @usageNotes
  34290. * ### Example
  34291. *
  34292. * ```
  34293. * class MyErrorHandler implements ErrorHandler {
  34294. * handleError(error) {
  34295. * // do something with the exception
  34296. * }
  34297. * }
  34298. *
  34299. * @NgModule({
  34300. * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
  34301. * })
  34302. * class MyModule {}
  34303. * ```
  34304. *
  34305. * @publicApi
  34306. */
  34307. var ErrorHandler = /** @class */ (function () {
  34308. function ErrorHandler() {
  34309. /**
  34310. * @internal
  34311. */
  34312. this._console = console;
  34313. }
  34314. ErrorHandler.prototype.handleError = function (error) {
  34315. var originalError = this._findOriginalError(error);
  34316. var context = this._findContext(error);
  34317. // Note: Browser consoles show the place from where console.error was called.
  34318. // We can use this to give users additional information about the error.
  34319. var errorLogger = getErrorLogger(error);
  34320. errorLogger(this._console, "ERROR", error);
  34321. if (originalError) {
  34322. errorLogger(this._console, "ORIGINAL ERROR", originalError);
  34323. }
  34324. if (context) {
  34325. errorLogger(this._console, 'ERROR CONTEXT', context);
  34326. }
  34327. };
  34328. /** @internal */
  34329. ErrorHandler.prototype._findContext = function (error) {
  34330. if (error) {
  34331. return getDebugContext(error) ? getDebugContext(error) :
  34332. this._findContext(getOriginalError(error));
  34333. }
  34334. return null;
  34335. };
  34336. /** @internal */
  34337. ErrorHandler.prototype._findOriginalError = function (error) {
  34338. var e = getOriginalError(error);
  34339. while (e && getOriginalError(e)) {
  34340. e = getOriginalError(e);
  34341. }
  34342. return e;
  34343. };
  34344. return ErrorHandler;
  34345. }());
  34346. /**
  34347. * @license
  34348. * Copyright Google Inc. All Rights Reserved.
  34349. *
  34350. * Use of this source code is governed by an MIT-style license that can be
  34351. * found in the LICENSE file at https://angular.io/license
  34352. */
  34353. /**
  34354. * @license
  34355. * Copyright Google Inc. All Rights Reserved.
  34356. *
  34357. * Use of this source code is governed by an MIT-style license that can be
  34358. * found in the LICENSE file at https://angular.io/license
  34359. */
  34360. /**
  34361. * THIS FILE CONTAINS CODE WHICH SHOULD BE TREE SHAKEN AND NEVER CALLED FROM PRODUCTION CODE!!!
  34362. */
  34363. /**
  34364. * Creates an `Array` construction with a given name. This is useful when
  34365. * looking for memory consumption to see what time of array it is.
  34366. *
  34367. *
  34368. * @param name Name to give to the constructor
  34369. * @returns A subclass of `Array` if possible. This can only be done in
  34370. * environments which support `class` construct.
  34371. */
  34372. function createNamedArrayType(name) {
  34373. // This should never be called in prod mode, so let's verify that is the case.
  34374. if (ngDevMode) {
  34375. try {
  34376. // We need to do it this way so that TypeScript does not down-level the below code.
  34377. var FunctionConstructor = createNamedArrayType.constructor;
  34378. return (new FunctionConstructor('Array', "return class ABC extends Array{}"))(Array);
  34379. }
  34380. catch (e) {
  34381. // If it does not work just give up and fall back to regular Array.
  34382. return Array;
  34383. }
  34384. }
  34385. else {
  34386. throw new Error('Looks like we are in \'prod mode\', but we are creating a named Array type, which is wrong! Check your code');
  34387. }
  34388. }
  34389. /**
  34390. * @license
  34391. * Copyright Google Inc. All Rights Reserved.
  34392. *
  34393. * Use of this source code is governed by an MIT-style license that can be
  34394. * found in the LICENSE file at https://angular.io/license
  34395. */
  34396. function normalizeDebugBindingName(name) {
  34397. // Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
  34398. name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
  34399. return "ng-reflect-" + name;
  34400. }
  34401. var CAMEL_CASE_REGEXP = /([A-Z])/g;
  34402. function camelCaseToDashCase(input) {
  34403. return input.replace(CAMEL_CASE_REGEXP, function () {
  34404. var m = [];
  34405. for (var _i = 0; _i < arguments.length; _i++) {
  34406. m[_i] = arguments[_i];
  34407. }
  34408. return '-' + m[1].toLowerCase();
  34409. });
  34410. }
  34411. function normalizeDebugBindingValue(value) {
  34412. try {
  34413. // Limit the size of the value as otherwise the DOM just gets polluted.
  34414. return value != null ? value.toString().slice(0, 30) : value;
  34415. }
  34416. catch (e) {
  34417. return '[ERROR] Exception while trying to serialize the value';
  34418. }
  34419. }
  34420. // Note: This hack is necessary so we don't erroneously get a circular dependency
  34421. /**
  34422. * @license
  34423. * Copyright Google Inc. All Rights Reserved.
  34424. *
  34425. * Use of this source code is governed by an MIT-style license that can be
  34426. * found in the LICENSE file at https://angular.io/license
  34427. */
  34428. /**
  34429. * @license
  34430. * Copyright Google Inc. All Rights Reserved.
  34431. *
  34432. * Use of this source code is governed by an MIT-style license that can be
  34433. * found in the LICENSE file at https://angular.io/license
  34434. */
  34435. /** A special value which designates that a value has not changed. */
  34436. var NO_CHANGE = {};
  34437. /**
  34438. * Combines the binding value and a factory for an animation player.
  34439. *
  34440. * Used to bind a player to an element template binding (currently only
  34441. * `[style]`, `[style.prop]`, `[class]` and `[class.name]` bindings
  34442. * supported). The provided `factoryFn` function will be run once all
  34443. * the associated bindings have been evaluated on the element and is
  34444. * designed to return a player which will then be placed on the element.
  34445. *
  34446. * @param factoryFn The function that is used to create a player
  34447. * once all the rendering-related (styling values) have been
  34448. * processed for the element binding.
  34449. * @param value The raw value that will be exposed to the binding
  34450. * so that the binding can update its internal values when
  34451. * any changes are evaluated.
  34452. */
  34453. /**
  34454. * Runs through the initial class values present in the provided
  34455. * context and renders them via the provided renderer on the element.
  34456. *
  34457. * @param element the element the styling will be applied to
  34458. * @param context the source styling context which contains the initial class values
  34459. * @param renderer the renderer instance that will be used to apply the class
  34460. * @returns the index that the classes were applied up until
  34461. */
  34462. function renderInitialClasses(element, context, renderer, startIndex) {
  34463. var initialClasses = context[4 /* InitialClassValuesPosition */];
  34464. var i = startIndex || 2 /* KeyValueStartPosition */;
  34465. while (i < initialClasses.length) {
  34466. var value = initialClasses[i + 1 /* ValueOffset */];
  34467. if (value) {
  34468. setClass(element, initialClasses[i + 0 /* PropOffset */], true, renderer, null);
  34469. }
  34470. i += 3 /* Size */;
  34471. }
  34472. return i;
  34473. }
  34474. /**
  34475. * Runs through the initial styles values present in the provided
  34476. * context and renders them via the provided renderer on the element.
  34477. *
  34478. * @param element the element the styling will be applied to
  34479. * @param context the source styling context which contains the initial class values
  34480. * @param renderer the renderer instance that will be used to apply the class
  34481. * @returns the index that the styles were applied up until
  34482. */
  34483. function renderInitialStyles(element, context, renderer, startIndex) {
  34484. var initialStyles = context[3 /* InitialStyleValuesPosition */];
  34485. var i = startIndex || 2 /* KeyValueStartPosition */;
  34486. while (i < initialStyles.length) {
  34487. var value = initialStyles[i + 1 /* ValueOffset */];
  34488. if (value) {
  34489. setStyle(element, initialStyles[i + 0 /* PropOffset */], value, renderer, null);
  34490. }
  34491. i += 3 /* Size */;
  34492. }
  34493. return i;
  34494. }
  34495. /**
  34496. * Assigns a style value to a style property for the given element.
  34497. *
  34498. * This function renders a given CSS prop/value entry using the
  34499. * provided renderer. If a `store` value is provided then
  34500. * that will be used a render context instead of the provided
  34501. * renderer.
  34502. *
  34503. * @param native the DOM Element
  34504. * @param prop the CSS style property that will be rendered
  34505. * @param value the CSS style value that will be rendered
  34506. * @param renderer
  34507. * @param store an optional key/value map that will be used as a context to render styles on
  34508. */
  34509. function setStyle(native, prop, value, renderer, sanitizer, store, playerBuilder) {
  34510. value =
  34511. sanitizer && value ? sanitizer(prop, value, 3 /* ValidateAndSanitize */) : value;
  34512. if (store || playerBuilder) {
  34513. if (store) {
  34514. store.setValue(prop, value);
  34515. }
  34516. if (playerBuilder) {
  34517. playerBuilder.setValue(prop, value);
  34518. }
  34519. }
  34520. else if (value) {
  34521. value = value.toString(); // opacity, z-index and flexbox all have number values which may not
  34522. // assign as numbers
  34523. ngDevMode && ngDevMode.rendererSetStyle++;
  34524. isProceduralRenderer(renderer) ?
  34525. renderer.setStyle(native, prop, value, RendererStyleFlags3.DashCase) :
  34526. native.style.setProperty(prop, value);
  34527. }
  34528. else {
  34529. ngDevMode && ngDevMode.rendererRemoveStyle++;
  34530. isProceduralRenderer(renderer) ?
  34531. renderer.removeStyle(native, prop, RendererStyleFlags3.DashCase) :
  34532. native.style.removeProperty(prop);
  34533. }
  34534. }
  34535. /**
  34536. * Adds/removes the provided className value to the provided element.
  34537. *
  34538. * This function renders a given CSS class value using the provided
  34539. * renderer (by adding or removing it from the provided element).
  34540. * If a `store` value is provided then that will be used a render
  34541. * context instead of the provided renderer.
  34542. *
  34543. * @param native the DOM Element
  34544. * @param prop the CSS style property that will be rendered
  34545. * @param value the CSS style value that will be rendered
  34546. * @param renderer
  34547. * @param store an optional key/value map that will be used as a context to render styles on
  34548. */
  34549. function setClass(native, className, add, renderer, store, playerBuilder) {
  34550. if (store || playerBuilder) {
  34551. if (store) {
  34552. store.setValue(className, add);
  34553. }
  34554. if (playerBuilder) {
  34555. playerBuilder.setValue(className, add);
  34556. }
  34557. // DOMTokenList will throw if we try to add or remove an empty string.
  34558. }
  34559. else if (className !== '') {
  34560. if (add) {
  34561. ngDevMode && ngDevMode.rendererAddClass++;
  34562. isProceduralRenderer(renderer) ? renderer.addClass(native, className) :
  34563. native['classList'].add(className);
  34564. }
  34565. else {
  34566. ngDevMode && ngDevMode.rendererRemoveClass++;
  34567. isProceduralRenderer(renderer) ? renderer.removeClass(native, className) :
  34568. native['classList'].remove(className);
  34569. }
  34570. }
  34571. }
  34572. function isClassBasedValue(context, index) {
  34573. var adjustedIndex = index >= 10 /* SingleStylesStartPosition */ ? (index + 0 /* FlagsOffset */) : index;
  34574. return (context[adjustedIndex] & 2 /* Class */) == 2 /* Class */;
  34575. }
  34576. function getValue(context, index) {
  34577. return context[index + 2 /* ValueOffset */];
  34578. }
  34579. function getProp(context, index) {
  34580. return context[index + 1 /* PropertyOffset */];
  34581. }
  34582. /**
  34583. * @license
  34584. * Copyright Google Inc. All Rights Reserved.
  34585. *
  34586. * Use of this source code is governed by an MIT-style license that can be
  34587. * found in the LICENSE file at https://angular.io/license
  34588. */
  34589. /**
  34590. * @license
  34591. * Copyright Google Inc. All Rights Reserved.
  34592. *
  34593. * Use of this source code is governed by an MIT-style license that can be
  34594. * found in the LICENSE file at https://angular.io/license
  34595. */
  34596. /**
  34597. * Marks that the next string is for element.
  34598. *
  34599. * See `I18nMutateOpCodes` documentation.
  34600. */
  34601. var ELEMENT_MARKER = {
  34602. marker: 'element'
  34603. };
  34604. /**
  34605. * Marks that the next string is for comment.
  34606. *
  34607. * See `I18nMutateOpCodes` documentation.
  34608. */
  34609. var COMMENT_MARKER = {
  34610. marker: 'comment'
  34611. };
  34612. var _stylingMode$1 = 0;
  34613. function runtimeIsNewStylingInUse() {
  34614. return _stylingMode$1 > 0 /* UseOld */;
  34615. }
  34616. var _currentSanitizer;
  34617. function setCurrentStyleSanitizer(sanitizer) {
  34618. _currentSanitizer = sanitizer;
  34619. }
  34620. function getCurrentStyleSanitizer() {
  34621. return _currentSanitizer;
  34622. }
  34623. /**
  34624. * @license
  34625. * Copyright Google Inc. All Rights Reserved.
  34626. *
  34627. * Use of this source code is governed by an MIT-style license that can be
  34628. * found in the LICENSE file at https://angular.io/license
  34629. */
  34630. function attachDebugObject(obj, debug) {
  34631. Object.defineProperty(obj, 'debug', { value: debug, enumerable: false });
  34632. }
  34633. /**
  34634. * @license
  34635. * Copyright Google Inc. All Rights Reserved.
  34636. *
  34637. * Use of this source code is governed by an MIT-style license that can be
  34638. * found in the LICENSE file at https://angular.io/license
  34639. */
  34640. function getConfig(context) {
  34641. return context[0 /* ConfigPosition */];
  34642. }
  34643. function getProp$1(context, index) {
  34644. return context[index + 2 /* PropOffset */];
  34645. }
  34646. function getPropConfig(context, index) {
  34647. return context[index + 0 /* ConfigAndGuardOffset */] &
  34648. 1 /* Mask */;
  34649. }
  34650. function isSanitizationRequired(context, index) {
  34651. return (getPropConfig(context, index) & 1 /* SanitizationRequired */) > 0;
  34652. }
  34653. function getGuardMask(context, index) {
  34654. var configGuardValue = context[index + 0 /* ConfigAndGuardOffset */];
  34655. return configGuardValue >> 1 /* TotalBits */;
  34656. }
  34657. function setGuardMask(context, index, maskValue) {
  34658. var config = getPropConfig(context, index);
  34659. var guardMask = maskValue << 1 /* TotalBits */;
  34660. context[index + 0 /* ConfigAndGuardOffset */] = config | guardMask;
  34661. }
  34662. function getValuesCount(context, index) {
  34663. return context[index + 1 /* ValuesCountOffset */];
  34664. }
  34665. function getBindingValue(context, index, offset) {
  34666. return context[index + 3 /* BindingsStartOffset */ + offset];
  34667. }
  34668. function getDefaultValue(context, index) {
  34669. var valuesCount = getValuesCount(context, index);
  34670. return context[index + 3 /* BindingsStartOffset */ + valuesCount - 1];
  34671. }
  34672. function isContextLocked(context) {
  34673. return (getConfig(context) & 1 /* Locked */) > 0;
  34674. }
  34675. function getPropValuesStartPosition(context) {
  34676. return 5 /* MapBindingsBindingsStartPosition */ +
  34677. context[3 /* MapBindingsValuesCountPosition */];
  34678. }
  34679. /**
  34680. * Determines whether the provided styling value is truthy or falsy.
  34681. */
  34682. function isStylingValueDefined(value) {
  34683. // the reason why null is compared against is because
  34684. // a CSS class value that is set to `false` must be
  34685. // respected (otherwise it would be treated as falsy).
  34686. // Empty string values are because developers usually
  34687. // set a value to an empty string to remove it.
  34688. return value != null && value !== '';
  34689. }
  34690. /**
  34691. * Returns the current style sanitizer function for the given view.
  34692. *
  34693. * The default style sanitizer (which lives inside of `LView`) will
  34694. * be returned depending on whether the `styleSanitizer` instruction
  34695. * was called or not prior to any styling instructions running.
  34696. */
  34697. function getCurrentOrLViewSanitizer(lView) {
  34698. var sanitizer = (getCurrentStyleSanitizer() || lView[SANITIZER]);
  34699. if (sanitizer && typeof sanitizer !== 'function') {
  34700. setCurrentStyleSanitizer(sanitizer);
  34701. return sanitizeUsingSanitizerObject;
  34702. }
  34703. return sanitizer;
  34704. }
  34705. /**
  34706. * Style sanitization function that internally uses a `Sanitizer` instance to handle style
  34707. * sanitization.
  34708. */
  34709. var sanitizeUsingSanitizerObject = function (prop, value, mode) {
  34710. var sanitizer = getCurrentStyleSanitizer();
  34711. if (sanitizer) {
  34712. if (mode & 2 /* SanitizeOnly */) {
  34713. return sanitizer.sanitize(SecurityContext$1.STYLE, value);
  34714. }
  34715. else {
  34716. return true;
  34717. }
  34718. }
  34719. return value;
  34720. };
  34721. /**
  34722. * --------
  34723. *
  34724. * This file contains the core logic for styling in Angular.
  34725. *
  34726. * All styling bindings (i.e. `[style]`, `[style.prop]`, `[class]` and `[class.name]`)
  34727. * will have their values be applied through the logic in this file.
  34728. *
  34729. * When a binding is encountered (e.g. `<div [style.width]="w">`) then
  34730. * the binding data will be populated into a `TStylingContext` data-structure.
  34731. * There is only one `TStylingContext` per `TNode` and each element instance
  34732. * will update its style/class binding values in concert with the styling
  34733. * context.
  34734. *
  34735. * To learn more about the algorithm see `TStylingContext`.
  34736. *
  34737. * --------
  34738. */
  34739. var DEFAULT_BINDING_VALUE = null;
  34740. var DEFAULT_SIZE_VALUE = 1;
  34741. // The first bit value reflects a map-based binding value's bit.
  34742. // The reason why it's always activated for every entry in the map
  34743. // is so that if any map-binding values update then all other prop
  34744. // based bindings will pass the guard check automatically without
  34745. // any extra code or flags.
  34746. var DEFAULT_GUARD_MASK_VALUE = 1;
  34747. var deferredBindingQueue = [];
  34748. /**
  34749. * Flushes the collection of deferred bindings and causes each entry
  34750. * to be registered into the context.
  34751. */
  34752. function flushDeferredBindings() {
  34753. var i = 0;
  34754. while (i < deferredBindingQueue.length) {
  34755. var context = deferredBindingQueue[i++];
  34756. var count = deferredBindingQueue[i++];
  34757. var prop = deferredBindingQueue[i++];
  34758. var bindingIndex = deferredBindingQueue[i++];
  34759. var sanitizationRequired = deferredBindingQueue[i++];
  34760. registerBinding(context, count, prop, bindingIndex, sanitizationRequired);
  34761. }
  34762. deferredBindingQueue.length = 0;
  34763. }
  34764. /**
  34765. * Registers the provided binding (prop + bindingIndex) into the context.
  34766. *
  34767. * This function is shared between bindings that are assigned immediately
  34768. * (via `updateBindingData`) and at a deferred stage. When called, it will
  34769. * figure out exactly where to place the binding data in the context.
  34770. *
  34771. * It is needed because it will either update or insert a styling property
  34772. * into the context at the correct spot.
  34773. *
  34774. * When called, one of two things will happen:
  34775. *
  34776. * 1) If the property already exists in the context then it will just add
  34777. * the provided `bindingValue` to the end of the binding sources region
  34778. * for that particular property.
  34779. *
  34780. * - If the binding value is a number then it will be added as a new
  34781. * binding index source next to the other binding sources for the property.
  34782. *
  34783. * - Otherwise, if the binding value is a string/boolean/null type then it will
  34784. * replace the default value for the property if the default value is `null`.
  34785. *
  34786. * 2) If the property does not exist then it will be inserted into the context.
  34787. * The styling context relies on all properties being stored in alphabetical
  34788. * order, so it knows exactly where to store it.
  34789. *
  34790. * When inserted, a default `null` value is created for the property which exists
  34791. * as the default value for the binding. If the bindingValue property is inserted
  34792. * and it is either a string, number or null value then that will replace the default
  34793. * value.
  34794. *
  34795. * Note that this function is also used for map-based styling bindings. They are treated
  34796. * much the same as prop-based bindings, but, because they do not have a property value
  34797. * (since it's a map), all map-based entries are stored in an already populated area of
  34798. * the context at the top (which is reserved for map-based entries).
  34799. */
  34800. function registerBinding(context, countId, prop, bindingValue, sanitizationRequired) {
  34801. // prop-based bindings (e.g `<div [style.width]="w" [class.foo]="f">`)
  34802. if (prop) {
  34803. var found = false;
  34804. var i = getPropValuesStartPosition(context);
  34805. while (i < context.length) {
  34806. var valuesCount = getValuesCount(context, i);
  34807. var p = getProp$1(context, i);
  34808. found = prop <= p;
  34809. if (found) {
  34810. // all style/class bindings are sorted by property name
  34811. if (prop < p) {
  34812. allocateNewContextEntry(context, i, prop, sanitizationRequired);
  34813. }
  34814. addBindingIntoContext(context, false, i, bindingValue, countId);
  34815. break;
  34816. }
  34817. i += 3 /* BindingsStartOffset */ + valuesCount;
  34818. }
  34819. if (!found) {
  34820. allocateNewContextEntry(context, context.length, prop, sanitizationRequired);
  34821. addBindingIntoContext(context, false, i, bindingValue, countId);
  34822. }
  34823. }
  34824. else {
  34825. // map-based bindings (e.g `<div [style]="s" [class]="{className:true}">`)
  34826. // there is no need to allocate the map-based binding region into the context
  34827. // since it is already there when the context is first created.
  34828. addBindingIntoContext(context, true, 2 /* MapBindingsPosition */, bindingValue, countId);
  34829. }
  34830. }
  34831. function allocateNewContextEntry(context, index, prop, sanitizationRequired) {
  34832. // 1,2: splice index locations
  34833. // 3: each entry gets a config value (guard mask + flags)
  34834. // 4. each entry gets a size value (which is always one because there is always a default binding
  34835. // value)
  34836. // 5. the property that is getting allocated into the context
  34837. // 6. the default binding value (usually `null`)
  34838. var config = sanitizationRequired ? 1 /* SanitizationRequired */ :
  34839. 0 /* Default */;
  34840. context.splice(index, 0, config, DEFAULT_SIZE_VALUE, prop, DEFAULT_BINDING_VALUE);
  34841. setGuardMask(context, index, DEFAULT_GUARD_MASK_VALUE);
  34842. }
  34843. /**
  34844. * Inserts a new binding value into a styling property tuple in the `TStylingContext`.
  34845. *
  34846. * A bindingValue is inserted into a context during the first update pass
  34847. * of a template or host bindings function. When this occurs, two things
  34848. * happen:
  34849. *
  34850. * - If the bindingValue value is a number then it is treated as a bindingIndex
  34851. * value (a index in the `LView`) and it will be inserted next to the other
  34852. * binding index entries.
  34853. *
  34854. * - Otherwise the binding value will update the default value for the property
  34855. * and this will only happen if the default value is `null`.
  34856. *
  34857. * Note that this function also handles map-based bindings and will insert them
  34858. * at the top of the context.
  34859. */
  34860. function addBindingIntoContext(context, isMapBased, index, bindingValue, countId) {
  34861. var valuesCount = getValuesCount(context, index);
  34862. var lastValueIndex = index + 3 /* BindingsStartOffset */ + valuesCount;
  34863. if (!isMapBased) {
  34864. // prop-based values all have default values, but map-based entries do not.
  34865. // we want to access the index for the default value in this case and not just
  34866. // the bindings...
  34867. lastValueIndex--;
  34868. }
  34869. if (typeof bindingValue === 'number') {
  34870. context.splice(lastValueIndex, 0, bindingValue);
  34871. context[index + 1 /* ValuesCountOffset */]++;
  34872. // now that a new binding index has been added to the property
  34873. // the guard mask bit value (at the `countId` position) needs
  34874. // to be included into the existing mask value.
  34875. var guardMask = getGuardMask(context, index) | (1 << countId);
  34876. setGuardMask(context, index, guardMask);
  34877. }
  34878. else if (typeof bindingValue === 'string' && context[lastValueIndex] == null) {
  34879. context[lastValueIndex] = bindingValue;
  34880. }
  34881. }
  34882. /**
  34883. * Runs through the provided styling context and applies each value to
  34884. * the provided element (via the renderer) if one or more values are present.
  34885. *
  34886. * This function will iterate over all entries present in the provided
  34887. * `TStylingContext` array (both prop-based and map-based bindings).-
  34888. *
  34889. * Each entry, within the `TStylingContext` array, is stored alphabetically
  34890. * and this means that each prop/value entry will be applied in order
  34891. * (so long as it is marked dirty in the provided `bitMask` value).
  34892. *
  34893. * If there are any map-based entries present (which are applied to the
  34894. * element via the `[style]` and `[class]` bindings) then those entries
  34895. * will be applied as well. However, the code for that is not apart of
  34896. * this function. Instead, each time a property is visited, then the
  34897. * code below will call an external function called `stylingMapsSyncFn`
  34898. * and, if present, it will keep the application of styling values in
  34899. * map-based bindings up to sync with the application of prop-based
  34900. * bindings.
  34901. *
  34902. * Visit `styling_next/map_based_bindings.ts` to learn more about how the
  34903. * algorithm works for map-based styling bindings.
  34904. *
  34905. * Note that this function is not designed to be called in isolation (use
  34906. * `applyClasses` and `applyStyles` to actually apply styling values).
  34907. */
  34908. function applyStyling(context, renderer, element, bindingData, bitMaskValue, applyStylingFn, sanitizer) {
  34909. deferredBindingQueue.length && flushDeferredBindings();
  34910. var bitMask = normalizeBitMaskValue(bitMaskValue);
  34911. var stylingMapsSyncFn = getStylingMapsSyncFn();
  34912. var mapsGuardMask = getGuardMask(context, 2 /* MapBindingsPosition */);
  34913. var applyAllValues = (bitMask & mapsGuardMask) > 0;
  34914. var mapsMode = applyAllValues ? 1 /* ApplyAllValues */ : 0 /* TraverseValues */;
  34915. var i = getPropValuesStartPosition(context);
  34916. while (i < context.length) {
  34917. var valuesCount = getValuesCount(context, i);
  34918. var guardMask = getGuardMask(context, i);
  34919. if (bitMask & guardMask) {
  34920. var valueApplied = false;
  34921. var prop = getProp$1(context, i);
  34922. var valuesCountUpToDefault = valuesCount - 1;
  34923. var defaultValue = getBindingValue(context, i, valuesCountUpToDefault);
  34924. // case 1: apply prop-based values
  34925. // try to apply the binding values and see if a non-null
  34926. // value gets set for the styling binding
  34927. for (var j = 0; j < valuesCountUpToDefault; j++) {
  34928. var bindingIndex = getBindingValue(context, i, j);
  34929. var value = bindingData[bindingIndex];
  34930. if (isStylingValueDefined(value)) {
  34931. var finalValue = sanitizer && isSanitizationRequired(context, i) ?
  34932. sanitizer(prop, value, 2 /* SanitizeOnly */) :
  34933. value;
  34934. applyStylingFn(renderer, element, prop, finalValue, bindingIndex);
  34935. valueApplied = true;
  34936. break;
  34937. }
  34938. }
  34939. // case 2: apply map-based values
  34940. // traverse through each map-based styling binding and update all values up to
  34941. // the provided `prop` value. If the property was not applied in the loop above
  34942. // then it will be attempted to be applied in the maps sync code below.
  34943. if (stylingMapsSyncFn) {
  34944. // determine whether or not to apply the target property or to skip it
  34945. var mode = mapsMode | (valueApplied ? 4 /* SkipTargetProp */ :
  34946. 2 /* ApplyTargetProp */);
  34947. var valueAppliedWithinMap = stylingMapsSyncFn(context, renderer, element, bindingData, applyStylingFn, sanitizer, mode, prop, defaultValue);
  34948. valueApplied = valueApplied || valueAppliedWithinMap;
  34949. }
  34950. // case 3: apply the default value
  34951. // if the value has not yet been applied then a truthy value does not exist in the
  34952. // prop-based or map-based bindings code. If and when this happens, just apply the
  34953. // default value (even if the default value is `null`).
  34954. if (!valueApplied) {
  34955. applyStylingFn(renderer, element, prop, defaultValue);
  34956. }
  34957. }
  34958. i += 3 /* BindingsStartOffset */ + valuesCount;
  34959. }
  34960. // the map-based styling entries may have not applied all their
  34961. // values. For this reason, one more call to the sync function
  34962. // needs to be issued at the end.
  34963. if (stylingMapsSyncFn) {
  34964. stylingMapsSyncFn(context, renderer, element, bindingData, applyStylingFn, sanitizer, mapsMode);
  34965. }
  34966. }
  34967. function normalizeBitMaskValue(value) {
  34968. // if pass => apply all values (-1 implies that all bits are flipped to true)
  34969. if (value === true)
  34970. return -1;
  34971. // if pass => skip all values
  34972. if (value === false)
  34973. return 0;
  34974. // return the bit mask value as is
  34975. return value;
  34976. }
  34977. var _activeStylingMapApplyFn = null;
  34978. function getStylingMapsSyncFn() {
  34979. return _activeStylingMapApplyFn;
  34980. }
  34981. function setStylingMapsSyncFn(fn) {
  34982. _activeStylingMapApplyFn = fn;
  34983. }
  34984. /**
  34985. * --------
  34986. *
  34987. * This file contains the algorithm logic for applying map-based bindings
  34988. * such as `[style]` and `[class]`.
  34989. *
  34990. * --------
  34991. */
  34992. /**
  34993. * Used to apply styling values presently within any map-based bindings on an element.
  34994. *
  34995. * Angular supports map-based styling bindings which can be applied via the
  34996. * `[style]` and `[class]` bindings which can be placed on any HTML element.
  34997. * These bindings can work independently, together or alongside prop-based
  34998. * styling bindings (e.g. `<div [style]="x" [style.width]="w">`).
  34999. *
  35000. * If a map-based styling binding is detected by the compiler, the following
  35001. * AOT code is produced:
  35002. *
  35003. * ```typescript
  35004. * styleMap(ctx.styles); // styles = {key:value}
  35005. * classMap(ctx.classes); // classes = {key:value}|string
  35006. * ```
  35007. *
  35008. * If and when either of the instructions above are evaluated, then the code
  35009. * present in this file is included into the bundle. The mechanism used, to
  35010. * activate support for map-based bindings at runtime is possible via the
  35011. * `activeStylingMapFeature` function (which is also present in this file).
  35012. *
  35013. * # The Algorithm
  35014. * Whenever a map-based binding updates (which is when the identity of the
  35015. * map-value changes) then the map is iterated over and a `LStylingMap` array
  35016. * is produced. The `LStylingMap` instance is stored in the binding location
  35017. * where the `BINDING_INDEX` is situated when the `styleMap()` or `classMap()`
  35018. * instruction were called. Once the binding changes, then the internal `bitMask`
  35019. * value is marked as dirty.
  35020. *
  35021. * Styling values are applied once CD exits the element (which happens when
  35022. * the `select(n)` instruction is called or the template function exits). When
  35023. * this occurs, all prop-based bindings are applied. If a map-based binding is
  35024. * present then a special flushing function (called a sync function) is made
  35025. * available and it will be called each time a styling property is flushed.
  35026. *
  35027. * The flushing algorithm is designed to apply styling for a property (which is
  35028. * a CSS property or a className value) one by one. If map-based bindings
  35029. * are present, then the flushing algorithm will keep calling the maps styling
  35030. * sync function each time a property is visited. This way, the flushing
  35031. * behavior of map-based bindings will always be at the same property level
  35032. * as the current prop-based property being iterated over (because everything
  35033. * is alphabetically sorted).
  35034. *
  35035. * Let's imagine we have the following HTML template code:
  35036. *
  35037. * ```html
  35038. * <div [style]="{width:'100px', height:'200px', 'z-index':'10'}"
  35039. * [style.width.px]="200">...</div>
  35040. * ```
  35041. *
  35042. * When CD occurs, both the `[style]` and `[style.width]` bindings
  35043. * are evaluated. Then when the styles are flushed on screen, the
  35044. * following operations happen:
  35045. *
  35046. * 1. `[style.width]` is attempted to be written to the element.
  35047. *
  35048. * 2. Once that happens, the algorithm instructs the map-based
  35049. * entries (`[style]` in this case) to "catch up" and apply
  35050. * all values up to the `width` value. When this happens the
  35051. * `height` value is applied to the element (since it is
  35052. * alphabetically situated before the `width` property).
  35053. *
  35054. * 3. Since there are no more prop-based entries anymore, the
  35055. * loop exits and then, just before the flushing ends, it
  35056. * instructs all map-based bindings to "finish up" applying
  35057. * their values.
  35058. *
  35059. * 4. The only remaining value within the map-based entries is
  35060. * the `z-index` value (`width` got skipped because it was
  35061. * successfully applied via the prop-based `[style.width]`
  35062. * binding). Since all map-based entries are told to "finish up",
  35063. * the `z-index` value is iterated over and it is then applied
  35064. * to the element.
  35065. *
  35066. * The most important thing to take note of here is that prop-based
  35067. * bindings are evaluated in order alongside map-based bindings.
  35068. * This allows all styling across an element to be applied in O(n)
  35069. * time (a similar algorithm is that of the array merge algorithm
  35070. * in merge sort).
  35071. */
  35072. var syncStylingMap = function (context, renderer, element, data, applyStylingFn, sanitizer, mode, targetProp, defaultValue) {
  35073. var targetPropValueWasApplied = false;
  35074. // once the map-based styling code is activate it is never deactivated. For this reason a
  35075. // check to see if the current styling context has any map based bindings is required.
  35076. var totalMaps = getValuesCount(context, 2 /* MapBindingsPosition */);
  35077. if (totalMaps) {
  35078. var runTheSyncAlgorithm = true;
  35079. var loopUntilEnd = !targetProp;
  35080. // If the code is told to finish up (run until the end), but the mode
  35081. // hasn't been flagged to apply values (it only traverses values) then
  35082. // there is no point in iterating over the array because nothing will
  35083. // be applied to the element.
  35084. if (loopUntilEnd && (mode & ~1 /* ApplyAllValues */)) {
  35085. runTheSyncAlgorithm = false;
  35086. targetPropValueWasApplied = true;
  35087. }
  35088. if (runTheSyncAlgorithm) {
  35089. targetPropValueWasApplied = innerSyncStylingMap(context, renderer, element, data, applyStylingFn, sanitizer, mode, targetProp || null, 0, defaultValue || null);
  35090. }
  35091. if (loopUntilEnd) {
  35092. resetSyncCursors();
  35093. }
  35094. }
  35095. return targetPropValueWasApplied;
  35096. };
  35097. /**
  35098. * Recursive function designed to apply map-based styling to an element one map at a time.
  35099. *
  35100. * This function is designed to be called from the `syncStylingMap` function and will
  35101. * apply map-based styling data one map at a time to the provided `element`.
  35102. *
  35103. * This function is recursive and it will call itself if a follow-up map value is to be
  35104. * processed. To learn more about how the algorithm works, see `syncStylingMap`.
  35105. */
  35106. function innerSyncStylingMap(context, renderer, element, data, applyStylingFn, sanitizer, mode, targetProp, currentMapIndex, defaultValue) {
  35107. var targetPropValueWasApplied = false;
  35108. var totalMaps = getValuesCount(context, 2 /* MapBindingsPosition */);
  35109. if (currentMapIndex < totalMaps) {
  35110. var bindingIndex = getBindingValue(context, 2 /* MapBindingsPosition */, currentMapIndex);
  35111. var lStylingMap = data[bindingIndex];
  35112. var cursor = getCurrentSyncCursor(currentMapIndex);
  35113. while (cursor < lStylingMap.length) {
  35114. var prop = getMapProp(lStylingMap, cursor);
  35115. var iteratedTooFar = targetProp && prop > targetProp;
  35116. var isTargetPropMatched = !iteratedTooFar && prop === targetProp;
  35117. var value = getMapValue(lStylingMap, cursor);
  35118. var valueIsDefined = isStylingValueDefined(value);
  35119. // the recursive code is designed to keep applying until
  35120. // it reaches or goes past the target prop. If and when
  35121. // this happens then it will stop processing values, but
  35122. // all other map values must also catch up to the same
  35123. // point. This is why a recursive call is still issued
  35124. // even if the code has iterated too far.
  35125. var innerMode = iteratedTooFar ? mode : resolveInnerMapMode(mode, valueIsDefined, isTargetPropMatched);
  35126. var innerProp = iteratedTooFar ? targetProp : prop;
  35127. var valueApplied = innerSyncStylingMap(context, renderer, element, data, applyStylingFn, sanitizer, innerMode, innerProp, currentMapIndex + 1, defaultValue);
  35128. if (iteratedTooFar) {
  35129. break;
  35130. }
  35131. if (!valueApplied && isValueAllowedToBeApplied(mode, isTargetPropMatched)) {
  35132. var useDefault = isTargetPropMatched && !valueIsDefined;
  35133. var valueToApply = useDefault ? defaultValue : value;
  35134. var bindingIndexToApply = useDefault ? bindingIndex : null;
  35135. var finalValue = sanitizer ?
  35136. sanitizer(prop, valueToApply, 3 /* ValidateAndSanitize */) :
  35137. valueToApply;
  35138. applyStylingFn(renderer, element, prop, finalValue, bindingIndexToApply);
  35139. valueApplied = true;
  35140. }
  35141. targetPropValueWasApplied = valueApplied && isTargetPropMatched;
  35142. cursor += 2 /* TupleSize */;
  35143. }
  35144. setCurrentSyncCursor(currentMapIndex, cursor);
  35145. }
  35146. return targetPropValueWasApplied;
  35147. }
  35148. /**
  35149. * Enables support for map-based styling bindings (e.g. `[style]` and `[class]` bindings).
  35150. */
  35151. function activeStylingMapFeature() {
  35152. setStylingMapsSyncFn(syncStylingMap);
  35153. }
  35154. /**
  35155. * Used to determine the mode for the inner recursive call.
  35156. *
  35157. * If an inner map is iterated on then this is done so for one
  35158. * of two reasons:
  35159. *
  35160. * - The target property was detected and the inner map
  35161. * must now "catch up" (pointer-wise) up to where the current
  35162. * map's cursor is situated.
  35163. *
  35164. * - The target property was not detected in the current map
  35165. * and must be found in an inner map. This can only be allowed
  35166. * if the current map iteration is not set to skip the target
  35167. * property.
  35168. */
  35169. function resolveInnerMapMode(currentMode, valueIsDefined, isExactMatch) {
  35170. var innerMode = currentMode;
  35171. if (!valueIsDefined && isExactMatch && !(currentMode & 4 /* SkipTargetProp */)) {
  35172. // case 1: set the mode to apply the targeted prop value if it
  35173. // ends up being encountered in another map value
  35174. innerMode |= 2 /* ApplyTargetProp */;
  35175. innerMode &= ~4 /* SkipTargetProp */;
  35176. }
  35177. else {
  35178. // case 2: set the mode to skip the targeted prop value if it
  35179. // ends up being encountered in another map value
  35180. innerMode |= 4 /* SkipTargetProp */;
  35181. innerMode &= ~2 /* ApplyTargetProp */;
  35182. }
  35183. return innerMode;
  35184. }
  35185. /**
  35186. * Decides whether or not a prop/value entry will be applied to an element.
  35187. *
  35188. * To determine whether or not a value is to be applied,
  35189. * the following procedure is evaluated:
  35190. *
  35191. * First check to see the current `mode` status:
  35192. * 1. If the mode value permits all props to be applied then allow.
  35193. * - But do not allow if the current prop is set to be skipped.
  35194. * 2. Otherwise if the current prop is permitted then allow.
  35195. */
  35196. function isValueAllowedToBeApplied(mode, isTargetPropMatched) {
  35197. var doApplyValue = (mode & 1 /* ApplyAllValues */) > 0;
  35198. if (!doApplyValue) {
  35199. if (mode & 2 /* ApplyTargetProp */) {
  35200. doApplyValue = isTargetPropMatched;
  35201. }
  35202. }
  35203. else if ((mode & 4 /* SkipTargetProp */) && isTargetPropMatched) {
  35204. doApplyValue = false;
  35205. }
  35206. return doApplyValue;
  35207. }
  35208. /**
  35209. * Used to keep track of concurrent cursor values for multiple map-based styling bindings present on
  35210. * an element.
  35211. */
  35212. var MAP_CURSORS = [];
  35213. /**
  35214. * Used to reset the state of each cursor value being used to iterate over map-based styling
  35215. * bindings.
  35216. */
  35217. function resetSyncCursors() {
  35218. for (var i = 0; i < MAP_CURSORS.length; i++) {
  35219. MAP_CURSORS[i] = 1 /* ValuesStartPosition */;
  35220. }
  35221. }
  35222. /**
  35223. * Returns an active cursor value at a given mapIndex location.
  35224. */
  35225. function getCurrentSyncCursor(mapIndex) {
  35226. if (mapIndex >= MAP_CURSORS.length) {
  35227. MAP_CURSORS.push(1 /* ValuesStartPosition */);
  35228. }
  35229. return MAP_CURSORS[mapIndex];
  35230. }
  35231. /**
  35232. * Sets a cursor value at a given mapIndex location.
  35233. */
  35234. function setCurrentSyncCursor(mapIndex, indexValue) {
  35235. MAP_CURSORS[mapIndex] = indexValue;
  35236. }
  35237. function getMapProp(map, index) {
  35238. return map[index + 0 /* PropOffset */];
  35239. }
  35240. function getMapValue(map, index) {
  35241. return map[index + 1 /* ValueOffset */];
  35242. }
  35243. /**
  35244. * A human-readable debug summary of the styling data present within `TStylingContext`.
  35245. *
  35246. * This class is designed to be used within testing code or when an
  35247. * application has `ngDevMode` activated.
  35248. */
  35249. var TStylingContextDebug = /** @class */ (function () {
  35250. function TStylingContextDebug(context) {
  35251. this.context = context;
  35252. }
  35253. Object.defineProperty(TStylingContextDebug.prototype, "isLocked", {
  35254. get: function () { return isContextLocked(this.context); },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(TStylingContextDebug.prototype, "entries", {
  35259. /**
  35260. * Returns a detailed summary of each styling entry in the context.
  35261. *
  35262. * See `TStylingTupleSummary`.
  35263. */
  35264. get: function () {
  35265. var context = this.context;
  35266. var entries = {};
  35267. var start = 2 /* MapBindingsPosition */;
  35268. var i = start;
  35269. while (i < context.length) {
  35270. var valuesCount = getValuesCount(context, i);
  35271. // the context may contain placeholder values which are populated ahead of time,
  35272. // but contain no actual binding values. In this situation there is no point in
  35273. // classifying this as an "entry" since no real data is stored here yet.
  35274. if (valuesCount) {
  35275. var prop = getProp$1(context, i);
  35276. var guardMask = getGuardMask(context, i);
  35277. var defaultValue = getDefaultValue(context, i);
  35278. var sanitizationRequired = isSanitizationRequired(context, i);
  35279. var bindingsStartPosition = i + 3 /* BindingsStartOffset */;
  35280. var sources = [];
  35281. for (var j = 0; j < valuesCount; j++) {
  35282. sources.push(context[bindingsStartPosition + j]);
  35283. }
  35284. entries[prop] = { prop: prop, guardMask: guardMask, sanitizationRequired: sanitizationRequired, valuesCount: valuesCount, defaultValue: defaultValue, sources: sources };
  35285. }
  35286. i += 3 /* BindingsStartOffset */ + valuesCount;
  35287. }
  35288. return entries;
  35289. },
  35290. enumerable: true,
  35291. configurable: true
  35292. });
  35293. return TStylingContextDebug;
  35294. }());
  35295. /**
  35296. * A human-readable debug summary of the styling data present for a `DebugNode` instance.
  35297. *
  35298. * This class is designed to be used within testing code or when an
  35299. * application has `ngDevMode` activated.
  35300. */
  35301. var NodeStylingDebug = /** @class */ (function () {
  35302. function NodeStylingDebug(context, _data, _isClassBased) {
  35303. this.context = context;
  35304. this._data = _data;
  35305. this._isClassBased = _isClassBased;
  35306. this._sanitizer = null;
  35307. }
  35308. /**
  35309. * Overrides the sanitizer used to process styles.
  35310. */
  35311. NodeStylingDebug.prototype.overrideSanitizer = function (sanitizer) { this._sanitizer = sanitizer; };
  35312. Object.defineProperty(NodeStylingDebug.prototype, "summary", {
  35313. /**
  35314. * Returns a detailed summary of each styling entry in the context and
  35315. * what their runtime representation is.
  35316. *
  35317. * See `LStylingSummary`.
  35318. */
  35319. get: function () {
  35320. var entries = {};
  35321. this._mapValues(function (prop, value, bindingIndex) {
  35322. entries[prop] = { prop: prop, value: value, bindingIndex: bindingIndex };
  35323. });
  35324. return entries;
  35325. },
  35326. enumerable: true,
  35327. configurable: true
  35328. });
  35329. Object.defineProperty(NodeStylingDebug.prototype, "values", {
  35330. /**
  35331. * Returns a key/value map of all the styles/classes that were last applied to the element.
  35332. */
  35333. get: function () {
  35334. var entries = {};
  35335. this._mapValues(function (prop, value) { entries[prop] = value; });
  35336. return entries;
  35337. },
  35338. enumerable: true,
  35339. configurable: true
  35340. });
  35341. NodeStylingDebug.prototype._mapValues = function (fn) {
  35342. // there is no need to store/track an element instance. The
  35343. // element is only used when the styling algorithm attempts to
  35344. // style the value (and we mock out the stylingApplyFn anyway).
  35345. var mockElement = {};
  35346. var hasMaps = getValuesCount(this.context, 2 /* MapBindingsPosition */) > 0;
  35347. if (hasMaps) {
  35348. activeStylingMapFeature();
  35349. }
  35350. var mapFn = function (renderer, element, prop, value, bindingIndex) {
  35351. fn(prop, value, bindingIndex || null);
  35352. };
  35353. var sanitizer = this._isClassBased ? null : (this._sanitizer ||
  35354. getCurrentOrLViewSanitizer(this._data));
  35355. applyStyling(this.context, null, mockElement, this._data, true, mapFn, sanitizer);
  35356. };
  35357. return NodeStylingDebug;
  35358. }());
  35359. /**
  35360. * @license
  35361. * Copyright Google Inc. All Rights Reserved.
  35362. *
  35363. * Use of this source code is governed by an MIT-style license that can be
  35364. * found in the LICENSE file at https://angular.io/license
  35365. */
  35366. /*
  35367. * This file contains conditionally attached classes which provide human readable (debug) level
  35368. * information for `LView`, `LContainer` and other internal data structures. These data structures
  35369. * are stored internally as array which makes it very difficult during debugging to reason about the
  35370. * current state of the system.
  35371. *
  35372. * Patching the array with extra property does change the array's hidden class' but it does not
  35373. * change the cost of access, therefore this patching should not have significant if any impact in
  35374. * `ngDevMode` mode. (see: https://jsperf.com/array-vs-monkey-patch-array)
  35375. *
  35376. * So instead of seeing:
  35377. * ```
  35378. * Array(30) [Object, 659, null, …]
  35379. * ```
  35380. *
  35381. * You get to see:
  35382. * ```
  35383. * LViewDebug {
  35384. * views: [...],
  35385. * flags: {attached: true, ...}
  35386. * nodes: [
  35387. * {html: '<div id="123">', ..., nodes: [
  35388. * {html: '<span>', ..., nodes: null}
  35389. * ]}
  35390. * ]
  35391. * }
  35392. * ```
  35393. */
  35394. var LViewArray = ngDevMode && createNamedArrayType('LView');
  35395. var LVIEW_EMPTY; // can't initialize here or it will not be tree shaken, because `LView`
  35396. // constructor could have side-effects.
  35397. /**
  35398. * This function clones a blueprint and creates LView.
  35399. *
  35400. * Simple slice will keep the same type, and we need it to be LView
  35401. */
  35402. function cloneToLView(list) {
  35403. if (LVIEW_EMPTY === undefined)
  35404. LVIEW_EMPTY = new LViewArray();
  35405. return LVIEW_EMPTY.concat(list);
  35406. }
  35407. /**
  35408. * This class is a debug version of Object literal so that we can have constructor name show up in
  35409. * debug tools in ngDevMode.
  35410. */
  35411. var TViewConstructor = /** @class */ (function () {
  35412. function TView(id, //
  35413. blueprint, //
  35414. template, //
  35415. viewQuery, //
  35416. node, //
  35417. data, //
  35418. bindingStartIndex, //
  35419. viewQueryStartIndex, //
  35420. expandoStartIndex, //
  35421. expandoInstructions, //
  35422. firstTemplatePass, //
  35423. staticViewQueries, //
  35424. staticContentQueries, //
  35425. preOrderHooks, //
  35426. preOrderCheckHooks, //
  35427. contentHooks, //
  35428. contentCheckHooks, //
  35429. viewHooks, //
  35430. viewCheckHooks, //
  35431. destroyHooks, //
  35432. cleanup, //
  35433. contentQueries, //
  35434. components, //
  35435. directiveRegistry, //
  35436. pipeRegistry, //
  35437. firstChild, //
  35438. schemas) {
  35439. this.id = id;
  35440. this.blueprint = blueprint;
  35441. this.template = template;
  35442. this.viewQuery = viewQuery;
  35443. this.node = node;
  35444. this.data = data;
  35445. this.bindingStartIndex = bindingStartIndex;
  35446. this.viewQueryStartIndex = viewQueryStartIndex;
  35447. this.expandoStartIndex = expandoStartIndex;
  35448. this.expandoInstructions = expandoInstructions;
  35449. this.firstTemplatePass = firstTemplatePass;
  35450. this.staticViewQueries = staticViewQueries;
  35451. this.staticContentQueries = staticContentQueries;
  35452. this.preOrderHooks = preOrderHooks;
  35453. this.preOrderCheckHooks = preOrderCheckHooks;
  35454. this.contentHooks = contentHooks;
  35455. this.contentCheckHooks = contentCheckHooks;
  35456. this.viewHooks = viewHooks;
  35457. this.viewCheckHooks = viewCheckHooks;
  35458. this.destroyHooks = destroyHooks;
  35459. this.cleanup = cleanup;
  35460. this.contentQueries = contentQueries;
  35461. this.components = components;
  35462. this.directiveRegistry = directiveRegistry;
  35463. this.pipeRegistry = pipeRegistry;
  35464. this.firstChild = firstChild;
  35465. this.schemas = schemas;
  35466. }
  35467. return TView;
  35468. }());
  35469. var TViewData = ngDevMode && createNamedArrayType('TViewData');
  35470. var TVIEWDATA_EMPTY; // can't initialize here or it will not be tree shaken, because `LView`
  35471. // constructor could have side-effects.
  35472. /**
  35473. * This function clones a blueprint and creates TData.
  35474. *
  35475. * Simple slice will keep the same type, and we need it to be TData
  35476. */
  35477. function cloneToTViewData(list) {
  35478. if (TVIEWDATA_EMPTY === undefined)
  35479. TVIEWDATA_EMPTY = new TViewData();
  35480. return TVIEWDATA_EMPTY.concat(list);
  35481. }
  35482. var LViewBlueprint = ngDevMode && createNamedArrayType('LViewBlueprint');
  35483. var MatchesArray = ngDevMode && createNamedArrayType('MatchesArray');
  35484. var TViewComponents = ngDevMode && createNamedArrayType('TViewComponents');
  35485. var TNodeLocalNames = ngDevMode && createNamedArrayType('TNodeLocalNames');
  35486. var TNodeInitialInputs = ngDevMode && createNamedArrayType('TNodeInitialInputs');
  35487. var TNodeInitialData = ngDevMode && createNamedArrayType('TNodeInitialData');
  35488. var LCleanup = ngDevMode && createNamedArrayType('LCleanup');
  35489. var TCleanup = ngDevMode && createNamedArrayType('TCleanup');
  35490. function attachLViewDebug(lView) {
  35491. attachDebugObject(lView, new LViewDebug(lView));
  35492. }
  35493. function toDebug(obj) {
  35494. if (obj) {
  35495. var debug = obj.debug;
  35496. assertDefined(debug, 'Object does not have a debug representation.');
  35497. return debug;
  35498. }
  35499. else {
  35500. return obj;
  35501. }
  35502. }
  35503. /**
  35504. * Use this method to unwrap a native element in `LView` and convert it into HTML for easier
  35505. * reading.
  35506. *
  35507. * @param value possibly wrapped native DOM node.
  35508. * @param includeChildren If `true` then the serialized HTML form will include child elements (same
  35509. * as `outerHTML`). If `false` then the serialized HTML form will only contain the element itself
  35510. * (will not serialize child elements).
  35511. */
  35512. function toHtml(value, includeChildren) {
  35513. if (includeChildren === void 0) { includeChildren = false; }
  35514. var node = unwrapRNode(value);
  35515. if (node) {
  35516. var isTextNode = node.nodeType === Node.TEXT_NODE;
  35517. var outerHTML = (isTextNode ? node.textContent : node.outerHTML) || '';
  35518. if (includeChildren || isTextNode) {
  35519. return outerHTML;
  35520. }
  35521. else {
  35522. var innerHTML = node.innerHTML;
  35523. return outerHTML.split(innerHTML)[0] || null;
  35524. }
  35525. }
  35526. else {
  35527. return null;
  35528. }
  35529. }
  35530. var LViewDebug = /** @class */ (function () {
  35531. function LViewDebug(_raw_lView) {
  35532. this._raw_lView = _raw_lView;
  35533. }
  35534. Object.defineProperty(LViewDebug.prototype, "flags", {
  35535. /**
  35536. * Flags associated with the `LView` unpacked into a more readable state.
  35537. */
  35538. get: function () {
  35539. var flags = this._raw_lView[FLAGS];
  35540. return {
  35541. __raw__flags__: flags,
  35542. initPhaseState: flags & 3 /* InitPhaseStateMask */,
  35543. creationMode: !!(flags & 4 /* CreationMode */),
  35544. firstViewPass: !!(flags & 8 /* FirstLViewPass */),
  35545. checkAlways: !!(flags & 16 /* CheckAlways */),
  35546. dirty: !!(flags & 64 /* Dirty */),
  35547. attached: !!(flags & 128 /* Attached */),
  35548. destroyed: !!(flags & 256 /* Destroyed */),
  35549. isRoot: !!(flags & 512 /* IsRoot */),
  35550. indexWithinInitPhase: flags >> 10 /* IndexWithinInitPhaseShift */,
  35551. };
  35552. },
  35553. enumerable: true,
  35554. configurable: true
  35555. });
  35556. Object.defineProperty(LViewDebug.prototype, "parent", {
  35557. get: function () { return toDebug(this._raw_lView[PARENT]); },
  35558. enumerable: true,
  35559. configurable: true
  35560. });
  35561. Object.defineProperty(LViewDebug.prototype, "host", {
  35562. get: function () { return toHtml(this._raw_lView[HOST], true); },
  35563. enumerable: true,
  35564. configurable: true
  35565. });
  35566. Object.defineProperty(LViewDebug.prototype, "context", {
  35567. get: function () { return this._raw_lView[CONTEXT]; },
  35568. enumerable: true,
  35569. configurable: true
  35570. });
  35571. Object.defineProperty(LViewDebug.prototype, "nodes", {
  35572. /**
  35573. * The tree of nodes associated with the current `LView`. The nodes have been normalized into a
  35574. * tree structure with relevant details pulled out for readability.
  35575. */
  35576. get: function () {
  35577. var lView = this._raw_lView;
  35578. var tNode = lView[TVIEW].firstChild;
  35579. return toDebugNodes(tNode, lView);
  35580. },
  35581. enumerable: true,
  35582. configurable: true
  35583. });
  35584. Object.defineProperty(LViewDebug.prototype, "__other__", {
  35585. /**
  35586. * Additional information which is hidden behind a property. The extra level of indirection is
  35587. * done so that the debug view would not be cluttered with properties which are only rarely
  35588. * relevant to the developer.
  35589. */
  35590. get: function () {
  35591. return {
  35592. tView: this._raw_lView[TVIEW],
  35593. cleanup: this._raw_lView[CLEANUP],
  35594. injector: this._raw_lView[INJECTOR$1],
  35595. rendererFactory: this._raw_lView[RENDERER_FACTORY],
  35596. renderer: this._raw_lView[RENDERER],
  35597. sanitizer: this._raw_lView[SANITIZER],
  35598. childHead: toDebug(this._raw_lView[CHILD_HEAD]),
  35599. next: toDebug(this._raw_lView[NEXT]),
  35600. childTail: toDebug(this._raw_lView[CHILD_TAIL]),
  35601. declarationView: toDebug(this._raw_lView[DECLARATION_VIEW]),
  35602. contentQueries: this._raw_lView[CONTENT_QUERIES],
  35603. queries: this._raw_lView[QUERIES],
  35604. tHost: this._raw_lView[T_HOST],
  35605. bindingIndex: this._raw_lView[BINDING_INDEX],
  35606. };
  35607. },
  35608. enumerable: true,
  35609. configurable: true
  35610. });
  35611. Object.defineProperty(LViewDebug.prototype, "childViews", {
  35612. /**
  35613. * Normalized view of child views (and containers) attached at this location.
  35614. */
  35615. get: function () {
  35616. var childViews = [];
  35617. var child = this.__other__.childHead;
  35618. while (child) {
  35619. childViews.push(child);
  35620. child = child.__other__.next;
  35621. }
  35622. return childViews;
  35623. },
  35624. enumerable: true,
  35625. configurable: true
  35626. });
  35627. return LViewDebug;
  35628. }());
  35629. /**
  35630. * Turns a flat list of nodes into a tree by walking the associated `TNode` tree.
  35631. *
  35632. * @param tNode
  35633. * @param lView
  35634. */
  35635. function toDebugNodes(tNode, lView) {
  35636. if (tNode) {
  35637. var debugNodes = [];
  35638. var tNodeCursor = tNode;
  35639. while (tNodeCursor) {
  35640. var rawValue = lView[tNode.index];
  35641. var native = unwrapRNode(rawValue);
  35642. var componentLViewDebug = isStylingContext(rawValue) ? null : toDebug(readLViewValue(rawValue));
  35643. var styles = null;
  35644. var classes = null;
  35645. if (runtimeIsNewStylingInUse()) {
  35646. styles = tNode.newStyles ? new NodeStylingDebug(tNode.newStyles, lView, false) : null;
  35647. classes = tNode.newClasses ? new NodeStylingDebug(tNode.newClasses, lView, true) : null;
  35648. }
  35649. debugNodes.push({
  35650. html: toHtml(native),
  35651. native: native, styles: styles, classes: classes,
  35652. nodes: toDebugNodes(tNode.child, lView),
  35653. component: componentLViewDebug,
  35654. });
  35655. tNodeCursor = tNodeCursor.next;
  35656. }
  35657. return debugNodes;
  35658. }
  35659. else {
  35660. return null;
  35661. }
  35662. }
  35663. var LContainerDebug = /** @class */ (function () {
  35664. function LContainerDebug(_raw_lContainer) {
  35665. this._raw_lContainer = _raw_lContainer;
  35666. }
  35667. Object.defineProperty(LContainerDebug.prototype, "activeIndex", {
  35668. get: function () { return this._raw_lContainer[ACTIVE_INDEX]; },
  35669. enumerable: true,
  35670. configurable: true
  35671. });
  35672. Object.defineProperty(LContainerDebug.prototype, "views", {
  35673. get: function () {
  35674. return this._raw_lContainer.slice(CONTAINER_HEADER_OFFSET)
  35675. .map(toDebug);
  35676. },
  35677. enumerable: true,
  35678. configurable: true
  35679. });
  35680. Object.defineProperty(LContainerDebug.prototype, "parent", {
  35681. get: function () { return toDebug(this._raw_lContainer[PARENT]); },
  35682. enumerable: true,
  35683. configurable: true
  35684. });
  35685. Object.defineProperty(LContainerDebug.prototype, "queries", {
  35686. get: function () { return this._raw_lContainer[QUERIES]; },
  35687. enumerable: true,
  35688. configurable: true
  35689. });
  35690. Object.defineProperty(LContainerDebug.prototype, "host", {
  35691. get: function () { return this._raw_lContainer[HOST]; },
  35692. enumerable: true,
  35693. configurable: true
  35694. });
  35695. Object.defineProperty(LContainerDebug.prototype, "native", {
  35696. get: function () { return this._raw_lContainer[NATIVE]; },
  35697. enumerable: true,
  35698. configurable: true
  35699. });
  35700. Object.defineProperty(LContainerDebug.prototype, "__other__", {
  35701. get: function () {
  35702. return {
  35703. next: toDebug(this._raw_lContainer[NEXT]),
  35704. };
  35705. },
  35706. enumerable: true,
  35707. configurable: true
  35708. });
  35709. return LContainerDebug;
  35710. }());
  35711. /**
  35712. * Return an `LView` value if found.
  35713. *
  35714. * @param value `LView` if any
  35715. */
  35716. function readLViewValue(value) {
  35717. while (Array.isArray(value)) {
  35718. // This check is not quite right, as it does not take into account `StylingContext`
  35719. // This is why it is in debug, not in util.ts
  35720. if (value.length >= HEADER_OFFSET - 1)
  35721. return value;
  35722. value = value[HOST];
  35723. }
  35724. return null;
  35725. }
  35726. var I18NDebugItem = /** @class */ (function () {
  35727. function I18NDebugItem(__raw_opCode, _lView, nodeIndex, type) {
  35728. this.__raw_opCode = __raw_opCode;
  35729. this._lView = _lView;
  35730. this.nodeIndex = nodeIndex;
  35731. this.type = type;
  35732. }
  35733. Object.defineProperty(I18NDebugItem.prototype, "tNode", {
  35734. get: function () { return getTNode(this.nodeIndex, this._lView); },
  35735. enumerable: true,
  35736. configurable: true
  35737. });
  35738. return I18NDebugItem;
  35739. }());
  35740. var I18nMutateOpCodesDebug = /** @class */ (function () {
  35741. function I18nMutateOpCodesDebug(__raw_opCodes, __lView) {
  35742. this.__raw_opCodes = __raw_opCodes;
  35743. this.__lView = __lView;
  35744. }
  35745. Object.defineProperty(I18nMutateOpCodesDebug.prototype, "operations", {
  35746. /**
  35747. * A list of operation information about how the OpCodes will act on the view.
  35748. */
  35749. get: function () {
  35750. var _a = this, __lView = _a.__lView, __raw_opCodes = _a.__raw_opCodes;
  35751. var results = [];
  35752. for (var i = 0; i < __raw_opCodes.length; i++) {
  35753. var opCode = __raw_opCodes[i];
  35754. var result = void 0;
  35755. if (typeof opCode === 'string') {
  35756. result = {
  35757. __raw_opCode: opCode,
  35758. type: 'Create Text Node',
  35759. nodeIndex: __raw_opCodes[++i],
  35760. text: opCode,
  35761. };
  35762. }
  35763. if (typeof opCode === 'number') {
  35764. switch (opCode & 7 /* MASK_OPCODE */) {
  35765. case 1 /* AppendChild */:
  35766. var destinationNodeIndex = opCode >>> 17 /* SHIFT_PARENT */;
  35767. result = new I18NDebugItem(opCode, __lView, destinationNodeIndex, 'AppendChild');
  35768. break;
  35769. case 0 /* Select */:
  35770. var nodeIndex = opCode >>> 3 /* SHIFT_REF */;
  35771. result = new I18NDebugItem(opCode, __lView, nodeIndex, 'Select');
  35772. break;
  35773. case 5 /* ElementEnd */:
  35774. var elementIndex = opCode >>> 3 /* SHIFT_REF */;
  35775. result = new I18NDebugItem(opCode, __lView, elementIndex, 'ElementEnd');
  35776. break;
  35777. case 4 /* Attr */:
  35778. elementIndex = opCode >>> 3 /* SHIFT_REF */;
  35779. result = new I18NDebugItem(opCode, __lView, elementIndex, 'Attr');
  35780. result['attrName'] = __raw_opCodes[++i];
  35781. result['attrValue'] = __raw_opCodes[++i];
  35782. break;
  35783. }
  35784. }
  35785. if (!result) {
  35786. switch (opCode) {
  35787. case COMMENT_MARKER:
  35788. result = {
  35789. __raw_opCode: opCode,
  35790. type: 'COMMENT_MARKER',
  35791. commentValue: __raw_opCodes[++i],
  35792. nodeIndex: __raw_opCodes[++i],
  35793. };
  35794. break;
  35795. case ELEMENT_MARKER:
  35796. result = {
  35797. __raw_opCode: opCode,
  35798. type: 'ELEMENT_MARKER',
  35799. };
  35800. break;
  35801. }
  35802. }
  35803. if (!result) {
  35804. result = {
  35805. __raw_opCode: opCode,
  35806. type: 'Unknown Op Code',
  35807. code: opCode,
  35808. };
  35809. }
  35810. results.push(result);
  35811. }
  35812. return results;
  35813. },
  35814. enumerable: true,
  35815. configurable: true
  35816. });
  35817. return I18nMutateOpCodesDebug;
  35818. }());
  35819. var I18nUpdateOpCodesDebug = /** @class */ (function () {
  35820. function I18nUpdateOpCodesDebug(__raw_opCodes, icus, __lView) {
  35821. this.__raw_opCodes = __raw_opCodes;
  35822. this.icus = icus;
  35823. this.__lView = __lView;
  35824. }
  35825. Object.defineProperty(I18nUpdateOpCodesDebug.prototype, "operations", {
  35826. /**
  35827. * A list of operation information about how the OpCodes will act on the view.
  35828. */
  35829. get: function () {
  35830. var _a = this, __lView = _a.__lView, __raw_opCodes = _a.__raw_opCodes, icus = _a.icus;
  35831. var results = [];
  35832. for (var i = 0; i < __raw_opCodes.length; i++) {
  35833. // bit code to check if we should apply the next update
  35834. var checkBit = __raw_opCodes[i];
  35835. // Number of opCodes to skip until next set of update codes
  35836. var skipCodes = __raw_opCodes[++i];
  35837. var value = '';
  35838. for (var j = i + 1; j <= (i + skipCodes); j++) {
  35839. var opCode = __raw_opCodes[j];
  35840. if (typeof opCode === 'string') {
  35841. value += opCode;
  35842. }
  35843. else if (typeof opCode == 'number') {
  35844. if (opCode < 0) {
  35845. // It's a binding index whose value is negative
  35846. // We cannot know the value of the binding so we only show the index
  35847. value += "\uFFFD" + (-opCode - 1) + "\uFFFD";
  35848. }
  35849. else {
  35850. var nodeIndex = opCode >>> 2 /* SHIFT_REF */;
  35851. var tIcuIndex = void 0;
  35852. var tIcu = void 0;
  35853. switch (opCode & 3 /* MASK_OPCODE */) {
  35854. case 1 /* Attr */:
  35855. var attrName = __raw_opCodes[++j];
  35856. var sanitizeFn = __raw_opCodes[++j];
  35857. results.push({
  35858. __raw_opCode: opCode,
  35859. checkBit: checkBit,
  35860. type: 'Attr',
  35861. attrValue: value, attrName: attrName, sanitizeFn: sanitizeFn,
  35862. });
  35863. break;
  35864. case 0 /* Text */:
  35865. results.push({
  35866. __raw_opCode: opCode,
  35867. checkBit: checkBit,
  35868. type: 'Text', nodeIndex: nodeIndex,
  35869. text: value,
  35870. });
  35871. break;
  35872. case 2 /* IcuSwitch */:
  35873. tIcuIndex = __raw_opCodes[++j];
  35874. tIcu = icus[tIcuIndex];
  35875. var result = new I18NDebugItem(opCode, __lView, nodeIndex, 'IcuSwitch');
  35876. result['tIcuIndex'] = tIcuIndex;
  35877. result['checkBit'] = checkBit;
  35878. result['mainBinding'] = value;
  35879. result['tIcu'] = tIcu;
  35880. results.push(result);
  35881. break;
  35882. case 3 /* IcuUpdate */:
  35883. tIcuIndex = __raw_opCodes[++j];
  35884. tIcu = icus[tIcuIndex];
  35885. result = new I18NDebugItem(opCode, __lView, nodeIndex, 'IcuUpdate');
  35886. result['tIcuIndex'] = tIcuIndex;
  35887. result['checkBit'] = checkBit;
  35888. result['tIcu'] = tIcu;
  35889. results.push(result);
  35890. break;
  35891. }
  35892. }
  35893. }
  35894. }
  35895. i += skipCodes;
  35896. }
  35897. return results;
  35898. },
  35899. enumerable: true,
  35900. configurable: true
  35901. });
  35902. return I18nUpdateOpCodesDebug;
  35903. }());
  35904. /**
  35905. * @license
  35906. * Copyright Google Inc. All Rights Reserved.
  35907. *
  35908. * Use of this source code is governed by an MIT-style license that can be
  35909. * found in the LICENSE file at https://angular.io/license
  35910. */
  35911. function selectInternal(lView, index) {
  35912. // Flush the initial hooks for elements in the view that have been added up to this point.
  35913. executePreOrderHooks(lView, lView[TVIEW], getCheckNoChangesMode(), index);
  35914. }
  35915. var ɵ0$8 = function () { return Promise.resolve(null); };
  35916. /**
  35917. * A permanent marker promise which signifies that the current CD tree is
  35918. * clean.
  35919. */
  35920. var _CLEAN_PROMISE = (ɵ0$8)();
  35921. /**
  35922. * Refreshes the view, executing the following steps in that order:
  35923. * triggers init hooks, refreshes dynamic embedded views, triggers content hooks, sets host
  35924. * bindings, refreshes child components.
  35925. * Note: view hooks are triggered later when leaving the view.
  35926. */
  35927. function refreshDescendantViews(lView) {
  35928. var tView = lView[TVIEW];
  35929. var creationMode = isCreationMode(lView);
  35930. // This needs to be set before children are processed to support recursive components
  35931. tView.firstTemplatePass = false;
  35932. // Resetting the bindingIndex of the current LView as the next steps may trigger change detection.
  35933. lView[BINDING_INDEX] = tView.bindingStartIndex;
  35934. // If this is a creation pass, we should not call lifecycle hooks or evaluate bindings.
  35935. // This will be done in the update pass.
  35936. if (!creationMode) {
  35937. var checkNoChangesMode = getCheckNoChangesMode();
  35938. executePreOrderHooks(lView, tView, checkNoChangesMode, undefined);
  35939. refreshDynamicEmbeddedViews(lView);
  35940. // Content query results must be refreshed before content hooks are called.
  35941. refreshContentQueries(tView, lView);
  35942. resetPreOrderHookFlags(lView);
  35943. executeHooks(lView, tView.contentHooks, tView.contentCheckHooks, checkNoChangesMode, 1 /* AfterContentInitHooksToBeRun */, undefined);
  35944. setHostBindings(tView, lView);
  35945. }
  35946. // We resolve content queries specifically marked as `static` in creation mode. Dynamic
  35947. // content queries are resolved during change detection (i.e. update mode), after embedded
  35948. // views are refreshed (see block above).
  35949. if (creationMode && tView.staticContentQueries) {
  35950. refreshContentQueries(tView, lView);
  35951. }
  35952. refreshChildComponents(tView.components);
  35953. }
  35954. /** Sets the host bindings for the current view. */
  35955. function setHostBindings(tView, viewData) {
  35956. try {
  35957. if (tView.expandoInstructions) {
  35958. var bindingRootIndex = viewData[BINDING_INDEX] = tView.expandoStartIndex;
  35959. setBindingRoot(bindingRootIndex);
  35960. var currentDirectiveIndex = -1;
  35961. var currentElementIndex = -1;
  35962. for (var i = 0; i < tView.expandoInstructions.length; i++) {
  35963. var instruction = tView.expandoInstructions[i];
  35964. if (typeof instruction === 'number') {
  35965. if (instruction <= 0) {
  35966. // Negative numbers mean that we are starting new EXPANDO block and need to update
  35967. // the current element and directive index.
  35968. currentElementIndex = -instruction;
  35969. // Injector block and providers are taken into account.
  35970. var providerCount = tView.expandoInstructions[++i];
  35971. bindingRootIndex += INJECTOR_BLOOM_PARENT_SIZE + providerCount;
  35972. currentDirectiveIndex = bindingRootIndex;
  35973. }
  35974. else {
  35975. // This is either the injector size (so the binding root can skip over directives
  35976. // and get to the first set of host bindings on this node) or the host var count
  35977. // (to get to the next set of host bindings on this node).
  35978. bindingRootIndex += instruction;
  35979. }
  35980. setBindingRoot(bindingRootIndex);
  35981. }
  35982. else {
  35983. // If it's not a number, it's a host binding function that needs to be executed.
  35984. if (instruction !== null) {
  35985. viewData[BINDING_INDEX] = bindingRootIndex;
  35986. var hostCtx = unwrapRNode(viewData[currentDirectiveIndex]);
  35987. instruction(2 /* Update */, hostCtx, currentElementIndex);
  35988. }
  35989. currentDirectiveIndex++;
  35990. }
  35991. }
  35992. }
  35993. }
  35994. finally {
  35995. }
  35996. }
  35997. /** Refreshes content queries for all directives in the given view. */
  35998. function refreshContentQueries(tView, lView) {
  35999. if (tView.contentQueries != null) {
  36000. for (var i = 0; i < tView.contentQueries.length; i++) {
  36001. var directiveDefIdx = tView.contentQueries[i];
  36002. var directiveDef = tView.data[directiveDefIdx];
  36003. ngDevMode &&
  36004. assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
  36005. directiveDef.contentQueries(2 /* Update */, lView[directiveDefIdx], directiveDefIdx);
  36006. }
  36007. }
  36008. }
  36009. /** Refreshes child components in the current view. */
  36010. function refreshChildComponents(components) {
  36011. if (components != null) {
  36012. for (var i = 0; i < components.length; i++) {
  36013. componentRefresh(components[i]);
  36014. }
  36015. }
  36016. }
  36017. /**
  36018. * Creates a native element from a tag name, using a renderer.
  36019. * @param name the tag name
  36020. * @param overriddenRenderer Optional A renderer to override the default one
  36021. * @returns the element created
  36022. */
  36023. function elementCreate(name, overriddenRenderer) {
  36024. var native;
  36025. var rendererToUse = overriddenRenderer || getLView()[RENDERER];
  36026. var namespace = getNamespace();
  36027. if (isProceduralRenderer(rendererToUse)) {
  36028. native = rendererToUse.createElement(name, namespace);
  36029. }
  36030. else {
  36031. if (namespace === null) {
  36032. native = rendererToUse.createElement(name);
  36033. }
  36034. else {
  36035. native = rendererToUse.createElementNS(namespace, name);
  36036. }
  36037. }
  36038. return native;
  36039. }
  36040. function createLView(parentLView, tView, context, flags, host, tHostNode, rendererFactory, renderer, sanitizer, injector) {
  36041. var lView = ngDevMode ? cloneToLView(tView.blueprint) : tView.blueprint.slice();
  36042. lView[HOST] = host;
  36043. lView[FLAGS] = flags | 4 /* CreationMode */ | 128 /* Attached */ | 8 /* FirstLViewPass */;
  36044. resetPreOrderHookFlags(lView);
  36045. lView[PARENT] = lView[DECLARATION_VIEW] = parentLView;
  36046. lView[CONTEXT] = context;
  36047. lView[RENDERER_FACTORY] = (rendererFactory || parentLView && parentLView[RENDERER_FACTORY]);
  36048. ngDevMode && assertDefined(lView[RENDERER_FACTORY], 'RendererFactory is required');
  36049. lView[RENDERER] = (renderer || parentLView && parentLView[RENDERER]);
  36050. ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
  36051. lView[SANITIZER] = sanitizer || parentLView && parentLView[SANITIZER] || null;
  36052. lView[INJECTOR$1] = injector || parentLView && parentLView[INJECTOR$1] || null;
  36053. lView[T_HOST] = tHostNode;
  36054. ngDevMode && attachLViewDebug(lView);
  36055. return lView;
  36056. }
  36057. function getOrCreateTNode(tView, tHostNode, index, type, name, attrs) {
  36058. // Keep this function short, so that the VM will inline it.
  36059. var adjustedIndex = index + HEADER_OFFSET;
  36060. var tNode = tView.data[adjustedIndex] ||
  36061. createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs, index);
  36062. setPreviousOrParentTNode(tNode, true);
  36063. return tNode;
  36064. }
  36065. function createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs, index) {
  36066. var previousOrParentTNode = getPreviousOrParentTNode();
  36067. var isParent = getIsParent();
  36068. var parent = isParent ? previousOrParentTNode : previousOrParentTNode && previousOrParentTNode.parent;
  36069. // Parents cannot cross component boundaries because components will be used in multiple places,
  36070. // so it's only set if the view is the same.
  36071. var parentInSameView = parent && parent !== tHostNode;
  36072. var tParentNode = parentInSameView ? parent : null;
  36073. var tNode = tView.data[adjustedIndex] =
  36074. createTNode(tParentNode, type, adjustedIndex, name, attrs);
  36075. // The first node is not always the one at index 0, in case of i18n, index 0 can be the
  36076. // instruction `i18nStart` and the first node has the index 1 or more
  36077. if (index === 0 || !tView.firstChild) {
  36078. tView.firstChild = tNode;
  36079. }
  36080. // Now link ourselves into the tree.
  36081. if (previousOrParentTNode) {
  36082. if (isParent && previousOrParentTNode.child == null &&
  36083. (tNode.parent !== null || previousOrParentTNode.type === 2 /* View */)) {
  36084. // We are in the same view, which means we are adding content node to the parent view.
  36085. previousOrParentTNode.child = tNode;
  36086. }
  36087. else if (!isParent) {
  36088. previousOrParentTNode.next = tNode;
  36089. }
  36090. }
  36091. return tNode;
  36092. }
  36093. function assignTViewNodeToLView(tView, tParentNode, index, lView) {
  36094. // View nodes are not stored in data because they can be added / removed at runtime (which
  36095. // would cause indices to change). Their TNodes are instead stored in tView.node.
  36096. var tNode = tView.node;
  36097. if (tNode == null) {
  36098. ngDevMode && tParentNode &&
  36099. assertNodeOfPossibleTypes(tParentNode, 3 /* Element */, 0 /* Container */);
  36100. tView.node = tNode = createTNode(tParentNode, //
  36101. 2 /* View */, index, null, null);
  36102. }
  36103. return lView[T_HOST] = tNode;
  36104. }
  36105. /**
  36106. * Used for rendering embedded views (e.g. dynamically created views)
  36107. *
  36108. * Dynamically created views must store/retrieve their TViews differently from component views
  36109. * because their template functions are nested in the template functions of their hosts, creating
  36110. * closures. If their host template happens to be an embedded template in a loop (e.g. ngFor
  36111. * inside
  36112. * an ngFor), the nesting would mean we'd have multiple instances of the template function, so we
  36113. * can't store TViews in the template function itself (as we do for comps). Instead, we store the
  36114. * TView for dynamically created views on their host TNode, which only has one instance.
  36115. */
  36116. function renderEmbeddedTemplate(viewToRender, tView, context) {
  36117. var _isParent = getIsParent();
  36118. var _previousOrParentTNode = getPreviousOrParentTNode();
  36119. var oldView;
  36120. if (viewToRender[FLAGS] & 512 /* IsRoot */) {
  36121. // This is a root view inside the view tree
  36122. tickRootContext(getRootContext(viewToRender));
  36123. }
  36124. else {
  36125. // Will become true if the `try` block executes with no errors.
  36126. var safeToRunHooks = false;
  36127. try {
  36128. setPreviousOrParentTNode(null, true);
  36129. oldView = enterView(viewToRender, viewToRender[T_HOST]);
  36130. resetPreOrderHookFlags(viewToRender);
  36131. executeTemplate(viewToRender, tView.template, getRenderFlags(viewToRender), context);
  36132. // This must be set to false immediately after the first creation run because in an
  36133. // ngFor loop, all the views will be created together before update mode runs and turns
  36134. // off firstTemplatePass. If we don't set it here, instances will perform directive
  36135. // matching, etc again and again.
  36136. viewToRender[TVIEW].firstTemplatePass = false;
  36137. refreshDescendantViews(viewToRender);
  36138. safeToRunHooks = true;
  36139. }
  36140. finally {
  36141. leaveView(oldView, safeToRunHooks);
  36142. setPreviousOrParentTNode(_previousOrParentTNode, _isParent);
  36143. }
  36144. }
  36145. }
  36146. function renderComponentOrTemplate(hostView, context, templateFn) {
  36147. var rendererFactory = hostView[RENDERER_FACTORY];
  36148. var oldView = enterView(hostView, hostView[T_HOST]);
  36149. var normalExecutionPath = !getCheckNoChangesMode();
  36150. var creationModeIsActive = isCreationMode(hostView);
  36151. // Will become true if the `try` block executes with no errors.
  36152. var safeToRunHooks = false;
  36153. try {
  36154. if (normalExecutionPath && !creationModeIsActive && rendererFactory.begin) {
  36155. rendererFactory.begin();
  36156. }
  36157. if (creationModeIsActive) {
  36158. // creation mode pass
  36159. templateFn && executeTemplate(hostView, templateFn, 1 /* Create */, context);
  36160. refreshDescendantViews(hostView);
  36161. hostView[FLAGS] &= ~4 /* CreationMode */;
  36162. }
  36163. // update mode pass
  36164. resetPreOrderHookFlags(hostView);
  36165. templateFn && executeTemplate(hostView, templateFn, 2 /* Update */, context);
  36166. refreshDescendantViews(hostView);
  36167. safeToRunHooks = true;
  36168. }
  36169. finally {
  36170. if (normalExecutionPath && !creationModeIsActive && rendererFactory.end) {
  36171. rendererFactory.end();
  36172. }
  36173. leaveView(oldView, safeToRunHooks);
  36174. }
  36175. }
  36176. function executeTemplate(lView, templateFn, rf, context) {
  36177. ɵɵnamespaceHTML();
  36178. try {
  36179. if (rf & 2 /* Update */) {
  36180. // When we're updating, have an inherent ɵɵselect(0) so we don't have to generate that
  36181. // instruction for most update blocks
  36182. selectInternal(lView, 0);
  36183. }
  36184. templateFn(rf, context);
  36185. }
  36186. finally {
  36187. }
  36188. }
  36189. /**
  36190. * This function returns the default configuration of rendering flags depending on when the
  36191. * template is in creation mode or update mode. Update block and create block are
  36192. * always run separately.
  36193. */
  36194. function getRenderFlags(view) {
  36195. return isCreationMode(view) ? 1 /* Create */ : 2 /* Update */;
  36196. }
  36197. /**
  36198. * Gets TView from a template function or creates a new TView
  36199. * if it doesn't already exist.
  36200. *
  36201. * @param def ComponentDef
  36202. * @returns TView
  36203. */
  36204. function getOrCreateTView(def) {
  36205. return def.tView || (def.tView = createTView(-1, def.template, def.consts, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas));
  36206. }
  36207. /**
  36208. * Creates a TView instance
  36209. *
  36210. * @param viewIndex The viewBlockId for inline views, or -1 if it's a component/dynamic
  36211. * @param templateFn Template function
  36212. * @param consts The number of nodes, local refs, and pipes in this template
  36213. * @param directives Registry of directives for this view
  36214. * @param pipes Registry of pipes for this view
  36215. * @param viewQuery View queries for this view
  36216. * @param schemas Schemas for this view
  36217. */
  36218. function createTView(viewIndex, templateFn, consts, vars, directives, pipes, viewQuery, schemas) {
  36219. ngDevMode && ngDevMode.tView++;
  36220. var bindingStartIndex = HEADER_OFFSET + consts;
  36221. // This length does not yet contain host bindings from child directives because at this point,
  36222. // we don't know which directives are active on this template. As soon as a directive is matched
  36223. // that has a host binding, we will update the blueprint with that def's hostVars count.
  36224. var initialViewLength = bindingStartIndex + vars;
  36225. var blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
  36226. return blueprint[TVIEW] = ngDevMode ?
  36227. new TViewConstructor(viewIndex, // id: number,
  36228. blueprint, // blueprint: LView,
  36229. templateFn, // template: ComponentTemplate<{}>|null,
  36230. viewQuery, // viewQuery: ViewQueriesFunction<{}>|null,
  36231. null, // node: TViewNode|TElementNode|null,
  36232. cloneToTViewData(blueprint).fill(null, bindingStartIndex), // data: TData,
  36233. bindingStartIndex, // bindingStartIndex: number,
  36234. initialViewLength, // viewQueryStartIndex: number,
  36235. initialViewLength, // expandoStartIndex: number,
  36236. null, // expandoInstructions: ExpandoInstructions|null,
  36237. true, // firstTemplatePass: boolean,
  36238. false, // staticViewQueries: boolean,
  36239. false, // staticContentQueries: boolean,
  36240. null, // preOrderHooks: HookData|null,
  36241. null, // preOrderCheckHooks: HookData|null,
  36242. null, // contentHooks: HookData|null,
  36243. null, // contentCheckHooks: HookData|null,
  36244. null, // viewHooks: HookData|null,
  36245. null, // viewCheckHooks: HookData|null,
  36246. null, // destroyHooks: HookData|null,
  36247. null, // cleanup: any[]|null,
  36248. null, // contentQueries: number[]|null,
  36249. null, // components: number[]|null,
  36250. typeof directives === 'function' ?
  36251. directives() :
  36252. directives, // directiveRegistry: DirectiveDefList|null,
  36253. typeof pipes === 'function' ? pipes() : pipes, // pipeRegistry: PipeDefList|null,
  36254. null, // firstChild: TNode|null,
  36255. schemas) :
  36256. {
  36257. id: viewIndex,
  36258. blueprint: blueprint,
  36259. template: templateFn,
  36260. viewQuery: viewQuery,
  36261. node: null,
  36262. data: blueprint.slice().fill(null, bindingStartIndex),
  36263. bindingStartIndex: bindingStartIndex,
  36264. viewQueryStartIndex: initialViewLength,
  36265. expandoStartIndex: initialViewLength,
  36266. expandoInstructions: null,
  36267. firstTemplatePass: true,
  36268. staticViewQueries: false,
  36269. staticContentQueries: false,
  36270. preOrderHooks: null,
  36271. preOrderCheckHooks: null,
  36272. contentHooks: null,
  36273. contentCheckHooks: null,
  36274. viewHooks: null,
  36275. viewCheckHooks: null,
  36276. destroyHooks: null,
  36277. cleanup: null,
  36278. contentQueries: null,
  36279. components: null,
  36280. directiveRegistry: typeof directives === 'function' ? directives() : directives,
  36281. pipeRegistry: typeof pipes === 'function' ? pipes() : pipes,
  36282. firstChild: null,
  36283. schemas: schemas,
  36284. };
  36285. }
  36286. function createViewBlueprint(bindingStartIndex, initialViewLength) {
  36287. var blueprint = new (ngDevMode ? LViewBlueprint : Array)(initialViewLength)
  36288. .fill(null, 0, bindingStartIndex)
  36289. .fill(NO_CHANGE, bindingStartIndex);
  36290. blueprint[BINDING_INDEX] = bindingStartIndex;
  36291. return blueprint;
  36292. }
  36293. function createError(text, token) {
  36294. return new Error("Renderer: " + text + " [" + stringifyForError(token) + "]");
  36295. }
  36296. /**
  36297. * Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
  36298. *
  36299. * @param elementOrSelector Render element or CSS selector to locate the element.
  36300. */
  36301. function locateHostElement(factory, elementOrSelector) {
  36302. var defaultRenderer = factory.createRenderer(null, null);
  36303. var rNode = typeof elementOrSelector === 'string' ?
  36304. (isProceduralRenderer(defaultRenderer) ?
  36305. defaultRenderer.selectRootElement(elementOrSelector) :
  36306. defaultRenderer.querySelector(elementOrSelector)) :
  36307. elementOrSelector;
  36308. if (ngDevMode && !rNode) {
  36309. if (typeof elementOrSelector === 'string') {
  36310. throw createError('Host node with selector not found:', elementOrSelector);
  36311. }
  36312. else {
  36313. throw createError('Host node is required:', elementOrSelector);
  36314. }
  36315. }
  36316. return rNode;
  36317. }
  36318. /**
  36319. * Saves the cleanup function itself in LView.cleanupInstances.
  36320. *
  36321. * This is necessary for functions that are wrapped with their contexts, like in renderer2
  36322. * listeners.
  36323. *
  36324. * On the first template pass, the index of the cleanup function is saved in TView.
  36325. */
  36326. function storeCleanupFn(view, cleanupFn) {
  36327. getCleanup(view).push(cleanupFn);
  36328. if (view[TVIEW].firstTemplatePass) {
  36329. getTViewCleanup(view).push(view[CLEANUP].length - 1, null);
  36330. }
  36331. }
  36332. /**
  36333. * Constructs a TNode object from the arguments.
  36334. *
  36335. * @param type The type of the node
  36336. * @param adjustedIndex The index of the TNode in TView.data, adjusted for HEADER_OFFSET
  36337. * @param tagName The tag name of the node
  36338. * @param attrs The attributes defined on this node
  36339. * @param tViews Any TViews attached to this node
  36340. * @returns the TNode object
  36341. */
  36342. function createTNode(tParent, type, adjustedIndex, tagName, attrs) {
  36343. ngDevMode && ngDevMode.tNode++;
  36344. return {
  36345. type: type,
  36346. index: adjustedIndex,
  36347. injectorIndex: tParent ? tParent.injectorIndex : -1,
  36348. directiveStart: -1,
  36349. directiveEnd: -1,
  36350. propertyMetadataStartIndex: -1,
  36351. propertyMetadataEndIndex: -1,
  36352. flags: 0,
  36353. providerIndexes: 0,
  36354. tagName: tagName,
  36355. attrs: attrs,
  36356. localNames: null,
  36357. initialInputs: undefined,
  36358. inputs: undefined,
  36359. outputs: undefined,
  36360. tViews: null,
  36361. next: null,
  36362. projectionNext: null,
  36363. child: null,
  36364. parent: tParent,
  36365. stylingTemplate: null,
  36366. projection: null,
  36367. onElementCreationFns: null,
  36368. // TODO (matsko): rename this to `styles` once the old styling impl is gone
  36369. newStyles: null,
  36370. // TODO (matsko): rename this to `classes` once the old styling impl is gone
  36371. newClasses: null,
  36372. };
  36373. }
  36374. /**
  36375. * Instantiate a root component.
  36376. */
  36377. function instantiateRootComponent(tView, viewData, def) {
  36378. var rootTNode = getPreviousOrParentTNode();
  36379. if (tView.firstTemplatePass) {
  36380. if (def.providersResolver)
  36381. def.providersResolver(def);
  36382. generateExpandoInstructionBlock(tView, rootTNode, 1);
  36383. baseResolveDirective(tView, viewData, def, def.factory);
  36384. }
  36385. var directive = getNodeInjectable(tView.data, viewData, viewData.length - 1, rootTNode);
  36386. postProcessBaseDirective(viewData, rootTNode, directive);
  36387. return directive;
  36388. }
  36389. function invokeHostBindingsInCreationMode(def, expando, directive, tNode, firstTemplatePass) {
  36390. var previousExpandoLength = expando.length;
  36391. var elementIndex = tNode.index - HEADER_OFFSET;
  36392. def.hostBindings(1 /* Create */, directive, elementIndex);
  36393. // `hostBindings` function may or may not contain `allocHostVars` call
  36394. // (e.g. it may not if it only contains host listeners), so we need to check whether
  36395. // `expandoInstructions` has changed and if not - we still push `hostBindings` to
  36396. // expando block, to make sure we execute it for DI cycle
  36397. if (previousExpandoLength === expando.length && firstTemplatePass) {
  36398. expando.push(def.hostBindings);
  36399. }
  36400. }
  36401. /**
  36402. * Generates a new block in TView.expandoInstructions for this node.
  36403. *
  36404. * Each expando block starts with the element index (turned negative so we can distinguish
  36405. * it from the hostVar count) and the directive count. See more in VIEW_DATA.md.
  36406. */
  36407. function generateExpandoInstructionBlock(tView, tNode, directiveCount) {
  36408. ngDevMode && assertEqual(tView.firstTemplatePass, true, 'Expando block should only be generated on first template pass.');
  36409. var elementIndex = -(tNode.index - HEADER_OFFSET);
  36410. var providerStartIndex = tNode.providerIndexes & 65535 /* ProvidersStartIndexMask */;
  36411. var providerCount = tView.data.length - providerStartIndex;
  36412. (tView.expandoInstructions || (tView.expandoInstructions = [])).push(elementIndex, providerCount, directiveCount);
  36413. }
  36414. /**
  36415. * A lighter version of postProcessDirective() that is used for the root component.
  36416. */
  36417. function postProcessBaseDirective(lView, previousOrParentTNode, directive) {
  36418. var native = getNativeByTNode(previousOrParentTNode, lView);
  36419. ngDevMode && assertEqual(lView[BINDING_INDEX], lView[TVIEW].bindingStartIndex, 'directives should be created before any bindings');
  36420. ngDevMode && assertPreviousIsParent(getIsParent());
  36421. attachPatchData(directive, lView);
  36422. if (native) {
  36423. attachPatchData(native, lView);
  36424. }
  36425. }
  36426. /** Stores index of component's host element so it will be queued for view refresh during CD. */
  36427. function queueComponentIndexForCheck(previousOrParentTNode) {
  36428. var tView = getLView()[TVIEW];
  36429. ngDevMode &&
  36430. assertEqual(tView.firstTemplatePass, true, 'Should only be called in first template pass.');
  36431. (tView.components || (tView.components = ngDevMode ? new TViewComponents() : [])).push(previousOrParentTNode.index);
  36432. }
  36433. /**
  36434. * Initializes the flags on the current node, setting all indices to the initial index,
  36435. * the directive count to 0, and adding the isComponent flag.
  36436. * @param index the initial index
  36437. */
  36438. function initNodeFlags(tNode, index, numberOfDirectives) {
  36439. var flags = tNode.flags;
  36440. ngDevMode && assertEqual(flags === 0 || flags === 1 /* isComponent */, true, 'expected node flags to not be initialized');
  36441. ngDevMode && assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
  36442. // When the first directive is created on a node, save the index
  36443. tNode.flags = flags & 1 /* isComponent */;
  36444. tNode.directiveStart = index;
  36445. tNode.directiveEnd = index + numberOfDirectives;
  36446. tNode.providerIndexes = index;
  36447. }
  36448. function baseResolveDirective(tView, viewData, def, directiveFactory) {
  36449. tView.data.push(def);
  36450. var nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), null);
  36451. tView.blueprint.push(nodeInjectorFactory);
  36452. viewData.push(nodeInjectorFactory);
  36453. }
  36454. //////////////////////////
  36455. //// ViewContainer & View
  36456. //////////////////////////
  36457. // Not sure why I need to do `any` here but TS complains later.
  36458. var LContainerArray = ngDevMode && createNamedArrayType('LContainer');
  36459. /**
  36460. * Goes over dynamic embedded views (ones created through ViewContainerRef APIs) and refreshes
  36461. * them
  36462. * by executing an associated template function.
  36463. */
  36464. function refreshDynamicEmbeddedViews(lView) {
  36465. for (var current = lView[CHILD_HEAD]; current !== null; current = current[NEXT]) {
  36466. // Note: current can be an LView or an LContainer instance, but here we are only interested
  36467. // in LContainer. We can tell it's an LContainer because its length is less than the LView
  36468. // header.
  36469. if (current[ACTIVE_INDEX] === -1 && isLContainer(current)) {
  36470. for (var i = CONTAINER_HEADER_OFFSET; i < current.length; i++) {
  36471. var dynamicViewData = current[i];
  36472. // The directives and pipes are not needed here as an existing view is only being
  36473. // refreshed.
  36474. ngDevMode && assertDefined(dynamicViewData[TVIEW], 'TView must be allocated');
  36475. renderEmbeddedTemplate(dynamicViewData, dynamicViewData[TVIEW], dynamicViewData[CONTEXT]);
  36476. }
  36477. }
  36478. }
  36479. }
  36480. /////////////
  36481. /**
  36482. * Refreshes components by entering the component view and processing its bindings, queries, etc.
  36483. *
  36484. * @param adjustedElementIndex Element index in LView[] (adjusted for HEADER_OFFSET)
  36485. */
  36486. function componentRefresh(adjustedElementIndex) {
  36487. var lView = getLView();
  36488. ngDevMode && assertDataInRange(lView, adjustedElementIndex);
  36489. var hostView = getComponentViewByIndex(adjustedElementIndex, lView);
  36490. ngDevMode && assertNodeType(lView[TVIEW].data[adjustedElementIndex], 3 /* Element */);
  36491. // Only components in creation mode, attached CheckAlways
  36492. // components or attached, dirty OnPush components should be checked
  36493. if ((viewAttachedToChangeDetector(hostView) || isCreationMode(lView)) &&
  36494. hostView[FLAGS] & (16 /* CheckAlways */ | 64 /* Dirty */)) {
  36495. syncViewWithBlueprint(hostView);
  36496. checkView(hostView, hostView[CONTEXT]);
  36497. }
  36498. }
  36499. /**
  36500. * Syncs an LView instance with its blueprint if they have gotten out of sync.
  36501. *
  36502. * Typically, blueprints and their view instances should always be in sync, so the loop here
  36503. * will be skipped. However, consider this case of two components side-by-side:
  36504. *
  36505. * App template:
  36506. * ```
  36507. * <comp></comp>
  36508. * <comp></comp>
  36509. * ```
  36510. *
  36511. * The following will happen:
  36512. * 1. App template begins processing.
  36513. * 2. First <comp> is matched as a component and its LView is created.
  36514. * 3. Second <comp> is matched as a component and its LView is created.
  36515. * 4. App template completes processing, so it's time to check child templates.
  36516. * 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
  36517. * 6. Second <comp> template is checked. Its blueprint has been updated by the first
  36518. * <comp> template, but its LView was created before this update, so it is out of sync.
  36519. *
  36520. * Note that embedded views inside ngFor loops will never be out of sync because these views
  36521. * are processed as soon as they are created.
  36522. *
  36523. * @param componentView The view to sync
  36524. */
  36525. function syncViewWithBlueprint(componentView) {
  36526. var componentTView = componentView[TVIEW];
  36527. for (var i = componentView.length; i < componentTView.blueprint.length; i++) {
  36528. componentView[i] = componentTView.blueprint[i];
  36529. }
  36530. }
  36531. /**
  36532. * Adds LView or LContainer to the end of the current view tree.
  36533. *
  36534. * This structure will be used to traverse through nested views to remove listeners
  36535. * and call onDestroy callbacks.
  36536. *
  36537. * @param lView The view where LView or LContainer should be added
  36538. * @param adjustedHostIndex Index of the view's host node in LView[], adjusted for header
  36539. * @param lViewOrLContainer The LView or LContainer to add to the view tree
  36540. * @returns The state passed in
  36541. */
  36542. function addToViewTree(lView, lViewOrLContainer) {
  36543. // TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer
  36544. // to
  36545. // the end of the queue, which means if the developer retrieves the LContainers from RNodes out
  36546. // of
  36547. // order, the change detection will run out of order, as the act of retrieving the the
  36548. // LContainer
  36549. // from the RNode is what adds it to the queue.
  36550. if (lView[CHILD_HEAD]) {
  36551. lView[CHILD_TAIL][NEXT] = lViewOrLContainer;
  36552. }
  36553. else {
  36554. lView[CHILD_HEAD] = lViewOrLContainer;
  36555. }
  36556. lView[CHILD_TAIL] = lViewOrLContainer;
  36557. return lViewOrLContainer;
  36558. }
  36559. ///////////////////////////////
  36560. //// Change detection
  36561. ///////////////////////////////
  36562. /**
  36563. * Marks current view and all ancestors dirty.
  36564. *
  36565. * Returns the root view because it is found as a byproduct of marking the view tree
  36566. * dirty, and can be used by methods that consume markViewDirty() to easily schedule
  36567. * change detection. Otherwise, such methods would need to traverse up the view tree
  36568. * an additional time to get the root view and schedule a tick on it.
  36569. *
  36570. * @param lView The starting LView to mark dirty
  36571. * @returns the root LView
  36572. */
  36573. function markViewDirty(lView) {
  36574. while (lView) {
  36575. lView[FLAGS] |= 64 /* Dirty */;
  36576. var parent_1 = getLViewParent(lView);
  36577. // Stop traversing up as soon as you find a root view that wasn't attached to any container
  36578. if (isRootView(lView) && !parent_1) {
  36579. return lView;
  36580. }
  36581. // continue otherwise
  36582. lView = parent_1;
  36583. }
  36584. return null;
  36585. }
  36586. function tickRootContext(rootContext) {
  36587. for (var i = 0; i < rootContext.components.length; i++) {
  36588. var rootComponent = rootContext.components[i];
  36589. renderComponentOrTemplate(readPatchedLView(rootComponent), rootComponent);
  36590. }
  36591. }
  36592. function detectChangesInternal(view, context) {
  36593. var rendererFactory = view[RENDERER_FACTORY];
  36594. if (rendererFactory.begin)
  36595. rendererFactory.begin();
  36596. try {
  36597. if (isCreationMode(view)) {
  36598. checkView(view, context); // creation mode pass
  36599. }
  36600. checkView(view, context); // update mode pass
  36601. }
  36602. catch (error) {
  36603. handleError(view, error);
  36604. throw error;
  36605. }
  36606. finally {
  36607. if (rendererFactory.end)
  36608. rendererFactory.end();
  36609. }
  36610. }
  36611. /**
  36612. * Synchronously perform change detection on a root view and its components.
  36613. *
  36614. * @param lView The view which the change detection should be performed on.
  36615. */
  36616. function detectChangesInRootView(lView) {
  36617. tickRootContext(lView[CONTEXT]);
  36618. }
  36619. function checkNoChangesInternal(view, context) {
  36620. setCheckNoChangesMode(true);
  36621. try {
  36622. detectChangesInternal(view, context);
  36623. }
  36624. finally {
  36625. setCheckNoChangesMode(false);
  36626. }
  36627. }
  36628. /**
  36629. * Checks the change detector on a root view and its components, and throws if any changes are
  36630. * detected.
  36631. *
  36632. * This is used in development mode to verify that running change detection doesn't
  36633. * introduce other changes.
  36634. *
  36635. * @param lView The view which the change detection should be checked on.
  36636. */
  36637. function checkNoChangesInRootView(lView) {
  36638. setCheckNoChangesMode(true);
  36639. try {
  36640. detectChangesInRootView(lView);
  36641. }
  36642. finally {
  36643. setCheckNoChangesMode(false);
  36644. }
  36645. }
  36646. /** Checks the view of the component provided. Does not gate on dirty checks or execute doCheck.
  36647. */
  36648. function checkView(hostView, component) {
  36649. var hostTView = hostView[TVIEW];
  36650. var oldView = enterView(hostView, hostView[T_HOST]);
  36651. var templateFn = hostTView.template;
  36652. var creationMode = isCreationMode(hostView);
  36653. // Will become true if the `try` block executes with no errors.
  36654. var safeToRunHooks = false;
  36655. try {
  36656. resetPreOrderHookFlags(hostView);
  36657. creationMode && executeViewQueryFn(1 /* Create */, hostTView, component);
  36658. executeTemplate(hostView, templateFn, getRenderFlags(hostView), component);
  36659. refreshDescendantViews(hostView);
  36660. // Only check view queries again in creation mode if there are static view queries
  36661. if (!creationMode || hostTView.staticViewQueries) {
  36662. executeViewQueryFn(2 /* Update */, hostTView, component);
  36663. }
  36664. safeToRunHooks = true;
  36665. }
  36666. finally {
  36667. leaveView(oldView, safeToRunHooks);
  36668. }
  36669. }
  36670. function executeViewQueryFn(flags, tView, component) {
  36671. var viewQuery = tView.viewQuery;
  36672. if (viewQuery) {
  36673. setCurrentQueryIndex(tView.viewQueryStartIndex);
  36674. viewQuery(flags, component);
  36675. }
  36676. }
  36677. var CLEAN_PROMISE = _CLEAN_PROMISE;
  36678. function getCleanup(view) {
  36679. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  36680. return view[CLEANUP] || (view[CLEANUP] = ngDevMode ? new LCleanup() : []);
  36681. }
  36682. function getTViewCleanup(view) {
  36683. return view[TVIEW].cleanup || (view[TVIEW].cleanup = ngDevMode ? new TCleanup() : []);
  36684. }
  36685. /** Handles an error thrown in an LView. */
  36686. function handleError(lView, error) {
  36687. var injector = lView[INJECTOR$1];
  36688. var errorHandler = injector ? injector.get(ErrorHandler, null) : null;
  36689. errorHandler && errorHandler.handleError(error);
  36690. }
  36691. /**
  36692. * @license
  36693. * Copyright Google Inc. All Rights Reserved.
  36694. *
  36695. * Use of this source code is governed by an MIT-style license that can be
  36696. * found in the LICENSE file at https://angular.io/license
  36697. */
  36698. function applyOnCreateInstructions(tNode) {
  36699. // there may be some instructions that need to run in a specific
  36700. // order because the CREATE block in a directive runs before the
  36701. // CREATE block in a template. To work around this instructions
  36702. // can get access to the function array below and defer any code
  36703. // to run after the element is created.
  36704. var fns;
  36705. if (fns = tNode.onElementCreationFns) {
  36706. for (var i = 0; i < fns.length; i++) {
  36707. fns[i]();
  36708. }
  36709. tNode.onElementCreationFns = null;
  36710. }
  36711. }
  36712. /**
  36713. * @license
  36714. * Copyright Google Inc. All Rights Reserved.
  36715. *
  36716. * Use of this source code is governed by an MIT-style license that can be
  36717. * found in the LICENSE file at https://angular.io/license
  36718. */
  36719. /**
  36720. * @license
  36721. * Copyright Google Inc. All Rights Reserved.
  36722. *
  36723. * Use of this source code is governed by an MIT-style license that can be
  36724. * found in the LICENSE file at https://angular.io/license
  36725. */
  36726. var _symbolIterator = null;
  36727. function getSymbolIterator() {
  36728. if (!_symbolIterator) {
  36729. var Symbol_1 = _global$1['Symbol'];
  36730. if (Symbol_1 && Symbol_1.iterator) {
  36731. _symbolIterator = Symbol_1.iterator;
  36732. }
  36733. else {
  36734. // es6-shim specific logic
  36735. var keys = Object.getOwnPropertyNames(Map.prototype);
  36736. for (var i = 0; i < keys.length; ++i) {
  36737. var key = keys[i];
  36738. if (key !== 'entries' && key !== 'size' &&
  36739. Map.prototype[key] === Map.prototype['entries']) {
  36740. _symbolIterator = key;
  36741. }
  36742. }
  36743. }
  36744. }
  36745. return _symbolIterator;
  36746. }
  36747. /**
  36748. * @license
  36749. * Copyright Google Inc. All Rights Reserved.
  36750. *
  36751. * Use of this source code is governed by an MIT-style license that can be
  36752. * found in the LICENSE file at https://angular.io/license
  36753. */
  36754. /**
  36755. * @license
  36756. * Copyright Google Inc. All Rights Reserved.
  36757. *
  36758. * Use of this source code is governed by an MIT-style license that can be
  36759. * found in the LICENSE file at https://angular.io/license
  36760. */
  36761. // JS has NaN !== NaN
  36762. function looseIdentical(a, b) {
  36763. return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
  36764. }
  36765. /**
  36766. * @license
  36767. * Copyright Google Inc. All Rights Reserved.
  36768. *
  36769. * Use of this source code is governed by an MIT-style license that can be
  36770. * found in the LICENSE file at https://angular.io/license
  36771. */
  36772. function devModeEqual(a, b) {
  36773. var isListLikeIterableA = isListLikeIterable(a);
  36774. var isListLikeIterableB = isListLikeIterable(b);
  36775. if (isListLikeIterableA && isListLikeIterableB) {
  36776. return areIterablesEqual(a, b, devModeEqual);
  36777. }
  36778. else {
  36779. var isAObject = a && (typeof a === 'object' || typeof a === 'function');
  36780. var isBObject = b && (typeof b === 'object' || typeof b === 'function');
  36781. if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
  36782. return true;
  36783. }
  36784. else {
  36785. return looseIdentical(a, b);
  36786. }
  36787. }
  36788. }
  36789. /**
  36790. * Indicates that the result of a {@link Pipe} transformation has changed even though the
  36791. * reference has not changed.
  36792. *
  36793. * Wrapped values are unwrapped automatically during the change detection, and the unwrapped value
  36794. * is stored.
  36795. *
  36796. * Example:
  36797. *
  36798. * ```
  36799. * if (this._latestValue === this._latestReturnedValue) {
  36800. * return this._latestReturnedValue;
  36801. * } else {
  36802. * this._latestReturnedValue = this._latestValue;
  36803. * return WrappedValue.wrap(this._latestValue); // this will force update
  36804. * }
  36805. * ```
  36806. *
  36807. * @publicApi
  36808. */
  36809. var WrappedValue = /** @class */ (function () {
  36810. function WrappedValue(value) {
  36811. this.wrapped = value;
  36812. }
  36813. /** Creates a wrapped value. */
  36814. WrappedValue.wrap = function (value) { return new WrappedValue(value); };
  36815. /**
  36816. * Returns the underlying value of a wrapped value.
  36817. * Returns the given `value` when it is not wrapped.
  36818. **/
  36819. WrappedValue.unwrap = function (value) { return WrappedValue.isWrapped(value) ? value.wrapped : value; };
  36820. /** Returns true if `value` is a wrapped value. */
  36821. WrappedValue.isWrapped = function (value) { return value instanceof WrappedValue; };
  36822. return WrappedValue;
  36823. }());
  36824. function isListLikeIterable(obj) {
  36825. if (!isJsObject(obj))
  36826. return false;
  36827. return Array.isArray(obj) ||
  36828. (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
  36829. getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
  36830. }
  36831. function areIterablesEqual(a, b, comparator) {
  36832. var iterator1 = a[getSymbolIterator()]();
  36833. var iterator2 = b[getSymbolIterator()]();
  36834. while (true) {
  36835. var item1 = iterator1.next();
  36836. var item2 = iterator2.next();
  36837. if (item1.done && item2.done)
  36838. return true;
  36839. if (item1.done || item2.done)
  36840. return false;
  36841. if (!comparator(item1.value, item2.value))
  36842. return false;
  36843. }
  36844. }
  36845. function iterateListLike(obj, fn) {
  36846. if (Array.isArray(obj)) {
  36847. for (var i = 0; i < obj.length; i++) {
  36848. fn(obj[i]);
  36849. }
  36850. }
  36851. else {
  36852. var iterator = obj[getSymbolIterator()]();
  36853. var item = void 0;
  36854. while (!((item = iterator.next()).done)) {
  36855. fn(item.value);
  36856. }
  36857. }
  36858. }
  36859. function isJsObject(o) {
  36860. return o !== null && (typeof o === 'function' || typeof o === 'object');
  36861. }
  36862. /**
  36863. * @license
  36864. * Copyright Google Inc. All Rights Reserved.
  36865. *
  36866. * Use of this source code is governed by an MIT-style license that can be
  36867. * found in the LICENSE file at https://angular.io/license
  36868. */
  36869. /**
  36870. * @license
  36871. * Copyright Google Inc. All Rights Reserved.
  36872. *
  36873. * Use of this source code is governed by an MIT-style license that can be
  36874. * found in the LICENSE file at https://angular.io/license
  36875. */
  36876. /**
  36877. * @license
  36878. * Copyright Google Inc. All Rights Reserved.
  36879. *
  36880. * Use of this source code is governed by an MIT-style license that can be
  36881. * found in the LICENSE file at https://angular.io/license
  36882. */
  36883. /**
  36884. * @license
  36885. * Copyright Google Inc. All Rights Reserved.
  36886. *
  36887. * Use of this source code is governed by an MIT-style license that can be
  36888. * found in the LICENSE file at https://angular.io/license
  36889. */
  36890. /**
  36891. * @license
  36892. * Copyright Google Inc. All Rights Reserved.
  36893. *
  36894. * Use of this source code is governed by an MIT-style license that can be
  36895. * found in the LICENSE file at https://angular.io/license
  36896. */
  36897. function getLContainer(tNode, embeddedView) {
  36898. ngDevMode && assertLView(embeddedView);
  36899. var container = embeddedView[PARENT];
  36900. if (tNode.index === -1) {
  36901. // This is a dynamically created view inside a dynamic container.
  36902. // The parent isn't an LContainer if the embedded view hasn't been attached yet.
  36903. return isLContainer(container) ? container : null;
  36904. }
  36905. else {
  36906. ngDevMode && assertLContainer(container);
  36907. // This is a inline view node (e.g. embeddedViewStart)
  36908. return container;
  36909. }
  36910. }
  36911. /**
  36912. * NOTE: for performance reasons, the possible actions are inlined within the function instead of
  36913. * being passed as an argument.
  36914. */
  36915. function executeActionOnElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
  36916. ngDevMode && assertDefined(lNodeToHandle, '\'lNodeToHandle\' is undefined');
  36917. var lContainer;
  36918. var isComponent = false;
  36919. // We are expecting an RNode, but in the case of a component or LContainer the `RNode` is wrapped
  36920. // in an array which needs to be unwrapped. We need to know if it is a component and if
  36921. // it has LContainer so that we can process all of those cases appropriately.
  36922. if (isLContainer(lNodeToHandle)) {
  36923. lContainer = lNodeToHandle;
  36924. }
  36925. else if (isLView(lNodeToHandle)) {
  36926. isComponent = true;
  36927. ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
  36928. lNodeToHandle = lNodeToHandle[HOST];
  36929. }
  36930. var rNode = unwrapRNode(lNodeToHandle);
  36931. ngDevMode && assertDomNode(rNode);
  36932. if (action === 0 /* Insert */) {
  36933. nativeInsertBefore(renderer, parent, rNode, beforeNode || null);
  36934. }
  36935. else if (action === 1 /* Detach */) {
  36936. nativeRemoveNode(renderer, rNode, isComponent);
  36937. }
  36938. else if (action === 2 /* Destroy */) {
  36939. ngDevMode && ngDevMode.rendererDestroyNode++;
  36940. renderer.destroyNode(rNode);
  36941. }
  36942. if (lContainer != null) {
  36943. executeActionOnContainer(renderer, action, lContainer, parent, beforeNode);
  36944. }
  36945. }
  36946. /**
  36947. * Detach a `LView` from the DOM by detaching its nodes.
  36948. *
  36949. * @param lView the `LView` to be detached.
  36950. */
  36951. function renderDetachView(lView) {
  36952. executeActionOnView(lView[RENDERER], 1 /* Detach */, lView, null, null);
  36953. }
  36954. /**
  36955. * Traverses down and up the tree of views and containers to remove listeners and
  36956. * call onDestroy callbacks.
  36957. *
  36958. * Notes:
  36959. * - Because it's used for onDestroy calls, it needs to be bottom-up.
  36960. * - Must process containers instead of their views to avoid splicing
  36961. * when views are destroyed and re-added.
  36962. * - Using a while loop because it's faster than recursion
  36963. * - Destroy only called on movement to sibling or movement to parent (laterally or up)
  36964. *
  36965. * @param rootView The view to destroy
  36966. */
  36967. function destroyViewTree(rootView) {
  36968. // If the view has no children, we can clean it up and return early.
  36969. var lViewOrLContainer = rootView[CHILD_HEAD];
  36970. if (!lViewOrLContainer) {
  36971. return cleanUpView(rootView);
  36972. }
  36973. while (lViewOrLContainer) {
  36974. var next = null;
  36975. if (isLView(lViewOrLContainer)) {
  36976. // If LView, traverse down to child.
  36977. next = lViewOrLContainer[CHILD_HEAD];
  36978. }
  36979. else {
  36980. ngDevMode && assertLContainer(lViewOrLContainer);
  36981. // If container, traverse down to its first LView.
  36982. var firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
  36983. if (firstView)
  36984. next = firstView;
  36985. }
  36986. if (!next) {
  36987. // Only clean up view when moving to the side or up, as destroy hooks
  36988. // should be called in order from the bottom up.
  36989. while (lViewOrLContainer && !lViewOrLContainer[NEXT] && lViewOrLContainer !== rootView) {
  36990. cleanUpView(lViewOrLContainer);
  36991. lViewOrLContainer = getParentState(lViewOrLContainer, rootView);
  36992. }
  36993. cleanUpView(lViewOrLContainer || rootView);
  36994. next = lViewOrLContainer && lViewOrLContainer[NEXT];
  36995. }
  36996. lViewOrLContainer = next;
  36997. }
  36998. }
  36999. /**
  37000. * A standalone function which destroys an LView,
  37001. * conducting cleanup (e.g. removing listeners, calling onDestroys).
  37002. *
  37003. * @param lView The view to be destroyed.
  37004. */
  37005. function destroyLView(lView) {
  37006. if (!(lView[FLAGS] & 256 /* Destroyed */)) {
  37007. var renderer = lView[RENDERER];
  37008. if (isProceduralRenderer(renderer) && renderer.destroyNode) {
  37009. executeActionOnView(renderer, 2 /* Destroy */, lView, null, null);
  37010. }
  37011. destroyViewTree(lView);
  37012. }
  37013. }
  37014. /**
  37015. * Determines which LViewOrLContainer to jump to when traversing back up the
  37016. * tree in destroyViewTree.
  37017. *
  37018. * Normally, the view's parent LView should be checked, but in the case of
  37019. * embedded views, the container (which is the view node's parent, but not the
  37020. * LView's parent) needs to be checked for a possible next property.
  37021. *
  37022. * @param lViewOrLContainer The LViewOrLContainer for which we need a parent state
  37023. * @param rootView The rootView, so we don't propagate too far up the view tree
  37024. * @returns The correct parent LViewOrLContainer
  37025. */
  37026. function getParentState(lViewOrLContainer, rootView) {
  37027. var tNode;
  37028. if (isLView(lViewOrLContainer) && (tNode = lViewOrLContainer[T_HOST]) &&
  37029. tNode.type === 2 /* View */) {
  37030. // if it's an embedded view, the state needs to go up to the container, in case the
  37031. // container has a next
  37032. return getLContainer(tNode, lViewOrLContainer);
  37033. }
  37034. else {
  37035. // otherwise, use parent view for containers or component views
  37036. return lViewOrLContainer[PARENT] === rootView ? null : lViewOrLContainer[PARENT];
  37037. }
  37038. }
  37039. /**
  37040. * Calls onDestroys hooks for all directives and pipes in a given view and then removes all
  37041. * listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
  37042. * can be propagated to @Output listeners.
  37043. *
  37044. * @param view The LView to clean up
  37045. */
  37046. function cleanUpView(view) {
  37047. if (isLView(view) && !(view[FLAGS] & 256 /* Destroyed */)) {
  37048. // Usually the Attached flag is removed when the view is detached from its parent, however
  37049. // if it's a root view, the flag won't be unset hence why we're also removing on destroy.
  37050. view[FLAGS] &= ~128 /* Attached */;
  37051. // Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
  37052. // runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
  37053. // We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
  37054. // This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
  37055. // really more of an "afterDestroy" hook if you think about it.
  37056. view[FLAGS] |= 256 /* Destroyed */;
  37057. executeOnDestroys(view);
  37058. removeListeners(view);
  37059. var hostTNode = view[T_HOST];
  37060. // For component views only, the local renderer is destroyed as clean up time.
  37061. if (hostTNode && hostTNode.type === 3 /* Element */ && isProceduralRenderer(view[RENDERER])) {
  37062. ngDevMode && ngDevMode.rendererDestroy++;
  37063. view[RENDERER].destroy();
  37064. }
  37065. // For embedded views still attached to a container: remove query result from this view.
  37066. if (viewAttachedToContainer(view) && view[QUERIES]) {
  37067. view[QUERIES].removeView();
  37068. }
  37069. }
  37070. }
  37071. /** Removes listeners and unsubscribes from output subscriptions */
  37072. function removeListeners(lView) {
  37073. var tCleanup = lView[TVIEW].cleanup;
  37074. if (tCleanup !== null) {
  37075. var lCleanup = lView[CLEANUP];
  37076. for (var i = 0; i < tCleanup.length - 1; i += 2) {
  37077. if (typeof tCleanup[i] === 'string') {
  37078. // This is a native DOM listener
  37079. var idxOrTargetGetter = tCleanup[i + 1];
  37080. var target = typeof idxOrTargetGetter === 'function' ?
  37081. idxOrTargetGetter(lView) :
  37082. unwrapRNode(lView[idxOrTargetGetter]);
  37083. var listener = lCleanup[tCleanup[i + 2]];
  37084. var useCaptureOrSubIdx = tCleanup[i + 3];
  37085. if (typeof useCaptureOrSubIdx === 'boolean') {
  37086. // native DOM listener registered with Renderer3
  37087. target.removeEventListener(tCleanup[i], listener, useCaptureOrSubIdx);
  37088. }
  37089. else {
  37090. if (useCaptureOrSubIdx >= 0) {
  37091. // unregister
  37092. lCleanup[useCaptureOrSubIdx]();
  37093. }
  37094. else {
  37095. // Subscription
  37096. lCleanup[-useCaptureOrSubIdx].unsubscribe();
  37097. }
  37098. }
  37099. i += 2;
  37100. }
  37101. else {
  37102. // This is a cleanup function that is grouped with the index of its context
  37103. var context = lCleanup[tCleanup[i + 1]];
  37104. tCleanup[i].call(context);
  37105. }
  37106. }
  37107. lView[CLEANUP] = null;
  37108. }
  37109. }
  37110. /** Calls onDestroy hooks for this view */
  37111. function executeOnDestroys(view) {
  37112. var tView = view[TVIEW];
  37113. var destroyHooks;
  37114. if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
  37115. for (var i = 0; i < destroyHooks.length; i += 2) {
  37116. var context = view[destroyHooks[i]];
  37117. // Only call the destroy hook if the context has been requested.
  37118. if (!(context instanceof NodeInjectorFactory)) {
  37119. destroyHooks[i + 1].call(context);
  37120. }
  37121. }
  37122. }
  37123. }
  37124. /**
  37125. * Inserts a native node before another native node for a given parent using {@link Renderer3}.
  37126. * This is a utility function that can be used when native nodes were determined - it abstracts an
  37127. * actual renderer being used.
  37128. */
  37129. function nativeInsertBefore(renderer, parent, child, beforeNode) {
  37130. ngDevMode && ngDevMode.rendererInsertBefore++;
  37131. if (isProceduralRenderer(renderer)) {
  37132. renderer.insertBefore(parent, child, beforeNode);
  37133. }
  37134. else {
  37135. parent.insertBefore(child, beforeNode, true);
  37136. }
  37137. }
  37138. /** Removes a node from the DOM given its native parent. */
  37139. function nativeRemoveChild(renderer, parent, child, isHostElement) {
  37140. if (isProceduralRenderer(renderer)) {
  37141. renderer.removeChild(parent, child, isHostElement);
  37142. }
  37143. else {
  37144. parent.removeChild(child);
  37145. }
  37146. }
  37147. /**
  37148. * Returns a native parent of a given native node.
  37149. */
  37150. function nativeParentNode(renderer, node) {
  37151. return (isProceduralRenderer(renderer) ? renderer.parentNode(node) : node.parentNode);
  37152. }
  37153. /**
  37154. * Removes a native node itself using a given renderer. To remove the node we are looking up its
  37155. * parent from the native tree as not all platforms / browsers support the equivalent of
  37156. * node.remove().
  37157. *
  37158. * @param renderer A renderer to be used
  37159. * @param rNode The native node that should be removed
  37160. * @param isHostElement A flag indicating if a node to be removed is a host of a component.
  37161. */
  37162. function nativeRemoveNode(renderer, rNode, isHostElement) {
  37163. var nativeParent = nativeParentNode(renderer, rNode);
  37164. if (nativeParent) {
  37165. nativeRemoveChild(renderer, nativeParent, rNode, isHostElement);
  37166. }
  37167. }
  37168. /**
  37169. * `executeActionOnView` performs an operation on the view as specified in `action` (insert, detach,
  37170. * destroy)
  37171. *
  37172. * Inserting a view without projection or containers at top level is simple. Just iterate over the
  37173. * root nodes of the View, and for each node perform the `action`.
  37174. *
  37175. * Things get more complicated with containers and projections. That is because coming across:
  37176. * - Container: implies that we have to insert/remove/destroy the views of that container as well
  37177. * which in turn can have their own Containers at the View roots.
  37178. * - Projection: implies that we have to insert/remove/destroy the nodes of the projection. The
  37179. * complication is that the nodes we are projecting can themselves have Containers
  37180. * or other Projections.
  37181. *
  37182. * As you can see this is a very recursive problem. While the recursive implementation is not the
  37183. * most efficient one, trying to unroll the nodes non-recursively results in very complex code that
  37184. * is very hard (to maintain). We are sacrificing a bit of performance for readability using a
  37185. * recursive implementation.
  37186. *
  37187. * @param renderer Renderer to use
  37188. * @param action action to perform (insert, detach, destroy)
  37189. * @param lView The LView which needs to be inserted, detached, destroyed.
  37190. * @param renderParent parent DOM element for insertion/removal.
  37191. * @param beforeNode Before which node the insertions should happen.
  37192. */
  37193. function executeActionOnView(renderer, action, lView, renderParent, beforeNode) {
  37194. var tView = lView[TVIEW];
  37195. ngDevMode && assertNodeType(tView.node, 2 /* View */);
  37196. var viewRootTNode = tView.node.child;
  37197. while (viewRootTNode !== null) {
  37198. executeActionOnNode(renderer, action, lView, viewRootTNode, renderParent, beforeNode);
  37199. viewRootTNode = viewRootTNode.next;
  37200. }
  37201. }
  37202. /**
  37203. * `executeActionOnProjection` performs an operation on the projection specified by `action`
  37204. * (insert, detach, destroy).
  37205. *
  37206. * Inserting a projection requires us to locate the projected nodes from the parent component. The
  37207. * complication is that those nodes themselves could be re-projected from their parent component.
  37208. *
  37209. * @param renderer Renderer to use
  37210. * @param action action to perform (insert, detach, destroy)
  37211. * @param lView The LView which needs to be inserted, detached, destroyed.
  37212. * @param renderParent parent DOM element for insertion/removal.
  37213. * @param beforeNode Before which node the insertions should happen.
  37214. */
  37215. function executeActionOnProjection(renderer, action, lView, tProjectionNode, renderParent, beforeNode) {
  37216. var componentLView = findComponentView(lView);
  37217. var componentNode = componentLView[T_HOST];
  37218. var nodeToProject = componentNode.projection[tProjectionNode.projection];
  37219. if (Array.isArray(nodeToProject)) {
  37220. for (var i = 0; i < nodeToProject.length; i++) {
  37221. var rNode = nodeToProject[i];
  37222. ngDevMode && assertDomNode(rNode);
  37223. executeActionOnElementOrContainer(action, renderer, renderParent, rNode, beforeNode);
  37224. }
  37225. }
  37226. else {
  37227. var projectionTNode = nodeToProject;
  37228. var projectedComponentLView = componentLView[PARENT];
  37229. while (projectionTNode !== null) {
  37230. executeActionOnNode(renderer, action, projectedComponentLView, projectionTNode, renderParent, beforeNode);
  37231. projectionTNode = projectionTNode.projectionNext;
  37232. }
  37233. }
  37234. }
  37235. /**
  37236. * `executeActionOnContainer` performs an operation on the container and its views as specified by
  37237. * `action` (insert, detach, destroy)
  37238. *
  37239. * Inserting a Container is complicated by the fact that the container may have Views which
  37240. * themselves have containers or projections.
  37241. *
  37242. * @param renderer Renderer to use
  37243. * @param action action to perform (insert, detach, destroy)
  37244. * @param lContainer The LContainer which needs to be inserted, detached, destroyed.
  37245. * @param renderParent parent DOM element for insertion/removal.
  37246. * @param beforeNode Before which node the insertions should happen.
  37247. */
  37248. function executeActionOnContainer(renderer, action, lContainer, renderParent, beforeNode) {
  37249. ngDevMode && assertLContainer(lContainer);
  37250. var anchor = lContainer[NATIVE]; // LContainer has its own before node.
  37251. var native = unwrapRNode(lContainer);
  37252. // An LContainer can be created dynamically on any node by injecting ViewContainerRef.
  37253. // Asking for a ViewContainerRef on an element will result in a creation of a separate anchor node
  37254. // (comment in the DOM) that will be different from the LContainer's host node. In this particular
  37255. // case we need to execute action on 2 nodes:
  37256. // - container's host node (this is done in the executeNodeAction)
  37257. // - container's host node (this is done here)
  37258. if (anchor !== native) {
  37259. executeActionOnElementOrContainer(action, renderer, renderParent, anchor, beforeNode);
  37260. }
  37261. for (var i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  37262. var lView = lContainer[i];
  37263. executeActionOnView(renderer, action, lView, renderParent, anchor);
  37264. }
  37265. }
  37266. /**
  37267. * `executeActionOnElementContainer` performs an operation on the ng-container node and its child
  37268. * nodes as specified by the `action` (insert, detach, destroy).
  37269. *
  37270. * @param renderer Renderer to use
  37271. * @param action action to perform (insert, detach, destroy)
  37272. * @param lView The LView which needs to be inserted, detached, destroyed.
  37273. * @param tElementContainerNode The TNode associated with the ElementContainer.
  37274. * @param renderParent parent DOM element for insertion/removal.
  37275. * @param beforeNode Before which node the insertions should happen.
  37276. */
  37277. function executeActionOnElementContainer(renderer, action, lView, tElementContainerNode, renderParent, beforeNode) {
  37278. var node = lView[tElementContainerNode.index];
  37279. executeActionOnElementOrContainer(action, renderer, renderParent, node, beforeNode);
  37280. var childTNode = tElementContainerNode.child;
  37281. while (childTNode) {
  37282. executeActionOnNode(renderer, action, lView, childTNode, renderParent, beforeNode);
  37283. childTNode = childTNode.next;
  37284. }
  37285. }
  37286. function executeActionOnNode(renderer, action, lView, tNode, renderParent, beforeNode) {
  37287. var elementContainerRootTNodeType = tNode.type;
  37288. if (elementContainerRootTNodeType === 4 /* ElementContainer */) {
  37289. executeActionOnElementContainer(renderer, action, lView, tNode, renderParent, beforeNode);
  37290. }
  37291. else if (elementContainerRootTNodeType === 1 /* Projection */) {
  37292. executeActionOnProjection(renderer, action, lView, tNode, renderParent, beforeNode);
  37293. }
  37294. else {
  37295. ngDevMode && assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */);
  37296. executeActionOnElementOrContainer(action, renderer, renderParent, lView[tNode.index], beforeNode);
  37297. }
  37298. }
  37299. /**
  37300. * @license
  37301. * Copyright Google Inc. All Rights Reserved.
  37302. *
  37303. * Use of this source code is governed by an MIT-style license that can be
  37304. * found in the LICENSE file at https://angular.io/license
  37305. */
  37306. /**
  37307. * @license
  37308. * Copyright Google Inc. All Rights Reserved.
  37309. *
  37310. * Use of this source code is governed by an MIT-style license that can be
  37311. * found in the LICENSE file at https://angular.io/license
  37312. */
  37313. /**
  37314. * @license
  37315. * Copyright Google Inc. All Rights Reserved.
  37316. *
  37317. * Use of this source code is governed by an MIT-style license that can be
  37318. * found in the LICENSE file at https://angular.io/license
  37319. */
  37320. /**
  37321. * @license
  37322. * Copyright Google Inc. All Rights Reserved.
  37323. *
  37324. * Use of this source code is governed by an MIT-style license that can be
  37325. * found in the LICENSE file at https://angular.io/license
  37326. */
  37327. /**
  37328. * @license
  37329. * Copyright Google Inc. All Rights Reserved.
  37330. *
  37331. * Use of this source code is governed by an MIT-style license that can be
  37332. * found in the LICENSE file at https://angular.io/license
  37333. */
  37334. /**
  37335. * @license
  37336. * Copyright Google Inc. All Rights Reserved.
  37337. *
  37338. * Use of this source code is governed by an MIT-style license that can be
  37339. * found in the LICENSE file at https://angular.io/license
  37340. */
  37341. /**
  37342. * @license
  37343. * Copyright Google Inc. All Rights Reserved.
  37344. *
  37345. * Use of this source code is governed by an MIT-style license that can be
  37346. * found in the LICENSE file at https://angular.io/license
  37347. */
  37348. /**
  37349. * Determine if the argument is shaped like a Promise
  37350. */
  37351. function isPromise$1(obj) {
  37352. // allow any Promise/A+ compliant thenable.
  37353. // It's up to the caller to ensure that obj.then conforms to the spec
  37354. return !!obj && typeof obj.then === 'function';
  37355. }
  37356. /**
  37357. * Determine if the argument is an Observable
  37358. */
  37359. function isObservable(obj) {
  37360. // TODO: use isObservable once we update pass rxjs 6.1
  37361. // https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#610-2018-05-03
  37362. return !!obj && typeof obj.subscribe === 'function';
  37363. }
  37364. /**
  37365. * @license
  37366. * Copyright Google Inc. All Rights Reserved.
  37367. *
  37368. * Use of this source code is governed by an MIT-style license that can be
  37369. * found in the LICENSE file at https://angular.io/license
  37370. */
  37371. /**
  37372. * @license
  37373. * Copyright Google Inc. All Rights Reserved.
  37374. *
  37375. * Use of this source code is governed by an MIT-style license that can be
  37376. * found in the LICENSE file at https://angular.io/license
  37377. */
  37378. /**
  37379. * @license
  37380. * Copyright Google Inc. All Rights Reserved.
  37381. *
  37382. * Use of this source code is governed by an MIT-style license that can be
  37383. * found in the LICENSE file at https://angular.io/license
  37384. */
  37385. /**
  37386. * @license
  37387. * Copyright Google Inc. All Rights Reserved.
  37388. *
  37389. * Use of this source code is governed by an MIT-style license that can be
  37390. * found in the LICENSE file at https://angular.io/license
  37391. */
  37392. /**
  37393. * @license
  37394. * Copyright Google Inc. All Rights Reserved.
  37395. *
  37396. * Use of this source code is governed by an MIT-style license that can be
  37397. * found in the LICENSE file at https://angular.io/license
  37398. */
  37399. /**
  37400. * @license
  37401. * Copyright Google Inc. All Rights Reserved.
  37402. *
  37403. * Use of this source code is governed by an MIT-style license that can be
  37404. * found in the LICENSE file at https://angular.io/license
  37405. */
  37406. /**
  37407. * @license
  37408. * Copyright Google Inc. All Rights Reserved.
  37409. *
  37410. * Use of this source code is governed by an MIT-style license that can be
  37411. * found in the LICENSE file at https://angular.io/license
  37412. */
  37413. /**
  37414. * @license
  37415. * Copyright Google Inc. All Rights Reserved.
  37416. *
  37417. * Use of this source code is governed by an MIT-style license that can be
  37418. * found in the LICENSE file at https://angular.io/license
  37419. */
  37420. /**
  37421. * Returns the component instance associated with a given DOM host element.
  37422. * Elements which don't represent components return `null`.
  37423. *
  37424. * @param element Host DOM element from which the component should be retrieved.
  37425. *
  37426. * ```
  37427. * <my-app>
  37428. * #VIEW
  37429. * <div>
  37430. * <child-comp></child-comp>
  37431. * </div>
  37432. * </mp-app>
  37433. *
  37434. * expect(getComponent(<child-comp>) instanceof ChildComponent).toBeTruthy();
  37435. * expect(getComponent(<my-app>) instanceof MyApp).toBeTruthy();
  37436. * ```
  37437. *
  37438. * @publicApi
  37439. */
  37440. function getComponent(element) {
  37441. var context = loadLContextFromNode(element);
  37442. if (context.component === undefined) {
  37443. context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
  37444. }
  37445. return context.component;
  37446. }
  37447. /**
  37448. * Returns the component instance associated with a given DOM host element.
  37449. * Elements which don't represent components return `null`.
  37450. *
  37451. * @param element Host DOM element from which the component should be retrieved.
  37452. *
  37453. * ```
  37454. * <my-app>
  37455. * #VIEW
  37456. * <div>
  37457. * <child-comp></child-comp>
  37458. * </div>
  37459. * </mp-app>
  37460. *
  37461. * expect(getComponent(<child-comp>) instanceof ChildComponent).toBeTruthy();
  37462. * expect(getComponent(<my-app>) instanceof MyApp).toBeTruthy();
  37463. * ```
  37464. *
  37465. * @publicApi
  37466. */
  37467. function getContext(element) {
  37468. var context = loadLContextFromNode(element);
  37469. return context.lView[CONTEXT];
  37470. }
  37471. /**
  37472. * Returns the component instance associated with view which owns the DOM element (`null`
  37473. * otherwise).
  37474. *
  37475. * @param element DOM element which is owned by an existing component's view.
  37476. *
  37477. * ```
  37478. * <my-app>
  37479. * #VIEW
  37480. * <div>
  37481. * <child-comp></child-comp>
  37482. * </div>
  37483. * </mp-app>
  37484. *
  37485. * expect(getViewComponent(<child-comp>) instanceof MyApp).toBeTruthy();
  37486. * expect(getViewComponent(<my-app>)).toEqual(null);
  37487. * ```
  37488. *
  37489. * @publicApi
  37490. */
  37491. function getViewComponent(element) {
  37492. var context = loadLContext(element);
  37493. var lView = context.lView;
  37494. var parent;
  37495. ngDevMode && assertLView(lView);
  37496. while (lView[HOST] === null && (parent = getLViewParent(lView))) {
  37497. // As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
  37498. lView = parent;
  37499. }
  37500. return lView[FLAGS] & 512 /* IsRoot */ ? null : lView[CONTEXT];
  37501. }
  37502. /**
  37503. * Retrieves an `Injector` associated with the element, component or directive.
  37504. *
  37505. * @param target A DOM element, component or directive instance.
  37506. *
  37507. * @publicApi
  37508. */
  37509. function getInjector(target) {
  37510. var context = loadLContext(target);
  37511. var tNode = context.lView[TVIEW].data[context.nodeIndex];
  37512. return new NodeInjector(tNode, context.lView);
  37513. }
  37514. /**
  37515. * Retrieve a set of injection tokens at a given DOM node.
  37516. *
  37517. * @param element Element for which the injection tokens should be retrieved.
  37518. * @publicApi
  37519. */
  37520. function getInjectionTokens(element) {
  37521. var context = loadLContext(element, false);
  37522. if (!context)
  37523. return [];
  37524. var lView = context.lView;
  37525. var tView = lView[TVIEW];
  37526. var tNode = tView.data[context.nodeIndex];
  37527. var providerTokens = [];
  37528. var startIndex = tNode.providerIndexes & 65535 /* ProvidersStartIndexMask */;
  37529. var endIndex = tNode.directiveEnd;
  37530. for (var i = startIndex; i < endIndex; i++) {
  37531. var value = tView.data[i];
  37532. if (isDirectiveDefHack(value)) {
  37533. // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
  37534. // design flaw. We should always store same type so that we can be monomorphic. The issue
  37535. // is that for Components/Directives we store the def instead the type. The correct behavior
  37536. // is that we should always be storing injectable type in this location.
  37537. value = value.type;
  37538. }
  37539. providerTokens.push(value);
  37540. }
  37541. return providerTokens;
  37542. }
  37543. function loadLContext(target, throwOnNotFound) {
  37544. if (throwOnNotFound === void 0) { throwOnNotFound = true; }
  37545. var context = getLContext(target);
  37546. if (!context && throwOnNotFound) {
  37547. throw new Error(ngDevMode ? "Unable to find context associated with " + stringifyForError(target) :
  37548. 'Invalid ng target');
  37549. }
  37550. return context;
  37551. }
  37552. /**
  37553. * Retrieve map of local references.
  37554. *
  37555. * The references are retrieved as a map of local reference name to element or directive instance.
  37556. *
  37557. * @param target A DOM element, component or directive instance.
  37558. *
  37559. * @publicApi
  37560. */
  37561. function getLocalRefs(target) {
  37562. var context = loadLContext(target);
  37563. if (context.localRefs === undefined) {
  37564. context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
  37565. }
  37566. return context.localRefs || {};
  37567. }
  37568. function loadLContextFromNode(node) {
  37569. if (!(node instanceof Node))
  37570. throw new Error('Expecting instance of DOM Node');
  37571. return loadLContext(node);
  37572. }
  37573. function isBrowserEvents(listener) {
  37574. // Browser events are those which don't have `useCapture` as boolean.
  37575. return typeof listener.useCapture === 'boolean';
  37576. }
  37577. /**
  37578. * Retrieves a list of DOM listeners.
  37579. *
  37580. * ```
  37581. * <my-app>
  37582. * #VIEW
  37583. * <div (click)="doSomething()">
  37584. * </div>
  37585. * </mp-app>
  37586. *
  37587. * expect(getListeners(<div>)).toEqual({
  37588. * name: 'click',
  37589. * element: <div>,
  37590. * callback: () => doSomething(),
  37591. * useCapture: false
  37592. * });
  37593. * ```
  37594. *
  37595. * @param element Element for which the DOM listeners should be retrieved.
  37596. * @publicApi
  37597. */
  37598. function getListeners(element) {
  37599. var lContext = loadLContextFromNode(element);
  37600. var lView = lContext.lView;
  37601. var tView = lView[TVIEW];
  37602. var lCleanup = lView[CLEANUP];
  37603. var tCleanup = tView.cleanup;
  37604. var listeners = [];
  37605. if (tCleanup && lCleanup) {
  37606. for (var i = 0; i < tCleanup.length;) {
  37607. var firstParam = tCleanup[i++];
  37608. var secondParam = tCleanup[i++];
  37609. if (typeof firstParam === 'string') {
  37610. var name_1 = firstParam;
  37611. var listenerElement = unwrapRNode(lView[secondParam]);
  37612. var callback = lCleanup[tCleanup[i++]];
  37613. var useCaptureOrIndx = tCleanup[i++];
  37614. // if useCaptureOrIndx is boolean then report it as is.
  37615. // if useCaptureOrIndx is positive number then it in unsubscribe method
  37616. // if useCaptureOrIndx is negative number then it is a Subscription
  37617. var useCapture = typeof useCaptureOrIndx === 'boolean' ?
  37618. useCaptureOrIndx :
  37619. (useCaptureOrIndx >= 0 ? false : null);
  37620. if (element == listenerElement) {
  37621. listeners.push({ element: element, name: name_1, callback: callback, useCapture: useCapture });
  37622. }
  37623. }
  37624. }
  37625. }
  37626. listeners.sort(sortListeners);
  37627. return listeners;
  37628. }
  37629. function sortListeners(a, b) {
  37630. if (a.name == b.name)
  37631. return 0;
  37632. return a.name < b.name ? -1 : 1;
  37633. }
  37634. /**
  37635. * This function should not exist because it is megamorphic and only mostly correct.
  37636. *
  37637. * See call site for more info.
  37638. */
  37639. function isDirectiveDefHack(obj) {
  37640. return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
  37641. }
  37642. /**
  37643. * @license
  37644. * Copyright Google Inc. All Rights Reserved.
  37645. *
  37646. * Use of this source code is governed by an MIT-style license that can be
  37647. * found in the LICENSE file at https://angular.io/license
  37648. */
  37649. /**
  37650. * @license
  37651. * Copyright Google Inc. All Rights Reserved.
  37652. *
  37653. * Use of this source code is governed by an MIT-style license that can be
  37654. * found in the LICENSE file at https://angular.io/license
  37655. */
  37656. /**
  37657. * @license
  37658. * Copyright Google Inc. All Rights Reserved.
  37659. *
  37660. * Use of this source code is governed by an MIT-style license that can be
  37661. * found in the LICENSE file at https://angular.io/license
  37662. */
  37663. /**
  37664. * Creates the root component view and the root component node.
  37665. *
  37666. * @param rNode Render host element.
  37667. * @param def ComponentDef
  37668. * @param rootView The parent view where the host node is stored
  37669. * @param renderer The current renderer
  37670. * @param sanitizer The sanitizer, if provided
  37671. *
  37672. * @returns Component view created
  37673. */
  37674. function createRootComponentView(rNode, def, rootView, rendererFactory, renderer, sanitizer) {
  37675. resetComponentState();
  37676. var tView = rootView[TVIEW];
  37677. ngDevMode && assertDataInRange(rootView, 0 + HEADER_OFFSET);
  37678. rootView[0 + HEADER_OFFSET] = rNode;
  37679. var tNode = getOrCreateTNode(tView, null, 0, 3 /* Element */, null, null);
  37680. var componentView = createLView(rootView, getOrCreateTView(def), null, def.onPush ? 64 /* Dirty */ : 16 /* CheckAlways */, rootView[HEADER_OFFSET], tNode, rendererFactory, renderer, sanitizer);
  37681. if (tView.firstTemplatePass) {
  37682. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, rootView), rootView, def.type);
  37683. tNode.flags = 1 /* isComponent */;
  37684. initNodeFlags(tNode, rootView.length, 1);
  37685. queueComponentIndexForCheck(tNode);
  37686. }
  37687. // Store component view at node index, with node as the HOST
  37688. return rootView[HEADER_OFFSET] = componentView;
  37689. }
  37690. /**
  37691. * Creates a root component and sets it up with features and host bindings. Shared by
  37692. * renderComponent() and ViewContainerRef.createComponent().
  37693. */
  37694. function createRootComponent(componentView, componentDef, rootView, rootContext, hostFeatures) {
  37695. var tView = rootView[TVIEW];
  37696. // Create directive instance with factory() and store at next index in viewData
  37697. var component = instantiateRootComponent(tView, rootView, componentDef);
  37698. rootContext.components.push(component);
  37699. componentView[CONTEXT] = component;
  37700. hostFeatures && hostFeatures.forEach(function (feature) { return feature(component, componentDef); });
  37701. // We want to generate an empty QueryList for root content queries for backwards
  37702. // compatibility with ViewEngine.
  37703. if (componentDef.contentQueries) {
  37704. componentDef.contentQueries(1 /* Create */, component, rootView.length - 1);
  37705. }
  37706. var rootTNode = getPreviousOrParentTNode();
  37707. if (tView.firstTemplatePass && componentDef.hostBindings) {
  37708. var elementIndex = rootTNode.index - HEADER_OFFSET;
  37709. var expando = tView.expandoInstructions;
  37710. invokeHostBindingsInCreationMode(componentDef, expando, component, rootTNode, tView.firstTemplatePass);
  37711. rootTNode.onElementCreationFns && applyOnCreateInstructions(rootTNode);
  37712. }
  37713. if (rootTNode.stylingTemplate) {
  37714. var native = componentView[HOST];
  37715. renderInitialClasses(native, rootTNode.stylingTemplate, componentView[RENDERER]);
  37716. renderInitialStyles(native, rootTNode.stylingTemplate, componentView[RENDERER]);
  37717. }
  37718. return component;
  37719. }
  37720. function createRootContext(scheduler, playerHandler) {
  37721. return {
  37722. components: [],
  37723. scheduler: scheduler || defaultScheduler,
  37724. clean: CLEAN_PROMISE,
  37725. playerHandler: playerHandler || null,
  37726. flags: 0 /* Empty */
  37727. };
  37728. }
  37729. /**
  37730. * Used to enable lifecycle hooks on the root component.
  37731. *
  37732. * Include this feature when calling `renderComponent` if the root component
  37733. * you are rendering has lifecycle hooks defined. Otherwise, the hooks won't
  37734. * be called properly.
  37735. *
  37736. * Example:
  37737. *
  37738. * ```
  37739. * renderComponent(AppComponent, {features: [RootLifecycleHooks]});
  37740. * ```
  37741. */
  37742. function LifecycleHooksFeature(component, def) {
  37743. var rootTView = readPatchedLView(component)[TVIEW];
  37744. var dirIndex = rootTView.data.length - 1;
  37745. registerPreOrderHooks(dirIndex, def, rootTView, -1, -1, -1);
  37746. // TODO(misko): replace `as TNode` with createTNode call. (needs refactoring to lose dep on
  37747. // LNode).
  37748. registerPostOrderHooks(rootTView, { directiveStart: dirIndex, directiveEnd: dirIndex + 1 });
  37749. }
  37750. /**
  37751. * @license
  37752. * Copyright Google Inc. All Rights Reserved.
  37753. *
  37754. * Use of this source code is governed by an MIT-style license that can be
  37755. * found in the LICENSE file at https://angular.io/license
  37756. */
  37757. /**
  37758. * Represents a basic change from a previous to a new value for a single
  37759. * property on a directive instance. Passed as a value in a
  37760. * {@link SimpleChanges} object to the `ngOnChanges` hook.
  37761. *
  37762. * @see `OnChanges`
  37763. *
  37764. * @publicApi
  37765. */
  37766. var SimpleChange = /** @class */ (function () {
  37767. function SimpleChange(previousValue, currentValue, firstChange) {
  37768. this.previousValue = previousValue;
  37769. this.currentValue = currentValue;
  37770. this.firstChange = firstChange;
  37771. }
  37772. /**
  37773. * Check whether the new value is the first value assigned.
  37774. */
  37775. SimpleChange.prototype.isFirstChange = function () { return this.firstChange; };
  37776. return SimpleChange;
  37777. }());
  37778. /**
  37779. * @license
  37780. * Copyright Google Inc. All Rights Reserved.
  37781. *
  37782. * Use of this source code is governed by an MIT-style license that can be
  37783. * found in the LICENSE file at https://angular.io/license
  37784. */
  37785. /**
  37786. * @license
  37787. * Copyright Google Inc. All Rights Reserved.
  37788. *
  37789. * Use of this source code is governed by an MIT-style license that can be
  37790. * found in the LICENSE file at https://angular.io/license
  37791. */
  37792. /**
  37793. * @license
  37794. * Copyright Google Inc. All Rights Reserved.
  37795. *
  37796. * Use of this source code is governed by an MIT-style license that can be
  37797. * found in the LICENSE file at https://angular.io/license
  37798. */
  37799. /**
  37800. * @license
  37801. * Copyright Google Inc. All Rights Reserved.
  37802. *
  37803. * Use of this source code is governed by an MIT-style license that can be
  37804. * found in the LICENSE file at https://angular.io/license
  37805. */
  37806. /**
  37807. * Represents a component created by a `ComponentFactory`.
  37808. * Provides access to the component instance and related objects,
  37809. * and provides the means of destroying the instance.
  37810. *
  37811. * @publicApi
  37812. */
  37813. var ComponentRef = /** @class */ (function () {
  37814. function ComponentRef() {
  37815. }
  37816. return ComponentRef;
  37817. }());
  37818. /**
  37819. * Base class for a factory that can create a component dynamically.
  37820. * Instantiate a factory for a given type of component with `resolveComponentFactory()`.
  37821. * Use the resulting `ComponentFactory.create()` method to create a component of that type.
  37822. *
  37823. * @see [Dynamic Components](guide/dynamic-component-loader)
  37824. *
  37825. * @publicApi
  37826. */
  37827. var ComponentFactory = /** @class */ (function () {
  37828. function ComponentFactory() {
  37829. }
  37830. return ComponentFactory;
  37831. }());
  37832. /**
  37833. * @license
  37834. * Copyright Google Inc. All Rights Reserved.
  37835. *
  37836. * Use of this source code is governed by an MIT-style license that can be
  37837. * found in the LICENSE file at https://angular.io/license
  37838. */
  37839. function noComponentFactoryError(component) {
  37840. var error = Error("No component factory found for " + stringify$1(component) + ". Did you add it to @NgModule.entryComponents?");
  37841. error[ERROR_COMPONENT] = component;
  37842. return error;
  37843. }
  37844. var ERROR_COMPONENT = 'ngComponent';
  37845. var _NullComponentFactoryResolver = /** @class */ (function () {
  37846. function _NullComponentFactoryResolver() {
  37847. }
  37848. _NullComponentFactoryResolver.prototype.resolveComponentFactory = function (component) {
  37849. throw noComponentFactoryError(component);
  37850. };
  37851. return _NullComponentFactoryResolver;
  37852. }());
  37853. /**
  37854. * A simple registry that maps `Components` to generated `ComponentFactory` classes
  37855. * that can be used to create instances of components.
  37856. * Use to obtain the factory for a given component type,
  37857. * then use the factory's `create()` method to create a component of that type.
  37858. *
  37859. * @see [Dynamic Components](guide/dynamic-component-loader)
  37860. * @publicApi
  37861. */
  37862. var ComponentFactoryResolver = /** @class */ (function () {
  37863. function ComponentFactoryResolver() {
  37864. }
  37865. ComponentFactoryResolver.NULL = new _NullComponentFactoryResolver();
  37866. return ComponentFactoryResolver;
  37867. }());
  37868. var ComponentFactoryBoundToModule = /** @class */ (function (_super) {
  37869. __extends(ComponentFactoryBoundToModule, _super);
  37870. function ComponentFactoryBoundToModule(factory, ngModule) {
  37871. var _this = _super.call(this) || this;
  37872. _this.factory = factory;
  37873. _this.ngModule = ngModule;
  37874. _this.selector = factory.selector;
  37875. _this.componentType = factory.componentType;
  37876. _this.ngContentSelectors = factory.ngContentSelectors;
  37877. _this.inputs = factory.inputs;
  37878. _this.outputs = factory.outputs;
  37879. return _this;
  37880. }
  37881. ComponentFactoryBoundToModule.prototype.create = function (injector, projectableNodes, rootSelectorOrNode, ngModule) {
  37882. return this.factory.create(injector, projectableNodes, rootSelectorOrNode, ngModule || this.ngModule);
  37883. };
  37884. return ComponentFactoryBoundToModule;
  37885. }(ComponentFactory));
  37886. /**
  37887. * @license
  37888. * Copyright Google Inc. All Rights Reserved.
  37889. *
  37890. * Use of this source code is governed by an MIT-style license that can be
  37891. * found in the LICENSE file at https://angular.io/license
  37892. */
  37893. /**
  37894. * Represents an instance of an NgModule created via a {@link NgModuleFactory}.
  37895. *
  37896. * `NgModuleRef` provides access to the NgModule Instance as well other objects related to this
  37897. * NgModule Instance.
  37898. *
  37899. * @publicApi
  37900. */
  37901. var NgModuleRef = /** @class */ (function () {
  37902. function NgModuleRef() {
  37903. }
  37904. return NgModuleRef;
  37905. }());
  37906. /**
  37907. * @publicApi
  37908. */
  37909. var NgModuleFactory = /** @class */ (function () {
  37910. function NgModuleFactory() {
  37911. }
  37912. return NgModuleFactory;
  37913. }());
  37914. /**
  37915. * @license
  37916. * Copyright Google Inc. All Rights Reserved.
  37917. *
  37918. * Use of this source code is governed by an MIT-style license that can be
  37919. * found in the LICENSE file at https://angular.io/license
  37920. */
  37921. var ViewRef = /** @class */ (function () {
  37922. function ViewRef(_lView, _context, _componentIndex) {
  37923. this._context = _context;
  37924. this._componentIndex = _componentIndex;
  37925. this._appRef = null;
  37926. this._viewContainerRef = null;
  37927. /**
  37928. * @internal
  37929. */
  37930. this._tViewNode = null;
  37931. this._lView = _lView;
  37932. }
  37933. Object.defineProperty(ViewRef.prototype, "rootNodes", {
  37934. get: function () {
  37935. if (this._lView[HOST] == null) {
  37936. var tView = this._lView[T_HOST];
  37937. return collectNativeNodes(this._lView, tView, []);
  37938. }
  37939. return [];
  37940. },
  37941. enumerable: true,
  37942. configurable: true
  37943. });
  37944. Object.defineProperty(ViewRef.prototype, "context", {
  37945. get: function () { return this._context ? this._context : this._lookUpContext(); },
  37946. enumerable: true,
  37947. configurable: true
  37948. });
  37949. Object.defineProperty(ViewRef.prototype, "destroyed", {
  37950. get: function () {
  37951. return (this._lView[FLAGS] & 256 /* Destroyed */) === 256 /* Destroyed */;
  37952. },
  37953. enumerable: true,
  37954. configurable: true
  37955. });
  37956. ViewRef.prototype.destroy = function () {
  37957. if (this._appRef) {
  37958. this._appRef.detachView(this);
  37959. }
  37960. else if (this._viewContainerRef) {
  37961. var index = this._viewContainerRef.indexOf(this);
  37962. if (index > -1) {
  37963. this._viewContainerRef.detach(index);
  37964. }
  37965. this._viewContainerRef = null;
  37966. }
  37967. destroyLView(this._lView);
  37968. };
  37969. ViewRef.prototype.onDestroy = function (callback) { storeCleanupFn(this._lView, callback); };
  37970. /**
  37971. * Marks a view and all of its ancestors dirty.
  37972. *
  37973. * It also triggers change detection by calling `scheduleTick` internally, which coalesces
  37974. * multiple `markForCheck` calls to into one change detection run.
  37975. *
  37976. * This can be used to ensure an {@link ChangeDetectionStrategy#OnPush OnPush} component is
  37977. * checked when it needs to be re-rendered but the two normal triggers haven't marked it
  37978. * dirty (i.e. inputs haven't changed and events haven't fired in the view).
  37979. *
  37980. * <!-- TODO: Add a link to a chapter on OnPush components -->
  37981. *
  37982. * @usageNotes
  37983. * ### Example
  37984. *
  37985. * ```typescript
  37986. * @Component({
  37987. * selector: 'my-app',
  37988. * template: `Number of ticks: {{numberOfTicks}}`
  37989. * changeDetection: ChangeDetectionStrategy.OnPush,
  37990. * })
  37991. * class AppComponent {
  37992. * numberOfTicks = 0;
  37993. *
  37994. * constructor(private ref: ChangeDetectorRef) {
  37995. * setInterval(() => {
  37996. * this.numberOfTicks++;
  37997. * // the following is required, otherwise the view will not be updated
  37998. * this.ref.markForCheck();
  37999. * }, 1000);
  38000. * }
  38001. * }
  38002. * ```
  38003. */
  38004. ViewRef.prototype.markForCheck = function () { markViewDirty(this._lView); };
  38005. /**
  38006. * Detaches the view from the change detection tree.
  38007. *
  38008. * Detached views will not be checked during change detection runs until they are
  38009. * re-attached, even if they are dirty. `detach` can be used in combination with
  38010. * {@link ChangeDetectorRef#detectChanges detectChanges} to implement local change
  38011. * detection checks.
  38012. *
  38013. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  38014. * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
  38015. *
  38016. * @usageNotes
  38017. * ### Example
  38018. *
  38019. * The following example defines a component with a large list of readonly data.
  38020. * Imagine the data changes constantly, many times per second. For performance reasons,
  38021. * we want to check and update the list every five seconds. We can do that by detaching
  38022. * the component's change detector and doing a local check every five seconds.
  38023. *
  38024. * ```typescript
  38025. * class DataProvider {
  38026. * // in a real application the returned data will be different every time
  38027. * get data() {
  38028. * return [1,2,3,4,5];
  38029. * }
  38030. * }
  38031. *
  38032. * @Component({
  38033. * selector: 'giant-list',
  38034. * template: `
  38035. * <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
  38036. * `,
  38037. * })
  38038. * class GiantList {
  38039. * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
  38040. * ref.detach();
  38041. * setInterval(() => {
  38042. * this.ref.detectChanges();
  38043. * }, 5000);
  38044. * }
  38045. * }
  38046. *
  38047. * @Component({
  38048. * selector: 'app',
  38049. * providers: [DataProvider],
  38050. * template: `
  38051. * <giant-list><giant-list>
  38052. * `,
  38053. * })
  38054. * class App {
  38055. * }
  38056. * ```
  38057. */
  38058. ViewRef.prototype.detach = function () { this._lView[FLAGS] &= ~128 /* Attached */; };
  38059. /**
  38060. * Re-attaches a view to the change detection tree.
  38061. *
  38062. * This can be used to re-attach views that were previously detached from the tree
  38063. * using {@link ChangeDetectorRef#detach detach}. Views are attached to the tree by default.
  38064. *
  38065. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  38066. *
  38067. * @usageNotes
  38068. * ### Example
  38069. *
  38070. * The following example creates a component displaying `live` data. The component will detach
  38071. * its change detector from the main change detector tree when the component's live property
  38072. * is set to false.
  38073. *
  38074. * ```typescript
  38075. * class DataProvider {
  38076. * data = 1;
  38077. *
  38078. * constructor() {
  38079. * setInterval(() => {
  38080. * this.data = this.data * 2;
  38081. * }, 500);
  38082. * }
  38083. * }
  38084. *
  38085. * @Component({
  38086. * selector: 'live-data',
  38087. * inputs: ['live'],
  38088. * template: 'Data: {{dataProvider.data}}'
  38089. * })
  38090. * class LiveData {
  38091. * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
  38092. *
  38093. * set live(value) {
  38094. * if (value) {
  38095. * this.ref.reattach();
  38096. * } else {
  38097. * this.ref.detach();
  38098. * }
  38099. * }
  38100. * }
  38101. *
  38102. * @Component({
  38103. * selector: 'my-app',
  38104. * providers: [DataProvider],
  38105. * template: `
  38106. * Live Update: <input type="checkbox" [(ngModel)]="live">
  38107. * <live-data [live]="live"><live-data>
  38108. * `,
  38109. * })
  38110. * class AppComponent {
  38111. * live = true;
  38112. * }
  38113. * ```
  38114. */
  38115. ViewRef.prototype.reattach = function () { this._lView[FLAGS] |= 128 /* Attached */; };
  38116. /**
  38117. * Checks the view and its children.
  38118. *
  38119. * This can also be used in combination with {@link ChangeDetectorRef#detach detach} to implement
  38120. * local change detection checks.
  38121. *
  38122. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  38123. * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
  38124. *
  38125. * @usageNotes
  38126. * ### Example
  38127. *
  38128. * The following example defines a component with a large list of readonly data.
  38129. * Imagine, the data changes constantly, many times per second. For performance reasons,
  38130. * we want to check and update the list every five seconds.
  38131. *
  38132. * We can do that by detaching the component's change detector and doing a local change detection
  38133. * check every five seconds.
  38134. *
  38135. * See {@link ChangeDetectorRef#detach detach} for more information.
  38136. */
  38137. ViewRef.prototype.detectChanges = function () { detectChangesInternal(this._lView, this.context); };
  38138. /**
  38139. * Checks the change detector and its children, and throws if any changes are detected.
  38140. *
  38141. * This is used in development mode to verify that running change detection doesn't
  38142. * introduce other changes.
  38143. */
  38144. ViewRef.prototype.checkNoChanges = function () { checkNoChangesInternal(this._lView, this.context); };
  38145. ViewRef.prototype.attachToViewContainerRef = function (vcRef) {
  38146. if (this._appRef) {
  38147. throw new Error('This view is already attached directly to the ApplicationRef!');
  38148. }
  38149. this._viewContainerRef = vcRef;
  38150. };
  38151. ViewRef.prototype.detachFromAppRef = function () {
  38152. this._appRef = null;
  38153. renderDetachView(this._lView);
  38154. };
  38155. ViewRef.prototype.attachToAppRef = function (appRef) {
  38156. if (this._viewContainerRef) {
  38157. throw new Error('This view is already attached to a ViewContainer!');
  38158. }
  38159. this._appRef = appRef;
  38160. };
  38161. ViewRef.prototype._lookUpContext = function () {
  38162. return this._context = getLViewParent(this._lView)[this._componentIndex];
  38163. };
  38164. return ViewRef;
  38165. }());
  38166. /** @internal */
  38167. var RootViewRef = /** @class */ (function (_super) {
  38168. __extends(RootViewRef, _super);
  38169. function RootViewRef(_view) {
  38170. var _this = _super.call(this, _view, null, -1) || this;
  38171. _this._view = _view;
  38172. return _this;
  38173. }
  38174. RootViewRef.prototype.detectChanges = function () { detectChangesInRootView(this._view); };
  38175. RootViewRef.prototype.checkNoChanges = function () { checkNoChangesInRootView(this._view); };
  38176. Object.defineProperty(RootViewRef.prototype, "context", {
  38177. get: function () { return null; },
  38178. enumerable: true,
  38179. configurable: true
  38180. });
  38181. return RootViewRef;
  38182. }(ViewRef));
  38183. function collectNativeNodes(lView, parentTNode, result) {
  38184. var tNodeChild = parentTNode.child;
  38185. while (tNodeChild) {
  38186. var nativeNode = getNativeByTNode(tNodeChild, lView);
  38187. nativeNode && result.push(nativeNode);
  38188. if (tNodeChild.type === 4 /* ElementContainer */) {
  38189. collectNativeNodes(lView, tNodeChild, result);
  38190. }
  38191. else if (tNodeChild.type === 1 /* Projection */) {
  38192. var componentView = findComponentView(lView);
  38193. var componentHost = componentView[T_HOST];
  38194. var parentView = getLViewParent(componentView);
  38195. var currentProjectedNode = componentHost.projection[tNodeChild.projection];
  38196. while (currentProjectedNode && parentView) {
  38197. result.push(getNativeByTNode(currentProjectedNode, parentView));
  38198. currentProjectedNode = currentProjectedNode.next;
  38199. }
  38200. }
  38201. tNodeChild = tNodeChild.next;
  38202. }
  38203. return result;
  38204. }
  38205. /**
  38206. * @license
  38207. * Copyright Google Inc. All Rights Reserved.
  38208. *
  38209. * Use of this source code is governed by an MIT-style license that can be
  38210. * found in the LICENSE file at https://angular.io/license
  38211. */
  38212. var R3ElementRef;
  38213. /**
  38214. * Creates an ElementRef given a node.
  38215. *
  38216. * @param ElementRefToken The ElementRef type
  38217. * @param tNode The node for which you'd like an ElementRef
  38218. * @param view The view to which the node belongs
  38219. * @returns The ElementRef instance to use
  38220. */
  38221. function createElementRef(ElementRefToken, tNode, view) {
  38222. if (!R3ElementRef) {
  38223. // TODO: Fix class name, should be ElementRef, but there appears to be a rollup bug
  38224. R3ElementRef = /** @class */ (function (_super) {
  38225. __extends(ElementRef_, _super);
  38226. function ElementRef_() {
  38227. return _super !== null && _super.apply(this, arguments) || this;
  38228. }
  38229. return ElementRef_;
  38230. }(ElementRefToken));
  38231. }
  38232. return new R3ElementRef(getNativeByTNode(tNode, view));
  38233. }
  38234. /**
  38235. * @license
  38236. * Copyright Google Inc. All Rights Reserved.
  38237. *
  38238. * Use of this source code is governed by an MIT-style license that can be
  38239. * found in the LICENSE file at https://angular.io/license
  38240. */
  38241. function noop() {
  38242. var args = [];
  38243. for (var _i = 0; _i < arguments.length; _i++) {
  38244. args[_i] = arguments[_i];
  38245. }
  38246. // Do nothing.
  38247. }
  38248. /**
  38249. * @license
  38250. * Copyright Google Inc. All Rights Reserved.
  38251. *
  38252. * Use of this source code is governed by an MIT-style license that can be
  38253. * found in the LICENSE file at https://angular.io/license
  38254. */
  38255. /**
  38256. * A wrapper around a native element inside of a View.
  38257. *
  38258. * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
  38259. * element.
  38260. *
  38261. * @security Permitting direct access to the DOM can make your application more vulnerable to
  38262. * XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
  38263. * [Security Guide](http://g.co/ng/security).
  38264. *
  38265. * @publicApi
  38266. */
  38267. // Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
  38268. // i.e. users have to ask for what they need. With that, we can build better analysis tools
  38269. // and could do better codegen in the future.
  38270. var ElementRef = /** @class */ (function () {
  38271. function ElementRef(nativeElement) {
  38272. this.nativeElement = nativeElement;
  38273. }
  38274. /**
  38275. * @internal
  38276. * @nocollapse
  38277. */
  38278. ElementRef.__NG_ELEMENT_ID__ = function () { return SWITCH_ELEMENT_REF_FACTORY(ElementRef); };
  38279. return ElementRef;
  38280. }());
  38281. var SWITCH_ELEMENT_REF_FACTORY__PRE_R3__ = noop;
  38282. var SWITCH_ELEMENT_REF_FACTORY = SWITCH_ELEMENT_REF_FACTORY__PRE_R3__;
  38283. /**
  38284. * @license
  38285. * Copyright Google Inc. All Rights Reserved.
  38286. *
  38287. * Use of this source code is governed by an MIT-style license that can be
  38288. * found in the LICENSE file at https://angular.io/license
  38289. */
  38290. /**
  38291. * @deprecated Use the `Renderer2` instead.
  38292. * @publicApi
  38293. */
  38294. var Renderer = /** @class */ (function () {
  38295. function Renderer() {
  38296. }
  38297. return Renderer;
  38298. }());
  38299. var Renderer2Interceptor = new InjectionToken('Renderer2Interceptor');
  38300. /**
  38301. * Creates and initializes a custom renderer that implements the `Renderer2` base class.
  38302. *
  38303. * @publicApi
  38304. */
  38305. var RendererFactory2 = /** @class */ (function () {
  38306. function RendererFactory2() {
  38307. }
  38308. return RendererFactory2;
  38309. }());
  38310. /**
  38311. * Flags for renderer-specific style modifiers.
  38312. * @publicApi
  38313. */
  38314. var RendererStyleFlags2;
  38315. (function (RendererStyleFlags2) {
  38316. /**
  38317. * Marks a style as important.
  38318. */
  38319. RendererStyleFlags2[RendererStyleFlags2["Important"] = 1] = "Important";
  38320. /**
  38321. * Marks a style as using dash case naming (this-is-dash-case).
  38322. */
  38323. RendererStyleFlags2[RendererStyleFlags2["DashCase"] = 2] = "DashCase";
  38324. })(RendererStyleFlags2 || (RendererStyleFlags2 = {}));
  38325. /**
  38326. * Extend this base class to implement custom rendering. By default, Angular
  38327. * renders a template into DOM. You can use custom rendering to intercept
  38328. * rendering calls, or to render to something other than DOM.
  38329. *
  38330. * Create your custom renderer using `RendererFactory2`.
  38331. *
  38332. * Use a custom renderer to bypass Angular's templating and
  38333. * make custom UI changes that can't be expressed declaratively.
  38334. * For example if you need to set a property or an attribute whose name is
  38335. * not statically known, use the `setProperty()` or
  38336. * `setAttribute()` method.
  38337. *
  38338. * @publicApi
  38339. */
  38340. var Renderer2 = /** @class */ (function () {
  38341. function Renderer2() {
  38342. }
  38343. /**
  38344. * @internal
  38345. * @nocollapse
  38346. */
  38347. Renderer2.__NG_ELEMENT_ID__ = function () { return SWITCH_RENDERER2_FACTORY(); };
  38348. return Renderer2;
  38349. }());
  38350. var SWITCH_RENDERER2_FACTORY__PRE_R3__ = noop;
  38351. var SWITCH_RENDERER2_FACTORY = SWITCH_RENDERER2_FACTORY__PRE_R3__;
  38352. /**
  38353. * @license
  38354. * Copyright Google Inc. All Rights Reserved.
  38355. *
  38356. * Use of this source code is governed by an MIT-style license that can be
  38357. * found in the LICENSE file at https://angular.io/license
  38358. */
  38359. /**
  38360. * @description Represents the version of Angular
  38361. *
  38362. * @publicApi
  38363. */
  38364. var Version$1 = /** @class */ (function () {
  38365. function Version(full) {
  38366. this.full = full;
  38367. this.major = full.split('.')[0];
  38368. this.minor = full.split('.')[1];
  38369. this.patch = full.split('.').slice(2).join('.');
  38370. }
  38371. return Version;
  38372. }());
  38373. /**
  38374. * @publicApi
  38375. */
  38376. var VERSION$2 = new Version$1('8.1.3');
  38377. /**
  38378. * @license
  38379. * Copyright Google Inc. All Rights Reserved.
  38380. *
  38381. * Use of this source code is governed by an MIT-style license that can be
  38382. * found in the LICENSE file at https://angular.io/license
  38383. */
  38384. var DefaultIterableDifferFactory = /** @class */ (function () {
  38385. function DefaultIterableDifferFactory() {
  38386. }
  38387. DefaultIterableDifferFactory.prototype.supports = function (obj) { return isListLikeIterable(obj); };
  38388. DefaultIterableDifferFactory.prototype.create = function (trackByFn) {
  38389. return new DefaultIterableDiffer(trackByFn);
  38390. };
  38391. return DefaultIterableDifferFactory;
  38392. }());
  38393. var trackByIdentity = function (index, item) { return item; };
  38394. /**
  38395. * @deprecated v4.0.0 - Should not be part of public API.
  38396. * @publicApi
  38397. */
  38398. var DefaultIterableDiffer = /** @class */ (function () {
  38399. function DefaultIterableDiffer(trackByFn) {
  38400. this.length = 0;
  38401. // Keeps track of the used records at any point in time (during & across `_check()` calls)
  38402. this._linkedRecords = null;
  38403. // Keeps track of the removed records at any point in time during `_check()` calls.
  38404. this._unlinkedRecords = null;
  38405. this._previousItHead = null;
  38406. this._itHead = null;
  38407. this._itTail = null;
  38408. this._additionsHead = null;
  38409. this._additionsTail = null;
  38410. this._movesHead = null;
  38411. this._movesTail = null;
  38412. this._removalsHead = null;
  38413. this._removalsTail = null;
  38414. // Keeps track of records where custom track by is the same, but item identity has changed
  38415. this._identityChangesHead = null;
  38416. this._identityChangesTail = null;
  38417. this._trackByFn = trackByFn || trackByIdentity;
  38418. }
  38419. DefaultIterableDiffer.prototype.forEachItem = function (fn) {
  38420. var record;
  38421. for (record = this._itHead; record !== null; record = record._next) {
  38422. fn(record);
  38423. }
  38424. };
  38425. DefaultIterableDiffer.prototype.forEachOperation = function (fn) {
  38426. var nextIt = this._itHead;
  38427. var nextRemove = this._removalsHead;
  38428. var addRemoveOffset = 0;
  38429. var moveOffsets = null;
  38430. while (nextIt || nextRemove) {
  38431. // Figure out which is the next record to process
  38432. // Order: remove, add, move
  38433. var record = !nextRemove ||
  38434. nextIt &&
  38435. nextIt.currentIndex <
  38436. getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ?
  38437. nextIt :
  38438. nextRemove;
  38439. var adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
  38440. var currentIndex = record.currentIndex;
  38441. // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
  38442. if (record === nextRemove) {
  38443. addRemoveOffset--;
  38444. nextRemove = nextRemove._nextRemoved;
  38445. }
  38446. else {
  38447. nextIt = nextIt._next;
  38448. if (record.previousIndex == null) {
  38449. addRemoveOffset++;
  38450. }
  38451. else {
  38452. // INVARIANT: currentIndex < previousIndex
  38453. if (!moveOffsets)
  38454. moveOffsets = [];
  38455. var localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
  38456. var localCurrentIndex = currentIndex - addRemoveOffset;
  38457. if (localMovePreviousIndex != localCurrentIndex) {
  38458. for (var i = 0; i < localMovePreviousIndex; i++) {
  38459. var offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0);
  38460. var index = offset + i;
  38461. if (localCurrentIndex <= index && index < localMovePreviousIndex) {
  38462. moveOffsets[i] = offset + 1;
  38463. }
  38464. }
  38465. var previousIndex = record.previousIndex;
  38466. moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
  38467. }
  38468. }
  38469. }
  38470. if (adjPreviousIndex !== currentIndex) {
  38471. fn(record, adjPreviousIndex, currentIndex);
  38472. }
  38473. }
  38474. };
  38475. DefaultIterableDiffer.prototype.forEachPreviousItem = function (fn) {
  38476. var record;
  38477. for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
  38478. fn(record);
  38479. }
  38480. };
  38481. DefaultIterableDiffer.prototype.forEachAddedItem = function (fn) {
  38482. var record;
  38483. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  38484. fn(record);
  38485. }
  38486. };
  38487. DefaultIterableDiffer.prototype.forEachMovedItem = function (fn) {
  38488. var record;
  38489. for (record = this._movesHead; record !== null; record = record._nextMoved) {
  38490. fn(record);
  38491. }
  38492. };
  38493. DefaultIterableDiffer.prototype.forEachRemovedItem = function (fn) {
  38494. var record;
  38495. for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
  38496. fn(record);
  38497. }
  38498. };
  38499. DefaultIterableDiffer.prototype.forEachIdentityChange = function (fn) {
  38500. var record;
  38501. for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
  38502. fn(record);
  38503. }
  38504. };
  38505. DefaultIterableDiffer.prototype.diff = function (collection) {
  38506. if (collection == null)
  38507. collection = [];
  38508. if (!isListLikeIterable(collection)) {
  38509. throw new Error("Error trying to diff '" + stringify$1(collection) + "'. Only arrays and iterables are allowed");
  38510. }
  38511. if (this.check(collection)) {
  38512. return this;
  38513. }
  38514. else {
  38515. return null;
  38516. }
  38517. };
  38518. DefaultIterableDiffer.prototype.onDestroy = function () { };
  38519. DefaultIterableDiffer.prototype.check = function (collection) {
  38520. var _this = this;
  38521. this._reset();
  38522. var record = this._itHead;
  38523. var mayBeDirty = false;
  38524. var index;
  38525. var item;
  38526. var itemTrackBy;
  38527. if (Array.isArray(collection)) {
  38528. this.length = collection.length;
  38529. for (var index_1 = 0; index_1 < this.length; index_1++) {
  38530. item = collection[index_1];
  38531. itemTrackBy = this._trackByFn(index_1, item);
  38532. if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
  38533. record = this._mismatch(record, item, itemTrackBy, index_1);
  38534. mayBeDirty = true;
  38535. }
  38536. else {
  38537. if (mayBeDirty) {
  38538. // TODO(misko): can we limit this to duplicates only?
  38539. record = this._verifyReinsertion(record, item, itemTrackBy, index_1);
  38540. }
  38541. if (!looseIdentical(record.item, item))
  38542. this._addIdentityChange(record, item);
  38543. }
  38544. record = record._next;
  38545. }
  38546. }
  38547. else {
  38548. index = 0;
  38549. iterateListLike(collection, function (item) {
  38550. itemTrackBy = _this._trackByFn(index, item);
  38551. if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
  38552. record = _this._mismatch(record, item, itemTrackBy, index);
  38553. mayBeDirty = true;
  38554. }
  38555. else {
  38556. if (mayBeDirty) {
  38557. // TODO(misko): can we limit this to duplicates only?
  38558. record = _this._verifyReinsertion(record, item, itemTrackBy, index);
  38559. }
  38560. if (!looseIdentical(record.item, item))
  38561. _this._addIdentityChange(record, item);
  38562. }
  38563. record = record._next;
  38564. index++;
  38565. });
  38566. this.length = index;
  38567. }
  38568. this._truncate(record);
  38569. this.collection = collection;
  38570. return this.isDirty;
  38571. };
  38572. Object.defineProperty(DefaultIterableDiffer.prototype, "isDirty", {
  38573. /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity
  38574. * changes.
  38575. */
  38576. get: function () {
  38577. return this._additionsHead !== null || this._movesHead !== null ||
  38578. this._removalsHead !== null || this._identityChangesHead !== null;
  38579. },
  38580. enumerable: true,
  38581. configurable: true
  38582. });
  38583. /**
  38584. * Reset the state of the change objects to show no changes. This means set previousKey to
  38585. * currentKey, and clear all of the queues (additions, moves, removals).
  38586. * Set the previousIndexes of moved and added items to their currentIndexes
  38587. * Reset the list of additions, moves and removals
  38588. *
  38589. * @internal
  38590. */
  38591. DefaultIterableDiffer.prototype._reset = function () {
  38592. if (this.isDirty) {
  38593. var record = void 0;
  38594. var nextRecord = void 0;
  38595. for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
  38596. record._nextPrevious = record._next;
  38597. }
  38598. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  38599. record.previousIndex = record.currentIndex;
  38600. }
  38601. this._additionsHead = this._additionsTail = null;
  38602. for (record = this._movesHead; record !== null; record = nextRecord) {
  38603. record.previousIndex = record.currentIndex;
  38604. nextRecord = record._nextMoved;
  38605. }
  38606. this._movesHead = this._movesTail = null;
  38607. this._removalsHead = this._removalsTail = null;
  38608. this._identityChangesHead = this._identityChangesTail = null;
  38609. // TODO(vicb): when assert gets supported
  38610. // assert(!this.isDirty);
  38611. }
  38612. };
  38613. /**
  38614. * This is the core function which handles differences between collections.
  38615. *
  38616. * - `record` is the record which we saw at this position last time. If null then it is a new
  38617. * item.
  38618. * - `item` is the current item in the collection
  38619. * - `index` is the position of the item in the collection
  38620. *
  38621. * @internal
  38622. */
  38623. DefaultIterableDiffer.prototype._mismatch = function (record, item, itemTrackBy, index) {
  38624. // The previous record after which we will append the current one.
  38625. var previousRecord;
  38626. if (record === null) {
  38627. previousRecord = this._itTail;
  38628. }
  38629. else {
  38630. previousRecord = record._prev;
  38631. // Remove the record from the collection since we know it does not match the item.
  38632. this._remove(record);
  38633. }
  38634. // Attempt to see if we have seen the item before.
  38635. record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
  38636. if (record !== null) {
  38637. // We have seen this before, we need to move it forward in the collection.
  38638. // But first we need to check if identity changed, so we can update in view if necessary
  38639. if (!looseIdentical(record.item, item))
  38640. this._addIdentityChange(record, item);
  38641. this._moveAfter(record, previousRecord, index);
  38642. }
  38643. else {
  38644. // Never seen it, check evicted list.
  38645. record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
  38646. if (record !== null) {
  38647. // It is an item which we have evicted earlier: reinsert it back into the list.
  38648. // But first we need to check if identity changed, so we can update in view if necessary
  38649. if (!looseIdentical(record.item, item))
  38650. this._addIdentityChange(record, item);
  38651. this._reinsertAfter(record, previousRecord, index);
  38652. }
  38653. else {
  38654. // It is a new item: add it.
  38655. record =
  38656. this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
  38657. }
  38658. }
  38659. return record;
  38660. };
  38661. /**
  38662. * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
  38663. *
  38664. * Use case: `[a, a]` => `[b, a, a]`
  38665. *
  38666. * If we did not have this check then the insertion of `b` would:
  38667. * 1) evict first `a`
  38668. * 2) insert `b` at `0` index.
  38669. * 3) leave `a` at index `1` as is. <-- this is wrong!
  38670. * 3) reinsert `a` at index 2. <-- this is wrong!
  38671. *
  38672. * The correct behavior is:
  38673. * 1) evict first `a`
  38674. * 2) insert `b` at `0` index.
  38675. * 3) reinsert `a` at index 1.
  38676. * 3) move `a` at from `1` to `2`.
  38677. *
  38678. *
  38679. * Double check that we have not evicted a duplicate item. We need to check if the item type may
  38680. * have already been removed:
  38681. * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
  38682. * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
  38683. * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
  38684. * at the end.
  38685. *
  38686. * @internal
  38687. */
  38688. DefaultIterableDiffer.prototype._verifyReinsertion = function (record, item, itemTrackBy, index) {
  38689. var reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
  38690. if (reinsertRecord !== null) {
  38691. record = this._reinsertAfter(reinsertRecord, record._prev, index);
  38692. }
  38693. else if (record.currentIndex != index) {
  38694. record.currentIndex = index;
  38695. this._addToMoves(record, index);
  38696. }
  38697. return record;
  38698. };
  38699. /**
  38700. * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection
  38701. *
  38702. * - `record` The first excess {@link IterableChangeRecord_}.
  38703. *
  38704. * @internal
  38705. */
  38706. DefaultIterableDiffer.prototype._truncate = function (record) {
  38707. // Anything after that needs to be removed;
  38708. while (record !== null) {
  38709. var nextRecord = record._next;
  38710. this._addToRemovals(this._unlink(record));
  38711. record = nextRecord;
  38712. }
  38713. if (this._unlinkedRecords !== null) {
  38714. this._unlinkedRecords.clear();
  38715. }
  38716. if (this._additionsTail !== null) {
  38717. this._additionsTail._nextAdded = null;
  38718. }
  38719. if (this._movesTail !== null) {
  38720. this._movesTail._nextMoved = null;
  38721. }
  38722. if (this._itTail !== null) {
  38723. this._itTail._next = null;
  38724. }
  38725. if (this._removalsTail !== null) {
  38726. this._removalsTail._nextRemoved = null;
  38727. }
  38728. if (this._identityChangesTail !== null) {
  38729. this._identityChangesTail._nextIdentityChange = null;
  38730. }
  38731. };
  38732. /** @internal */
  38733. DefaultIterableDiffer.prototype._reinsertAfter = function (record, prevRecord, index) {
  38734. if (this._unlinkedRecords !== null) {
  38735. this._unlinkedRecords.remove(record);
  38736. }
  38737. var prev = record._prevRemoved;
  38738. var next = record._nextRemoved;
  38739. if (prev === null) {
  38740. this._removalsHead = next;
  38741. }
  38742. else {
  38743. prev._nextRemoved = next;
  38744. }
  38745. if (next === null) {
  38746. this._removalsTail = prev;
  38747. }
  38748. else {
  38749. next._prevRemoved = prev;
  38750. }
  38751. this._insertAfter(record, prevRecord, index);
  38752. this._addToMoves(record, index);
  38753. return record;
  38754. };
  38755. /** @internal */
  38756. DefaultIterableDiffer.prototype._moveAfter = function (record, prevRecord, index) {
  38757. this._unlink(record);
  38758. this._insertAfter(record, prevRecord, index);
  38759. this._addToMoves(record, index);
  38760. return record;
  38761. };
  38762. /** @internal */
  38763. DefaultIterableDiffer.prototype._addAfter = function (record, prevRecord, index) {
  38764. this._insertAfter(record, prevRecord, index);
  38765. if (this._additionsTail === null) {
  38766. // TODO(vicb):
  38767. // assert(this._additionsHead === null);
  38768. this._additionsTail = this._additionsHead = record;
  38769. }
  38770. else {
  38771. // TODO(vicb):
  38772. // assert(_additionsTail._nextAdded === null);
  38773. // assert(record._nextAdded === null);
  38774. this._additionsTail = this._additionsTail._nextAdded = record;
  38775. }
  38776. return record;
  38777. };
  38778. /** @internal */
  38779. DefaultIterableDiffer.prototype._insertAfter = function (record, prevRecord, index) {
  38780. // TODO(vicb):
  38781. // assert(record != prevRecord);
  38782. // assert(record._next === null);
  38783. // assert(record._prev === null);
  38784. var next = prevRecord === null ? this._itHead : prevRecord._next;
  38785. // TODO(vicb):
  38786. // assert(next != record);
  38787. // assert(prevRecord != record);
  38788. record._next = next;
  38789. record._prev = prevRecord;
  38790. if (next === null) {
  38791. this._itTail = record;
  38792. }
  38793. else {
  38794. next._prev = record;
  38795. }
  38796. if (prevRecord === null) {
  38797. this._itHead = record;
  38798. }
  38799. else {
  38800. prevRecord._next = record;
  38801. }
  38802. if (this._linkedRecords === null) {
  38803. this._linkedRecords = new _DuplicateMap();
  38804. }
  38805. this._linkedRecords.put(record);
  38806. record.currentIndex = index;
  38807. return record;
  38808. };
  38809. /** @internal */
  38810. DefaultIterableDiffer.prototype._remove = function (record) {
  38811. return this._addToRemovals(this._unlink(record));
  38812. };
  38813. /** @internal */
  38814. DefaultIterableDiffer.prototype._unlink = function (record) {
  38815. if (this._linkedRecords !== null) {
  38816. this._linkedRecords.remove(record);
  38817. }
  38818. var prev = record._prev;
  38819. var next = record._next;
  38820. // TODO(vicb):
  38821. // assert((record._prev = null) === null);
  38822. // assert((record._next = null) === null);
  38823. if (prev === null) {
  38824. this._itHead = next;
  38825. }
  38826. else {
  38827. prev._next = next;
  38828. }
  38829. if (next === null) {
  38830. this._itTail = prev;
  38831. }
  38832. else {
  38833. next._prev = prev;
  38834. }
  38835. return record;
  38836. };
  38837. /** @internal */
  38838. DefaultIterableDiffer.prototype._addToMoves = function (record, toIndex) {
  38839. // TODO(vicb):
  38840. // assert(record._nextMoved === null);
  38841. if (record.previousIndex === toIndex) {
  38842. return record;
  38843. }
  38844. if (this._movesTail === null) {
  38845. // TODO(vicb):
  38846. // assert(_movesHead === null);
  38847. this._movesTail = this._movesHead = record;
  38848. }
  38849. else {
  38850. // TODO(vicb):
  38851. // assert(_movesTail._nextMoved === null);
  38852. this._movesTail = this._movesTail._nextMoved = record;
  38853. }
  38854. return record;
  38855. };
  38856. DefaultIterableDiffer.prototype._addToRemovals = function (record) {
  38857. if (this._unlinkedRecords === null) {
  38858. this._unlinkedRecords = new _DuplicateMap();
  38859. }
  38860. this._unlinkedRecords.put(record);
  38861. record.currentIndex = null;
  38862. record._nextRemoved = null;
  38863. if (this._removalsTail === null) {
  38864. // TODO(vicb):
  38865. // assert(_removalsHead === null);
  38866. this._removalsTail = this._removalsHead = record;
  38867. record._prevRemoved = null;
  38868. }
  38869. else {
  38870. // TODO(vicb):
  38871. // assert(_removalsTail._nextRemoved === null);
  38872. // assert(record._nextRemoved === null);
  38873. record._prevRemoved = this._removalsTail;
  38874. this._removalsTail = this._removalsTail._nextRemoved = record;
  38875. }
  38876. return record;
  38877. };
  38878. /** @internal */
  38879. DefaultIterableDiffer.prototype._addIdentityChange = function (record, item) {
  38880. record.item = item;
  38881. if (this._identityChangesTail === null) {
  38882. this._identityChangesTail = this._identityChangesHead = record;
  38883. }
  38884. else {
  38885. this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
  38886. }
  38887. return record;
  38888. };
  38889. return DefaultIterableDiffer;
  38890. }());
  38891. var IterableChangeRecord_ = /** @class */ (function () {
  38892. function IterableChangeRecord_(item, trackById) {
  38893. this.item = item;
  38894. this.trackById = trackById;
  38895. this.currentIndex = null;
  38896. this.previousIndex = null;
  38897. /** @internal */
  38898. this._nextPrevious = null;
  38899. /** @internal */
  38900. this._prev = null;
  38901. /** @internal */
  38902. this._next = null;
  38903. /** @internal */
  38904. this._prevDup = null;
  38905. /** @internal */
  38906. this._nextDup = null;
  38907. /** @internal */
  38908. this._prevRemoved = null;
  38909. /** @internal */
  38910. this._nextRemoved = null;
  38911. /** @internal */
  38912. this._nextAdded = null;
  38913. /** @internal */
  38914. this._nextMoved = null;
  38915. /** @internal */
  38916. this._nextIdentityChange = null;
  38917. }
  38918. return IterableChangeRecord_;
  38919. }());
  38920. // A linked list of CollectionChangeRecords with the same IterableChangeRecord_.item
  38921. var _DuplicateItemRecordList = /** @class */ (function () {
  38922. function _DuplicateItemRecordList() {
  38923. /** @internal */
  38924. this._head = null;
  38925. /** @internal */
  38926. this._tail = null;
  38927. }
  38928. /**
  38929. * Append the record to the list of duplicates.
  38930. *
  38931. * Note: by design all records in the list of duplicates hold the same value in record.item.
  38932. */
  38933. _DuplicateItemRecordList.prototype.add = function (record) {
  38934. if (this._head === null) {
  38935. this._head = this._tail = record;
  38936. record._nextDup = null;
  38937. record._prevDup = null;
  38938. }
  38939. else {
  38940. // TODO(vicb):
  38941. // assert(record.item == _head.item ||
  38942. // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
  38943. this._tail._nextDup = record;
  38944. record._prevDup = this._tail;
  38945. record._nextDup = null;
  38946. this._tail = record;
  38947. }
  38948. };
  38949. // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and
  38950. // IterableChangeRecord_.currentIndex >= atOrAfterIndex
  38951. _DuplicateItemRecordList.prototype.get = function (trackById, atOrAfterIndex) {
  38952. var record;
  38953. for (record = this._head; record !== null; record = record._nextDup) {
  38954. if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex) &&
  38955. looseIdentical(record.trackById, trackById)) {
  38956. return record;
  38957. }
  38958. }
  38959. return null;
  38960. };
  38961. /**
  38962. * Remove one {@link IterableChangeRecord_} from the list of duplicates.
  38963. *
  38964. * Returns whether the list of duplicates is empty.
  38965. */
  38966. _DuplicateItemRecordList.prototype.remove = function (record) {
  38967. // TODO(vicb):
  38968. // assert(() {
  38969. // // verify that the record being removed is in the list.
  38970. // for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
  38971. // if (identical(cursor, record)) return true;
  38972. // }
  38973. // return false;
  38974. //});
  38975. var prev = record._prevDup;
  38976. var next = record._nextDup;
  38977. if (prev === null) {
  38978. this._head = next;
  38979. }
  38980. else {
  38981. prev._nextDup = next;
  38982. }
  38983. if (next === null) {
  38984. this._tail = prev;
  38985. }
  38986. else {
  38987. next._prevDup = prev;
  38988. }
  38989. return this._head === null;
  38990. };
  38991. return _DuplicateItemRecordList;
  38992. }());
  38993. var _DuplicateMap = /** @class */ (function () {
  38994. function _DuplicateMap() {
  38995. this.map = new Map();
  38996. }
  38997. _DuplicateMap.prototype.put = function (record) {
  38998. var key = record.trackById;
  38999. var duplicates = this.map.get(key);
  39000. if (!duplicates) {
  39001. duplicates = new _DuplicateItemRecordList();
  39002. this.map.set(key, duplicates);
  39003. }
  39004. duplicates.add(record);
  39005. };
  39006. /**
  39007. * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
  39008. * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there.
  39009. *
  39010. * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
  39011. * have any more `a`s needs to return the second `a`.
  39012. */
  39013. _DuplicateMap.prototype.get = function (trackById, atOrAfterIndex) {
  39014. var key = trackById;
  39015. var recordList = this.map.get(key);
  39016. return recordList ? recordList.get(trackById, atOrAfterIndex) : null;
  39017. };
  39018. /**
  39019. * Removes a {@link IterableChangeRecord_} from the list of duplicates.
  39020. *
  39021. * The list of duplicates also is removed from the map if it gets empty.
  39022. */
  39023. _DuplicateMap.prototype.remove = function (record) {
  39024. var key = record.trackById;
  39025. var recordList = this.map.get(key);
  39026. // Remove the list of duplicates when it gets empty
  39027. if (recordList.remove(record)) {
  39028. this.map.delete(key);
  39029. }
  39030. return record;
  39031. };
  39032. Object.defineProperty(_DuplicateMap.prototype, "isEmpty", {
  39033. get: function () { return this.map.size === 0; },
  39034. enumerable: true,
  39035. configurable: true
  39036. });
  39037. _DuplicateMap.prototype.clear = function () { this.map.clear(); };
  39038. return _DuplicateMap;
  39039. }());
  39040. function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
  39041. var previousIndex = item.previousIndex;
  39042. if (previousIndex === null)
  39043. return previousIndex;
  39044. var moveOffset = 0;
  39045. if (moveOffsets && previousIndex < moveOffsets.length) {
  39046. moveOffset = moveOffsets[previousIndex];
  39047. }
  39048. return previousIndex + addRemoveOffset + moveOffset;
  39049. }
  39050. /**
  39051. * @license
  39052. * Copyright Google Inc. All Rights Reserved.
  39053. *
  39054. * Use of this source code is governed by an MIT-style license that can be
  39055. * found in the LICENSE file at https://angular.io/license
  39056. */
  39057. var DefaultKeyValueDifferFactory = /** @class */ (function () {
  39058. function DefaultKeyValueDifferFactory() {
  39059. }
  39060. DefaultKeyValueDifferFactory.prototype.supports = function (obj) { return obj instanceof Map || isJsObject(obj); };
  39061. DefaultKeyValueDifferFactory.prototype.create = function () { return new DefaultKeyValueDiffer(); };
  39062. return DefaultKeyValueDifferFactory;
  39063. }());
  39064. var DefaultKeyValueDiffer = /** @class */ (function () {
  39065. function DefaultKeyValueDiffer() {
  39066. this._records = new Map();
  39067. this._mapHead = null;
  39068. // _appendAfter is used in the check loop
  39069. this._appendAfter = null;
  39070. this._previousMapHead = null;
  39071. this._changesHead = null;
  39072. this._changesTail = null;
  39073. this._additionsHead = null;
  39074. this._additionsTail = null;
  39075. this._removalsHead = null;
  39076. this._removalsTail = null;
  39077. }
  39078. Object.defineProperty(DefaultKeyValueDiffer.prototype, "isDirty", {
  39079. get: function () {
  39080. return this._additionsHead !== null || this._changesHead !== null ||
  39081. this._removalsHead !== null;
  39082. },
  39083. enumerable: true,
  39084. configurable: true
  39085. });
  39086. DefaultKeyValueDiffer.prototype.forEachItem = function (fn) {
  39087. var record;
  39088. for (record = this._mapHead; record !== null; record = record._next) {
  39089. fn(record);
  39090. }
  39091. };
  39092. DefaultKeyValueDiffer.prototype.forEachPreviousItem = function (fn) {
  39093. var record;
  39094. for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
  39095. fn(record);
  39096. }
  39097. };
  39098. DefaultKeyValueDiffer.prototype.forEachChangedItem = function (fn) {
  39099. var record;
  39100. for (record = this._changesHead; record !== null; record = record._nextChanged) {
  39101. fn(record);
  39102. }
  39103. };
  39104. DefaultKeyValueDiffer.prototype.forEachAddedItem = function (fn) {
  39105. var record;
  39106. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  39107. fn(record);
  39108. }
  39109. };
  39110. DefaultKeyValueDiffer.prototype.forEachRemovedItem = function (fn) {
  39111. var record;
  39112. for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
  39113. fn(record);
  39114. }
  39115. };
  39116. DefaultKeyValueDiffer.prototype.diff = function (map) {
  39117. if (!map) {
  39118. map = new Map();
  39119. }
  39120. else if (!(map instanceof Map || isJsObject(map))) {
  39121. throw new Error("Error trying to diff '" + stringify$1(map) + "'. Only maps and objects are allowed");
  39122. }
  39123. return this.check(map) ? this : null;
  39124. };
  39125. DefaultKeyValueDiffer.prototype.onDestroy = function () { };
  39126. /**
  39127. * Check the current state of the map vs the previous.
  39128. * The algorithm is optimised for when the keys do no change.
  39129. */
  39130. DefaultKeyValueDiffer.prototype.check = function (map) {
  39131. var _this = this;
  39132. this._reset();
  39133. var insertBefore = this._mapHead;
  39134. this._appendAfter = null;
  39135. this._forEach(map, function (value, key) {
  39136. if (insertBefore && insertBefore.key === key) {
  39137. _this._maybeAddToChanges(insertBefore, value);
  39138. _this._appendAfter = insertBefore;
  39139. insertBefore = insertBefore._next;
  39140. }
  39141. else {
  39142. var record = _this._getOrCreateRecordForKey(key, value);
  39143. insertBefore = _this._insertBeforeOrAppend(insertBefore, record);
  39144. }
  39145. });
  39146. // Items remaining at the end of the list have been deleted
  39147. if (insertBefore) {
  39148. if (insertBefore._prev) {
  39149. insertBefore._prev._next = null;
  39150. }
  39151. this._removalsHead = insertBefore;
  39152. for (var record = insertBefore; record !== null; record = record._nextRemoved) {
  39153. if (record === this._mapHead) {
  39154. this._mapHead = null;
  39155. }
  39156. this._records.delete(record.key);
  39157. record._nextRemoved = record._next;
  39158. record.previousValue = record.currentValue;
  39159. record.currentValue = null;
  39160. record._prev = null;
  39161. record._next = null;
  39162. }
  39163. }
  39164. // Make sure tails have no next records from previous runs
  39165. if (this._changesTail)
  39166. this._changesTail._nextChanged = null;
  39167. if (this._additionsTail)
  39168. this._additionsTail._nextAdded = null;
  39169. return this.isDirty;
  39170. };
  39171. /**
  39172. * Inserts a record before `before` or append at the end of the list when `before` is null.
  39173. *
  39174. * Notes:
  39175. * - This method appends at `this._appendAfter`,
  39176. * - This method updates `this._appendAfter`,
  39177. * - The return value is the new value for the insertion pointer.
  39178. */
  39179. DefaultKeyValueDiffer.prototype._insertBeforeOrAppend = function (before, record) {
  39180. if (before) {
  39181. var prev = before._prev;
  39182. record._next = before;
  39183. record._prev = prev;
  39184. before._prev = record;
  39185. if (prev) {
  39186. prev._next = record;
  39187. }
  39188. if (before === this._mapHead) {
  39189. this._mapHead = record;
  39190. }
  39191. this._appendAfter = before;
  39192. return before;
  39193. }
  39194. if (this._appendAfter) {
  39195. this._appendAfter._next = record;
  39196. record._prev = this._appendAfter;
  39197. }
  39198. else {
  39199. this._mapHead = record;
  39200. }
  39201. this._appendAfter = record;
  39202. return null;
  39203. };
  39204. DefaultKeyValueDiffer.prototype._getOrCreateRecordForKey = function (key, value) {
  39205. if (this._records.has(key)) {
  39206. var record_1 = this._records.get(key);
  39207. this._maybeAddToChanges(record_1, value);
  39208. var prev = record_1._prev;
  39209. var next = record_1._next;
  39210. if (prev) {
  39211. prev._next = next;
  39212. }
  39213. if (next) {
  39214. next._prev = prev;
  39215. }
  39216. record_1._next = null;
  39217. record_1._prev = null;
  39218. return record_1;
  39219. }
  39220. var record = new KeyValueChangeRecord_(key);
  39221. this._records.set(key, record);
  39222. record.currentValue = value;
  39223. this._addToAdditions(record);
  39224. return record;
  39225. };
  39226. /** @internal */
  39227. DefaultKeyValueDiffer.prototype._reset = function () {
  39228. if (this.isDirty) {
  39229. var record = void 0;
  39230. // let `_previousMapHead` contain the state of the map before the changes
  39231. this._previousMapHead = this._mapHead;
  39232. for (record = this._previousMapHead; record !== null; record = record._next) {
  39233. record._nextPrevious = record._next;
  39234. }
  39235. // Update `record.previousValue` with the value of the item before the changes
  39236. // We need to update all changed items (that's those which have been added and changed)
  39237. for (record = this._changesHead; record !== null; record = record._nextChanged) {
  39238. record.previousValue = record.currentValue;
  39239. }
  39240. for (record = this._additionsHead; record != null; record = record._nextAdded) {
  39241. record.previousValue = record.currentValue;
  39242. }
  39243. this._changesHead = this._changesTail = null;
  39244. this._additionsHead = this._additionsTail = null;
  39245. this._removalsHead = null;
  39246. }
  39247. };
  39248. // Add the record or a given key to the list of changes only when the value has actually changed
  39249. DefaultKeyValueDiffer.prototype._maybeAddToChanges = function (record, newValue) {
  39250. if (!looseIdentical(newValue, record.currentValue)) {
  39251. record.previousValue = record.currentValue;
  39252. record.currentValue = newValue;
  39253. this._addToChanges(record);
  39254. }
  39255. };
  39256. DefaultKeyValueDiffer.prototype._addToAdditions = function (record) {
  39257. if (this._additionsHead === null) {
  39258. this._additionsHead = this._additionsTail = record;
  39259. }
  39260. else {
  39261. this._additionsTail._nextAdded = record;
  39262. this._additionsTail = record;
  39263. }
  39264. };
  39265. DefaultKeyValueDiffer.prototype._addToChanges = function (record) {
  39266. if (this._changesHead === null) {
  39267. this._changesHead = this._changesTail = record;
  39268. }
  39269. else {
  39270. this._changesTail._nextChanged = record;
  39271. this._changesTail = record;
  39272. }
  39273. };
  39274. /** @internal */
  39275. DefaultKeyValueDiffer.prototype._forEach = function (obj, fn) {
  39276. if (obj instanceof Map) {
  39277. obj.forEach(fn);
  39278. }
  39279. else {
  39280. Object.keys(obj).forEach(function (k) { return fn(obj[k], k); });
  39281. }
  39282. };
  39283. return DefaultKeyValueDiffer;
  39284. }());
  39285. var KeyValueChangeRecord_ = /** @class */ (function () {
  39286. function KeyValueChangeRecord_(key) {
  39287. this.key = key;
  39288. this.previousValue = null;
  39289. this.currentValue = null;
  39290. /** @internal */
  39291. this._nextPrevious = null;
  39292. /** @internal */
  39293. this._next = null;
  39294. /** @internal */
  39295. this._prev = null;
  39296. /** @internal */
  39297. this._nextAdded = null;
  39298. /** @internal */
  39299. this._nextRemoved = null;
  39300. /** @internal */
  39301. this._nextChanged = null;
  39302. }
  39303. return KeyValueChangeRecord_;
  39304. }());
  39305. /**
  39306. * @license
  39307. * Copyright Google Inc. All Rights Reserved.
  39308. *
  39309. * Use of this source code is governed by an MIT-style license that can be
  39310. * found in the LICENSE file at https://angular.io/license
  39311. */
  39312. /**
  39313. * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
  39314. *
  39315. * @publicApi
  39316. */
  39317. var IterableDiffers = /** @class */ (function () {
  39318. function IterableDiffers(factories) {
  39319. this.factories = factories;
  39320. }
  39321. IterableDiffers.create = function (factories, parent) {
  39322. if (parent != null) {
  39323. var copied = parent.factories.slice();
  39324. factories = factories.concat(copied);
  39325. }
  39326. return new IterableDiffers(factories);
  39327. };
  39328. /**
  39329. * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
  39330. * inherited {@link IterableDiffers} instance with the provided factories and return a new
  39331. * {@link IterableDiffers} instance.
  39332. *
  39333. * @usageNotes
  39334. * ### Example
  39335. *
  39336. * The following example shows how to extend an existing list of factories,
  39337. * which will only be applied to the injector for this component and its children.
  39338. * This step is all that's required to make a new {@link IterableDiffer} available.
  39339. *
  39340. * ```
  39341. * @Component({
  39342. * viewProviders: [
  39343. * IterableDiffers.extend([new ImmutableListDiffer()])
  39344. * ]
  39345. * })
  39346. * ```
  39347. */
  39348. IterableDiffers.extend = function (factories) {
  39349. return {
  39350. provide: IterableDiffers,
  39351. useFactory: function (parent) {
  39352. if (!parent) {
  39353. // Typically would occur when calling IterableDiffers.extend inside of dependencies passed
  39354. // to
  39355. // bootstrap(), which would override default pipes instead of extending them.
  39356. throw new Error('Cannot extend IterableDiffers without a parent injector');
  39357. }
  39358. return IterableDiffers.create(factories, parent);
  39359. },
  39360. // Dependency technically isn't optional, but we can provide a better error message this way.
  39361. deps: [[IterableDiffers, new SkipSelf(), new Optional()]]
  39362. };
  39363. };
  39364. IterableDiffers.prototype.find = function (iterable) {
  39365. var factory = this.factories.find(function (f) { return f.supports(iterable); });
  39366. if (factory != null) {
  39367. return factory;
  39368. }
  39369. else {
  39370. throw new Error("Cannot find a differ supporting object '" + iterable + "' of type '" + getTypeNameForDebugging(iterable) + "'");
  39371. }
  39372. };
  39373. /** @nocollapse */
  39374. IterableDiffers.ngInjectableDef = ɵɵdefineInjectable({
  39375. token: IterableDiffers,
  39376. providedIn: 'root',
  39377. factory: function () { return new IterableDiffers([new DefaultIterableDifferFactory()]); }
  39378. });
  39379. return IterableDiffers;
  39380. }());
  39381. function getTypeNameForDebugging(type) {
  39382. return type['name'] || typeof type;
  39383. }
  39384. /**
  39385. * @license
  39386. * Copyright Google Inc. All Rights Reserved.
  39387. *
  39388. * Use of this source code is governed by an MIT-style license that can be
  39389. * found in the LICENSE file at https://angular.io/license
  39390. */
  39391. /**
  39392. * A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
  39393. *
  39394. * @publicApi
  39395. */
  39396. var KeyValueDiffers = /** @class */ (function () {
  39397. function KeyValueDiffers(factories) {
  39398. this.factories = factories;
  39399. }
  39400. KeyValueDiffers.create = function (factories, parent) {
  39401. if (parent) {
  39402. var copied = parent.factories.slice();
  39403. factories = factories.concat(copied);
  39404. }
  39405. return new KeyValueDiffers(factories);
  39406. };
  39407. /**
  39408. * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
  39409. * inherited {@link KeyValueDiffers} instance with the provided factories and return a new
  39410. * {@link KeyValueDiffers} instance.
  39411. *
  39412. * @usageNotes
  39413. * ### Example
  39414. *
  39415. * The following example shows how to extend an existing list of factories,
  39416. * which will only be applied to the injector for this component and its children.
  39417. * This step is all that's required to make a new {@link KeyValueDiffer} available.
  39418. *
  39419. * ```
  39420. * @Component({
  39421. * viewProviders: [
  39422. * KeyValueDiffers.extend([new ImmutableMapDiffer()])
  39423. * ]
  39424. * })
  39425. * ```
  39426. */
  39427. KeyValueDiffers.extend = function (factories) {
  39428. return {
  39429. provide: KeyValueDiffers,
  39430. useFactory: function (parent) {
  39431. if (!parent) {
  39432. // Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
  39433. // to bootstrap(), which would override default pipes instead of extending them.
  39434. throw new Error('Cannot extend KeyValueDiffers without a parent injector');
  39435. }
  39436. return KeyValueDiffers.create(factories, parent);
  39437. },
  39438. // Dependency technically isn't optional, but we can provide a better error message this way.
  39439. deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]]
  39440. };
  39441. };
  39442. KeyValueDiffers.prototype.find = function (kv) {
  39443. var factory = this.factories.find(function (f) { return f.supports(kv); });
  39444. if (factory) {
  39445. return factory;
  39446. }
  39447. throw new Error("Cannot find a differ supporting object '" + kv + "'");
  39448. };
  39449. /** @nocollapse */
  39450. KeyValueDiffers.ngInjectableDef = ɵɵdefineInjectable({
  39451. token: KeyValueDiffers,
  39452. providedIn: 'root',
  39453. factory: function () { return new KeyValueDiffers([new DefaultKeyValueDifferFactory()]); }
  39454. });
  39455. return KeyValueDiffers;
  39456. }());
  39457. /**
  39458. * @license
  39459. * Copyright Google Inc. All Rights Reserved.
  39460. *
  39461. * Use of this source code is governed by an MIT-style license that can be
  39462. * found in the LICENSE file at https://angular.io/license
  39463. */
  39464. /**
  39465. * Base class for Angular Views, provides change detection functionality.
  39466. * A change-detection tree collects all views that are to be checked for changes.
  39467. * Use the methods to add and remove views from the tree, initiate change-detection,
  39468. * and explicitly mark views as _dirty_, meaning that they have changed and need to be rerendered.
  39469. *
  39470. * @usageNotes
  39471. *
  39472. * The following examples demonstrate how to modify default change-detection behavior
  39473. * to perform explicit detection when needed.
  39474. *
  39475. * ### Use `markForCheck()` with `CheckOnce` strategy
  39476. *
  39477. * The following example sets the `OnPush` change-detection strategy for a component
  39478. * (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check
  39479. * after an interval. See [live demo](http://plnkr.co/edit/GC512b?p=preview).
  39480. *
  39481. * <code-example path="core/ts/change_detect/change-detection.ts"
  39482. * region="mark-for-check"></code-example>
  39483. *
  39484. * ### Detach change detector to limit how often check occurs
  39485. *
  39486. * The following example defines a component with a large list of read-only data
  39487. * that is expected to change constantly, many times per second.
  39488. * To improve performance, we want to check and update the list
  39489. * less often than the changes actually occur. To do that, we detach
  39490. * the component's change detector and perform an explicit local check every five seconds.
  39491. *
  39492. * <code-example path="core/ts/change_detect/change-detection.ts" region="detach"></code-example>
  39493. *
  39494. *
  39495. * ### Reattaching a detached component
  39496. *
  39497. * The following example creates a component displaying live data.
  39498. * The component detaches its change detector from the main change detector tree
  39499. * when the `live` property is set to false, and reattaches it when the property
  39500. * becomes true.
  39501. *
  39502. * <code-example path="core/ts/change_detect/change-detection.ts" region="reattach"></code-example>
  39503. *
  39504. * @publicApi
  39505. */
  39506. var ChangeDetectorRef = /** @class */ (function () {
  39507. function ChangeDetectorRef() {
  39508. }
  39509. /**
  39510. * @internal
  39511. * @nocollapse
  39512. */
  39513. ChangeDetectorRef.__NG_ELEMENT_ID__ = function () { return SWITCH_CHANGE_DETECTOR_REF_FACTORY(); };
  39514. return ChangeDetectorRef;
  39515. }());
  39516. var SWITCH_CHANGE_DETECTOR_REF_FACTORY__PRE_R3__ = function () {
  39517. var args = [];
  39518. for (var _i = 0; _i < arguments.length; _i++) {
  39519. args[_i] = arguments[_i];
  39520. }
  39521. };
  39522. var SWITCH_CHANGE_DETECTOR_REF_FACTORY = SWITCH_CHANGE_DETECTOR_REF_FACTORY__PRE_R3__;
  39523. /**
  39524. * @license
  39525. * Copyright Google Inc. All Rights Reserved.
  39526. *
  39527. * Use of this source code is governed by an MIT-style license that can be
  39528. * found in the LICENSE file at https://angular.io/license
  39529. */
  39530. /**
  39531. * Structural diffing for `Object`s and `Map`s.
  39532. */
  39533. var keyValDiff = [new DefaultKeyValueDifferFactory()];
  39534. /**
  39535. * Structural diffing for `Iterable` types such as `Array`s.
  39536. */
  39537. var iterableDiff = [new DefaultIterableDifferFactory()];
  39538. var defaultIterableDiffers = new IterableDiffers(iterableDiff);
  39539. var defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
  39540. /**
  39541. * @license
  39542. * Copyright Google Inc. All Rights Reserved.
  39543. *
  39544. * Use of this source code is governed by an MIT-style license that can be
  39545. * found in the LICENSE file at https://angular.io/license
  39546. */
  39547. /**
  39548. * Represents an embedded template that can be used to instantiate embedded views.
  39549. * To instantiate embedded views based on a template, use the `ViewContainerRef`
  39550. * method `createEmbeddedView()`.
  39551. *
  39552. * Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
  39553. * element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
  39554. * is injected into the constructor of the directive,
  39555. * using the `TemplateRef` token.
  39556. *
  39557. * You can also use a `Query` to find a `TemplateRef` associated with
  39558. * a component or a directive.
  39559. *
  39560. * @see `ViewContainerRef`
  39561. * @see [Navigate the Component Tree with DI](guide/dependency-injection-navtree)
  39562. *
  39563. * @publicApi
  39564. */
  39565. var TemplateRef = /** @class */ (function () {
  39566. function TemplateRef() {
  39567. }
  39568. /**
  39569. * @internal
  39570. * @nocollapse
  39571. */
  39572. TemplateRef.__NG_ELEMENT_ID__ = function () { return SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); };
  39573. return TemplateRef;
  39574. }());
  39575. var SWITCH_TEMPLATE_REF_FACTORY__PRE_R3__ = noop;
  39576. var SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__PRE_R3__;
  39577. /**
  39578. * @license
  39579. * Copyright Google Inc. All Rights Reserved.
  39580. *
  39581. * Use of this source code is governed by an MIT-style license that can be
  39582. * found in the LICENSE file at https://angular.io/license
  39583. */
  39584. /**
  39585. * Represents a container where one or more views can be attached to a component.
  39586. *
  39587. * Can contain *host views* (created by instantiating a
  39588. * component with the `createComponent()` method), and *embedded views*
  39589. * (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
  39590. *
  39591. * A view container instance can contain other view containers,
  39592. * creating a [view hierarchy](guide/glossary#view-tree).
  39593. *
  39594. * @see `ComponentRef`
  39595. * @see `EmbeddedViewRef`
  39596. *
  39597. * @publicApi
  39598. */
  39599. var ViewContainerRef = /** @class */ (function () {
  39600. function ViewContainerRef() {
  39601. }
  39602. /**
  39603. * @internal
  39604. * @nocollapse
  39605. */
  39606. ViewContainerRef.__NG_ELEMENT_ID__ = function () { return SWITCH_VIEW_CONTAINER_REF_FACTORY(ViewContainerRef, ElementRef); };
  39607. return ViewContainerRef;
  39608. }());
  39609. var SWITCH_VIEW_CONTAINER_REF_FACTORY__PRE_R3__ = noop;
  39610. var SWITCH_VIEW_CONTAINER_REF_FACTORY = SWITCH_VIEW_CONTAINER_REF_FACTORY__PRE_R3__;
  39611. /**
  39612. * @license
  39613. * Copyright Google Inc. All Rights Reserved.
  39614. *
  39615. * Use of this source code is governed by an MIT-style license that can be
  39616. * found in the LICENSE file at https://angular.io/license
  39617. */
  39618. function expressionChangedAfterItHasBeenCheckedError(context, oldValue, currValue, isFirstCheck) {
  39619. var msg = "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '" + oldValue + "'. Current value: '" + currValue + "'.";
  39620. if (isFirstCheck) {
  39621. msg +=
  39622. " It seems like the view has been created after its parent and its children have been dirty checked." +
  39623. " Has it been created in a change detection hook ?";
  39624. }
  39625. return viewDebugError(msg, context);
  39626. }
  39627. function viewWrappedDebugError(err, context) {
  39628. if (!(err instanceof Error)) {
  39629. // errors that are not Error instances don't have a stack,
  39630. // so it is ok to wrap them into a new Error object...
  39631. err = new Error(err.toString());
  39632. }
  39633. _addDebugContext(err, context);
  39634. return err;
  39635. }
  39636. function viewDebugError(msg, context) {
  39637. var err = new Error(msg);
  39638. _addDebugContext(err, context);
  39639. return err;
  39640. }
  39641. function _addDebugContext(err, context) {
  39642. err[ERROR_DEBUG_CONTEXT] = context;
  39643. err[ERROR_LOGGER] = context.logError.bind(context);
  39644. }
  39645. function isViewDebugError(err) {
  39646. return !!getDebugContext(err);
  39647. }
  39648. function viewDestroyedError(action) {
  39649. return new Error("ViewDestroyedError: Attempt to use a destroyed view: " + action);
  39650. }
  39651. /**
  39652. * @license
  39653. * Copyright Google Inc. All Rights Reserved.
  39654. *
  39655. * Use of this source code is governed by an MIT-style license that can be
  39656. * found in the LICENSE file at https://angular.io/license
  39657. */
  39658. // Called before each cycle of a view's check to detect whether this is in the
  39659. // initState for which we need to call ngOnInit, ngAfterContentInit or ngAfterViewInit
  39660. // lifecycle methods. Returns true if this check cycle should call lifecycle
  39661. // methods.
  39662. function shiftInitState(view, priorInitState, newInitState) {
  39663. // Only update the InitState if we are currently in the prior state.
  39664. // For example, only move into CallingInit if we are in BeforeInit. Only
  39665. // move into CallingContentInit if we are in CallingInit. Normally this will
  39666. // always be true because of how checkCycle is called in checkAndUpdateView.
  39667. // However, if checkAndUpdateView is called recursively or if an exception is
  39668. // thrown while checkAndUpdateView is running, checkAndUpdateView starts over
  39669. // from the beginning. This ensures the state is monotonically increasing,
  39670. // terminating in the AfterInit state, which ensures the Init methods are called
  39671. // at least once and only once.
  39672. var state = view.state;
  39673. var initState = state & 1792 /* InitState_Mask */;
  39674. if (initState === priorInitState) {
  39675. view.state = (state & ~1792 /* InitState_Mask */) | newInitState;
  39676. view.initIndex = -1;
  39677. return true;
  39678. }
  39679. return initState === newInitState;
  39680. }
  39681. // Returns true if the lifecycle init method should be called for the node with
  39682. // the given init index.
  39683. function shouldCallLifecycleInitHook(view, initState, index) {
  39684. if ((view.state & 1792 /* InitState_Mask */) === initState && view.initIndex <= index) {
  39685. view.initIndex = index + 1;
  39686. return true;
  39687. }
  39688. return false;
  39689. }
  39690. /**
  39691. * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
  39692. */
  39693. function asTextData(view, index) {
  39694. return view.nodes[index];
  39695. }
  39696. /**
  39697. * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
  39698. */
  39699. function asElementData(view, index) {
  39700. return view.nodes[index];
  39701. }
  39702. /**
  39703. * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
  39704. */
  39705. function asProviderData(view, index) {
  39706. return view.nodes[index];
  39707. }
  39708. /**
  39709. * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
  39710. */
  39711. function asPureExpressionData(view, index) {
  39712. return view.nodes[index];
  39713. }
  39714. /**
  39715. * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
  39716. */
  39717. function asQueryList(view, index) {
  39718. return view.nodes[index];
  39719. }
  39720. /**
  39721. * This object is used to prevent cycles in the source files and to have a place where
  39722. * debug mode can hook it. It is lazily filled when `isDevMode` is known.
  39723. */
  39724. var Services = {
  39725. setCurrentNode: undefined,
  39726. createRootView: undefined,
  39727. createEmbeddedView: undefined,
  39728. createComponentView: undefined,
  39729. createNgModuleRef: undefined,
  39730. overrideProvider: undefined,
  39731. overrideComponentView: undefined,
  39732. clearOverrides: undefined,
  39733. checkAndUpdateView: undefined,
  39734. checkNoChangesView: undefined,
  39735. destroyView: undefined,
  39736. resolveDep: undefined,
  39737. createDebugContext: undefined,
  39738. handleEvent: undefined,
  39739. updateDirectives: undefined,
  39740. updateRenderer: undefined,
  39741. dirtyParentQueries: undefined,
  39742. };
  39743. /**
  39744. * @license
  39745. * Copyright Google Inc. All Rights Reserved.
  39746. *
  39747. * Use of this source code is governed by an MIT-style license that can be
  39748. * found in the LICENSE file at https://angular.io/license
  39749. */
  39750. var NOOP = function () { };
  39751. var _tokenKeyCache = new Map();
  39752. function tokenKey(token) {
  39753. var key = _tokenKeyCache.get(token);
  39754. if (!key) {
  39755. key = stringify$1(token) + '_' + _tokenKeyCache.size;
  39756. _tokenKeyCache.set(token, key);
  39757. }
  39758. return key;
  39759. }
  39760. function checkBinding(view, def, bindingIdx, value) {
  39761. var oldValues = view.oldValues;
  39762. if ((view.state & 2 /* FirstCheck */) ||
  39763. !looseIdentical(oldValues[def.bindingIndex + bindingIdx], value)) {
  39764. return true;
  39765. }
  39766. return false;
  39767. }
  39768. function checkAndUpdateBinding(view, def, bindingIdx, value) {
  39769. if (checkBinding(view, def, bindingIdx, value)) {
  39770. view.oldValues[def.bindingIndex + bindingIdx] = value;
  39771. return true;
  39772. }
  39773. return false;
  39774. }
  39775. function checkBindingNoChanges(view, def, bindingIdx, value) {
  39776. var oldValue = view.oldValues[def.bindingIndex + bindingIdx];
  39777. if ((view.state & 1 /* BeforeFirstCheck */) || !devModeEqual(oldValue, value)) {
  39778. var bindingName = def.bindings[bindingIdx].name;
  39779. throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, def.nodeIndex), bindingName + ": " + oldValue, bindingName + ": " + value, (view.state & 1 /* BeforeFirstCheck */) !== 0);
  39780. }
  39781. }
  39782. function markParentViewsForCheck(view) {
  39783. var currView = view;
  39784. while (currView) {
  39785. if (currView.def.flags & 2 /* OnPush */) {
  39786. currView.state |= 8 /* ChecksEnabled */;
  39787. }
  39788. currView = currView.viewContainerParent || currView.parent;
  39789. }
  39790. }
  39791. function markParentViewsForCheckProjectedViews(view, endView) {
  39792. var currView = view;
  39793. while (currView && currView !== endView) {
  39794. currView.state |= 64 /* CheckProjectedViews */;
  39795. currView = currView.viewContainerParent || currView.parent;
  39796. }
  39797. }
  39798. function dispatchEvent(view, nodeIndex, eventName, event) {
  39799. try {
  39800. var nodeDef = view.def.nodes[nodeIndex];
  39801. var startView = nodeDef.flags & 33554432 /* ComponentView */ ?
  39802. asElementData(view, nodeIndex).componentView :
  39803. view;
  39804. markParentViewsForCheck(startView);
  39805. return Services.handleEvent(view, nodeIndex, eventName, event);
  39806. }
  39807. catch (e) {
  39808. // Attention: Don't rethrow, as it would cancel Observable subscriptions!
  39809. view.root.errorHandler.handleError(e);
  39810. }
  39811. }
  39812. function declaredViewContainer(view) {
  39813. if (view.parent) {
  39814. var parentView = view.parent;
  39815. return asElementData(parentView, view.parentNodeDef.nodeIndex);
  39816. }
  39817. return null;
  39818. }
  39819. /**
  39820. * for component views, this is the host element.
  39821. * for embedded views, this is the index of the parent node
  39822. * that contains the view container.
  39823. */
  39824. function viewParentEl(view) {
  39825. var parentView = view.parent;
  39826. if (parentView) {
  39827. return view.parentNodeDef.parent;
  39828. }
  39829. else {
  39830. return null;
  39831. }
  39832. }
  39833. function renderNode(view, def) {
  39834. switch (def.flags & 201347067 /* Types */) {
  39835. case 1 /* TypeElement */:
  39836. return asElementData(view, def.nodeIndex).renderElement;
  39837. case 2 /* TypeText */:
  39838. return asTextData(view, def.nodeIndex).renderText;
  39839. }
  39840. }
  39841. function elementEventFullName(target, name) {
  39842. return target ? target + ":" + name : name;
  39843. }
  39844. function isComponentView(view) {
  39845. return !!view.parent && !!(view.parentNodeDef.flags & 32768 /* Component */);
  39846. }
  39847. function isEmbeddedView(view) {
  39848. return !!view.parent && !(view.parentNodeDef.flags & 32768 /* Component */);
  39849. }
  39850. function splitDepsDsl(deps, sourceName) {
  39851. return deps.map(function (value) {
  39852. var _a;
  39853. var token;
  39854. var flags;
  39855. if (Array.isArray(value)) {
  39856. _a = __read(value, 2), flags = _a[0], token = _a[1];
  39857. }
  39858. else {
  39859. flags = 0 /* None */;
  39860. token = value;
  39861. }
  39862. if (token && (typeof token === 'function' || typeof token === 'object') && sourceName) {
  39863. Object.defineProperty(token, SOURCE, { value: sourceName, configurable: true });
  39864. }
  39865. return { flags: flags, token: token, tokenKey: tokenKey(token) };
  39866. });
  39867. }
  39868. function getParentRenderElement(view, renderHost, def) {
  39869. var renderParent = def.renderParent;
  39870. if (renderParent) {
  39871. if ((renderParent.flags & 1 /* TypeElement */) === 0 ||
  39872. (renderParent.flags & 33554432 /* ComponentView */) === 0 ||
  39873. (renderParent.element.componentRendererType &&
  39874. renderParent.element.componentRendererType.encapsulation ===
  39875. ViewEncapsulation$1.Native)) {
  39876. // only children of non components, or children of components with native encapsulation should
  39877. // be attached.
  39878. return asElementData(view, def.renderParent.nodeIndex).renderElement;
  39879. }
  39880. }
  39881. else {
  39882. return renderHost;
  39883. }
  39884. }
  39885. var DEFINITION_CACHE = new WeakMap();
  39886. function resolveDefinition(factory) {
  39887. var value = DEFINITION_CACHE.get(factory);
  39888. if (!value) {
  39889. value = factory(function () { return NOOP; });
  39890. value.factory = factory;
  39891. DEFINITION_CACHE.set(factory, value);
  39892. }
  39893. return value;
  39894. }
  39895. function rootRenderNodes(view) {
  39896. var renderNodes = [];
  39897. visitRootRenderNodes(view, 0 /* Collect */, undefined, undefined, renderNodes);
  39898. return renderNodes;
  39899. }
  39900. function visitRootRenderNodes(view, action, parentNode, nextSibling, target) {
  39901. // We need to re-compute the parent node in case the nodes have been moved around manually
  39902. if (action === 3 /* RemoveChild */) {
  39903. parentNode = view.renderer.parentNode(renderNode(view, view.def.lastRenderRootNode));
  39904. }
  39905. visitSiblingRenderNodes(view, action, 0, view.def.nodes.length - 1, parentNode, nextSibling, target);
  39906. }
  39907. function visitSiblingRenderNodes(view, action, startIndex, endIndex, parentNode, nextSibling, target) {
  39908. for (var i = startIndex; i <= endIndex; i++) {
  39909. var nodeDef = view.def.nodes[i];
  39910. if (nodeDef.flags & (1 /* TypeElement */ | 2 /* TypeText */ | 8 /* TypeNgContent */)) {
  39911. visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target);
  39912. }
  39913. // jump to next sibling
  39914. i += nodeDef.childCount;
  39915. }
  39916. }
  39917. function visitProjectedRenderNodes(view, ngContentIndex, action, parentNode, nextSibling, target) {
  39918. var compView = view;
  39919. while (compView && !isComponentView(compView)) {
  39920. compView = compView.parent;
  39921. }
  39922. var hostView = compView.parent;
  39923. var hostElDef = viewParentEl(compView);
  39924. var startIndex = hostElDef.nodeIndex + 1;
  39925. var endIndex = hostElDef.nodeIndex + hostElDef.childCount;
  39926. for (var i = startIndex; i <= endIndex; i++) {
  39927. var nodeDef = hostView.def.nodes[i];
  39928. if (nodeDef.ngContentIndex === ngContentIndex) {
  39929. visitRenderNode(hostView, nodeDef, action, parentNode, nextSibling, target);
  39930. }
  39931. // jump to next sibling
  39932. i += nodeDef.childCount;
  39933. }
  39934. if (!hostView.parent) {
  39935. // a root view
  39936. var projectedNodes = view.root.projectableNodes[ngContentIndex];
  39937. if (projectedNodes) {
  39938. for (var i = 0; i < projectedNodes.length; i++) {
  39939. execRenderNodeAction(view, projectedNodes[i], action, parentNode, nextSibling, target);
  39940. }
  39941. }
  39942. }
  39943. }
  39944. function visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target) {
  39945. if (nodeDef.flags & 8 /* TypeNgContent */) {
  39946. visitProjectedRenderNodes(view, nodeDef.ngContent.index, action, parentNode, nextSibling, target);
  39947. }
  39948. else {
  39949. var rn = renderNode(view, nodeDef);
  39950. if (action === 3 /* RemoveChild */ && (nodeDef.flags & 33554432 /* ComponentView */) &&
  39951. (nodeDef.bindingFlags & 48 /* CatSyntheticProperty */)) {
  39952. // Note: we might need to do both actions.
  39953. if (nodeDef.bindingFlags & (16 /* SyntheticProperty */)) {
  39954. execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
  39955. }
  39956. if (nodeDef.bindingFlags & (32 /* SyntheticHostProperty */)) {
  39957. var compView = asElementData(view, nodeDef.nodeIndex).componentView;
  39958. execRenderNodeAction(compView, rn, action, parentNode, nextSibling, target);
  39959. }
  39960. }
  39961. else {
  39962. execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
  39963. }
  39964. if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
  39965. var embeddedViews = asElementData(view, nodeDef.nodeIndex).viewContainer._embeddedViews;
  39966. for (var k = 0; k < embeddedViews.length; k++) {
  39967. visitRootRenderNodes(embeddedViews[k], action, parentNode, nextSibling, target);
  39968. }
  39969. }
  39970. if (nodeDef.flags & 1 /* TypeElement */ && !nodeDef.element.name) {
  39971. visitSiblingRenderNodes(view, action, nodeDef.nodeIndex + 1, nodeDef.nodeIndex + nodeDef.childCount, parentNode, nextSibling, target);
  39972. }
  39973. }
  39974. }
  39975. function execRenderNodeAction(view, renderNode, action, parentNode, nextSibling, target) {
  39976. var renderer = view.renderer;
  39977. switch (action) {
  39978. case 1 /* AppendChild */:
  39979. renderer.appendChild(parentNode, renderNode);
  39980. break;
  39981. case 2 /* InsertBefore */:
  39982. renderer.insertBefore(parentNode, renderNode, nextSibling);
  39983. break;
  39984. case 3 /* RemoveChild */:
  39985. renderer.removeChild(parentNode, renderNode);
  39986. break;
  39987. case 0 /* Collect */:
  39988. target.push(renderNode);
  39989. break;
  39990. }
  39991. }
  39992. var NS_PREFIX_RE = /^:([^:]+):(.+)$/;
  39993. function splitNamespace(name) {
  39994. if (name[0] === ':') {
  39995. var match = name.match(NS_PREFIX_RE);
  39996. return [match[1], match[2]];
  39997. }
  39998. return ['', name];
  39999. }
  40000. /**
  40001. * @license
  40002. * Copyright Google Inc. All Rights Reserved.
  40003. *
  40004. * Use of this source code is governed by an MIT-style license that can be
  40005. * found in the LICENSE file at https://angular.io/license
  40006. */
  40007. var UNDEFINED_VALUE = new Object();
  40008. var InjectorRefTokenKey = tokenKey(Injector);
  40009. var INJECTORRefTokenKey = tokenKey(INJECTOR);
  40010. var NgModuleRefTokenKey = tokenKey(NgModuleRef);
  40011. function initNgModule(data) {
  40012. var def = data._def;
  40013. var providers = data._providers = new Array(def.providers.length);
  40014. for (var i = 0; i < def.providers.length; i++) {
  40015. var provDef = def.providers[i];
  40016. if (!(provDef.flags & 4096 /* LazyProvider */)) {
  40017. // Make sure the provider has not been already initialized outside this loop.
  40018. if (providers[i] === undefined) {
  40019. providers[i] = _createProviderInstance(data, provDef);
  40020. }
  40021. }
  40022. }
  40023. }
  40024. function resolveNgModuleDep(data, depDef, notFoundValue) {
  40025. if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
  40026. var former = setCurrentInjector(data);
  40027. try {
  40028. if (depDef.flags & 8 /* Value */) {
  40029. return depDef.token;
  40030. }
  40031. if (depDef.flags & 2 /* Optional */) {
  40032. notFoundValue = null;
  40033. }
  40034. if (depDef.flags & 1 /* SkipSelf */) {
  40035. return data._parent.get(depDef.token, notFoundValue);
  40036. }
  40037. var tokenKey_1 = depDef.tokenKey;
  40038. switch (tokenKey_1) {
  40039. case InjectorRefTokenKey:
  40040. case INJECTORRefTokenKey:
  40041. case NgModuleRefTokenKey:
  40042. return data;
  40043. }
  40044. var providerDef = data._def.providersByKey[tokenKey_1];
  40045. var injectableDef = void 0;
  40046. if (providerDef) {
  40047. var providerInstance = data._providers[providerDef.index];
  40048. if (providerInstance === undefined) {
  40049. providerInstance = data._providers[providerDef.index] =
  40050. _createProviderInstance(data, providerDef);
  40051. }
  40052. return providerInstance === UNDEFINED_VALUE ? undefined : providerInstance;
  40053. }
  40054. else if ((injectableDef = getInjectableDef(depDef.token)) && targetsModule(data, injectableDef)) {
  40055. var index = data._providers.length;
  40056. data._def.providers[index] = data._def.providersByKey[depDef.tokenKey] = {
  40057. flags: 1024 /* TypeFactoryProvider */ | 4096 /* LazyProvider */,
  40058. value: injectableDef.factory,
  40059. deps: [], index: index,
  40060. token: depDef.token,
  40061. };
  40062. data._providers[index] = UNDEFINED_VALUE;
  40063. return (data._providers[index] =
  40064. _createProviderInstance(data, data._def.providersByKey[depDef.tokenKey]));
  40065. }
  40066. else if (depDef.flags & 4 /* Self */) {
  40067. return notFoundValue;
  40068. }
  40069. return data._parent.get(depDef.token, notFoundValue);
  40070. }
  40071. finally {
  40072. setCurrentInjector(former);
  40073. }
  40074. }
  40075. function moduleTransitivelyPresent(ngModule, scope) {
  40076. return ngModule._def.modules.indexOf(scope) > -1;
  40077. }
  40078. function targetsModule(ngModule, def) {
  40079. return def.providedIn != null && (moduleTransitivelyPresent(ngModule, def.providedIn) ||
  40080. def.providedIn === 'root' && ngModule._def.isRoot);
  40081. }
  40082. function _createProviderInstance(ngModule, providerDef) {
  40083. var injectable;
  40084. switch (providerDef.flags & 201347067 /* Types */) {
  40085. case 512 /* TypeClassProvider */:
  40086. injectable = _createClass(ngModule, providerDef.value, providerDef.deps);
  40087. break;
  40088. case 1024 /* TypeFactoryProvider */:
  40089. injectable = _callFactory(ngModule, providerDef.value, providerDef.deps);
  40090. break;
  40091. case 2048 /* TypeUseExistingProvider */:
  40092. injectable = resolveNgModuleDep(ngModule, providerDef.deps[0]);
  40093. break;
  40094. case 256 /* TypeValueProvider */:
  40095. injectable = providerDef.value;
  40096. break;
  40097. }
  40098. // The read of `ngOnDestroy` here is slightly expensive as it's megamorphic, so it should be
  40099. // avoided if possible. The sequence of checks here determines whether ngOnDestroy needs to be
  40100. // checked. It might not if the `injectable` isn't an object or if NodeFlags.OnDestroy is already
  40101. // set (ngOnDestroy was detected statically).
  40102. if (injectable !== UNDEFINED_VALUE && injectable !== null && typeof injectable === 'object' &&
  40103. !(providerDef.flags & 131072 /* OnDestroy */) && typeof injectable.ngOnDestroy === 'function') {
  40104. providerDef.flags |= 131072 /* OnDestroy */;
  40105. }
  40106. return injectable === undefined ? UNDEFINED_VALUE : injectable;
  40107. }
  40108. function _createClass(ngModule, ctor, deps) {
  40109. var len = deps.length;
  40110. switch (len) {
  40111. case 0:
  40112. return new ctor();
  40113. case 1:
  40114. return new ctor(resolveNgModuleDep(ngModule, deps[0]));
  40115. case 2:
  40116. return new ctor(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]));
  40117. case 3:
  40118. return new ctor(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]), resolveNgModuleDep(ngModule, deps[2]));
  40119. default:
  40120. var depValues = new Array(len);
  40121. for (var i = 0; i < len; i++) {
  40122. depValues[i] = resolveNgModuleDep(ngModule, deps[i]);
  40123. }
  40124. return new (ctor.bind.apply(ctor, __spread([void 0], depValues)))();
  40125. }
  40126. }
  40127. function _callFactory(ngModule, factory, deps) {
  40128. var len = deps.length;
  40129. switch (len) {
  40130. case 0:
  40131. return factory();
  40132. case 1:
  40133. return factory(resolveNgModuleDep(ngModule, deps[0]));
  40134. case 2:
  40135. return factory(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]));
  40136. case 3:
  40137. return factory(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]), resolveNgModuleDep(ngModule, deps[2]));
  40138. default:
  40139. var depValues = Array(len);
  40140. for (var i = 0; i < len; i++) {
  40141. depValues[i] = resolveNgModuleDep(ngModule, deps[i]);
  40142. }
  40143. return factory.apply(void 0, __spread(depValues));
  40144. }
  40145. }
  40146. function callNgModuleLifecycle(ngModule, lifecycles) {
  40147. var def = ngModule._def;
  40148. var destroyed = new Set();
  40149. for (var i = 0; i < def.providers.length; i++) {
  40150. var provDef = def.providers[i];
  40151. if (provDef.flags & 131072 /* OnDestroy */) {
  40152. var instance = ngModule._providers[i];
  40153. if (instance && instance !== UNDEFINED_VALUE) {
  40154. var onDestroy = instance.ngOnDestroy;
  40155. if (typeof onDestroy === 'function' && !destroyed.has(instance)) {
  40156. onDestroy.apply(instance);
  40157. destroyed.add(instance);
  40158. }
  40159. }
  40160. }
  40161. }
  40162. }
  40163. /**
  40164. * @license
  40165. * Copyright Google Inc. All Rights Reserved.
  40166. *
  40167. * Use of this source code is governed by an MIT-style license that can be
  40168. * found in the LICENSE file at https://angular.io/license
  40169. */
  40170. function attachEmbeddedView(parentView, elementData, viewIndex, view) {
  40171. var embeddedViews = elementData.viewContainer._embeddedViews;
  40172. if (viewIndex === null || viewIndex === undefined) {
  40173. viewIndex = embeddedViews.length;
  40174. }
  40175. view.viewContainerParent = parentView;
  40176. addToArray(embeddedViews, viewIndex, view);
  40177. attachProjectedView(elementData, view);
  40178. Services.dirtyParentQueries(view);
  40179. var prevView = viewIndex > 0 ? embeddedViews[viewIndex - 1] : null;
  40180. renderAttachEmbeddedView(elementData, prevView, view);
  40181. }
  40182. function attachProjectedView(vcElementData, view) {
  40183. var dvcElementData = declaredViewContainer(view);
  40184. if (!dvcElementData || dvcElementData === vcElementData ||
  40185. view.state & 16 /* IsProjectedView */) {
  40186. return;
  40187. }
  40188. // Note: For performance reasons, we
  40189. // - add a view to template._projectedViews only 1x throughout its lifetime,
  40190. // and remove it not until the view is destroyed.
  40191. // (hard, as when a parent view is attached/detached we would need to attach/detach all
  40192. // nested projected views as well, even across component boundaries).
  40193. // - don't track the insertion order of views in the projected views array
  40194. // (hard, as when the views of the same template are inserted different view containers)
  40195. view.state |= 16 /* IsProjectedView */;
  40196. var projectedViews = dvcElementData.template._projectedViews;
  40197. if (!projectedViews) {
  40198. projectedViews = dvcElementData.template._projectedViews = [];
  40199. }
  40200. projectedViews.push(view);
  40201. // Note: we are changing the NodeDef here as we cannot calculate
  40202. // the fact whether a template is used for projection during compilation.
  40203. markNodeAsProjectedTemplate(view.parent.def, view.parentNodeDef);
  40204. }
  40205. function markNodeAsProjectedTemplate(viewDef, nodeDef) {
  40206. if (nodeDef.flags & 4 /* ProjectedTemplate */) {
  40207. return;
  40208. }
  40209. viewDef.nodeFlags |= 4 /* ProjectedTemplate */;
  40210. nodeDef.flags |= 4 /* ProjectedTemplate */;
  40211. var parentNodeDef = nodeDef.parent;
  40212. while (parentNodeDef) {
  40213. parentNodeDef.childFlags |= 4 /* ProjectedTemplate */;
  40214. parentNodeDef = parentNodeDef.parent;
  40215. }
  40216. }
  40217. function detachEmbeddedView(elementData, viewIndex) {
  40218. var embeddedViews = elementData.viewContainer._embeddedViews;
  40219. if (viewIndex == null || viewIndex >= embeddedViews.length) {
  40220. viewIndex = embeddedViews.length - 1;
  40221. }
  40222. if (viewIndex < 0) {
  40223. return null;
  40224. }
  40225. var view = embeddedViews[viewIndex];
  40226. view.viewContainerParent = null;
  40227. removeFromArray(embeddedViews, viewIndex);
  40228. // See attachProjectedView for why we don't update projectedViews here.
  40229. Services.dirtyParentQueries(view);
  40230. renderDetachView$1(view);
  40231. return view;
  40232. }
  40233. function detachProjectedView(view) {
  40234. if (!(view.state & 16 /* IsProjectedView */)) {
  40235. return;
  40236. }
  40237. var dvcElementData = declaredViewContainer(view);
  40238. if (dvcElementData) {
  40239. var projectedViews = dvcElementData.template._projectedViews;
  40240. if (projectedViews) {
  40241. removeFromArray(projectedViews, projectedViews.indexOf(view));
  40242. Services.dirtyParentQueries(view);
  40243. }
  40244. }
  40245. }
  40246. function moveEmbeddedView(elementData, oldViewIndex, newViewIndex) {
  40247. var embeddedViews = elementData.viewContainer._embeddedViews;
  40248. var view = embeddedViews[oldViewIndex];
  40249. removeFromArray(embeddedViews, oldViewIndex);
  40250. if (newViewIndex == null) {
  40251. newViewIndex = embeddedViews.length;
  40252. }
  40253. addToArray(embeddedViews, newViewIndex, view);
  40254. // Note: Don't need to change projectedViews as the order in there
  40255. // as always invalid...
  40256. Services.dirtyParentQueries(view);
  40257. renderDetachView$1(view);
  40258. var prevView = newViewIndex > 0 ? embeddedViews[newViewIndex - 1] : null;
  40259. renderAttachEmbeddedView(elementData, prevView, view);
  40260. return view;
  40261. }
  40262. function renderAttachEmbeddedView(elementData, prevView, view) {
  40263. var prevRenderNode = prevView ? renderNode(prevView, prevView.def.lastRenderRootNode) :
  40264. elementData.renderElement;
  40265. var parentNode = view.renderer.parentNode(prevRenderNode);
  40266. var nextSibling = view.renderer.nextSibling(prevRenderNode);
  40267. // Note: We can't check if `nextSibling` is present, as on WebWorkers it will always be!
  40268. // However, browsers automatically do `appendChild` when there is no `nextSibling`.
  40269. visitRootRenderNodes(view, 2 /* InsertBefore */, parentNode, nextSibling, undefined);
  40270. }
  40271. function renderDetachView$1(view) {
  40272. visitRootRenderNodes(view, 3 /* RemoveChild */, null, null, undefined);
  40273. }
  40274. function addToArray(arr, index, value) {
  40275. // perf: array.push is faster than array.splice!
  40276. if (index >= arr.length) {
  40277. arr.push(value);
  40278. }
  40279. else {
  40280. arr.splice(index, 0, value);
  40281. }
  40282. }
  40283. function removeFromArray(arr, index) {
  40284. // perf: array.pop is faster than array.splice!
  40285. if (index >= arr.length - 1) {
  40286. arr.pop();
  40287. }
  40288. else {
  40289. arr.splice(index, 1);
  40290. }
  40291. }
  40292. /**
  40293. * @license
  40294. * Copyright Google Inc. All Rights Reserved.
  40295. *
  40296. * Use of this source code is governed by an MIT-style license that can be
  40297. * found in the LICENSE file at https://angular.io/license
  40298. */
  40299. var EMPTY_CONTEXT = new Object();
  40300. function getComponentViewDefinitionFactory(componentFactory) {
  40301. return componentFactory.viewDefFactory;
  40302. }
  40303. var ComponentFactory_ = /** @class */ (function (_super) {
  40304. __extends(ComponentFactory_, _super);
  40305. function ComponentFactory_(selector, componentType, viewDefFactory, _inputs, _outputs, ngContentSelectors) {
  40306. var _this =
  40307. // Attention: this ctor is called as top level function.
  40308. // Putting any logic in here will destroy closure tree shaking!
  40309. _super.call(this) || this;
  40310. _this.selector = selector;
  40311. _this.componentType = componentType;
  40312. _this._inputs = _inputs;
  40313. _this._outputs = _outputs;
  40314. _this.ngContentSelectors = ngContentSelectors;
  40315. _this.viewDefFactory = viewDefFactory;
  40316. return _this;
  40317. }
  40318. Object.defineProperty(ComponentFactory_.prototype, "inputs", {
  40319. get: function () {
  40320. var inputsArr = [];
  40321. var inputs = this._inputs;
  40322. for (var propName in inputs) {
  40323. var templateName = inputs[propName];
  40324. inputsArr.push({ propName: propName, templateName: templateName });
  40325. }
  40326. return inputsArr;
  40327. },
  40328. enumerable: true,
  40329. configurable: true
  40330. });
  40331. Object.defineProperty(ComponentFactory_.prototype, "outputs", {
  40332. get: function () {
  40333. var outputsArr = [];
  40334. for (var propName in this._outputs) {
  40335. var templateName = this._outputs[propName];
  40336. outputsArr.push({ propName: propName, templateName: templateName });
  40337. }
  40338. return outputsArr;
  40339. },
  40340. enumerable: true,
  40341. configurable: true
  40342. });
  40343. /**
  40344. * Creates a new component.
  40345. */
  40346. ComponentFactory_.prototype.create = function (injector, projectableNodes, rootSelectorOrNode, ngModule) {
  40347. if (!ngModule) {
  40348. throw new Error('ngModule should be provided');
  40349. }
  40350. var viewDef = resolveDefinition(this.viewDefFactory);
  40351. var componentNodeIndex = viewDef.nodes[0].element.componentProvider.nodeIndex;
  40352. var view = Services.createRootView(injector, projectableNodes || [], rootSelectorOrNode, viewDef, ngModule, EMPTY_CONTEXT);
  40353. var component = asProviderData(view, componentNodeIndex).instance;
  40354. if (rootSelectorOrNode) {
  40355. view.renderer.setAttribute(asElementData(view, 0).renderElement, 'ng-version', VERSION$2.full);
  40356. }
  40357. return new ComponentRef_(view, new ViewRef_(view), component);
  40358. };
  40359. return ComponentFactory_;
  40360. }(ComponentFactory));
  40361. var ComponentRef_ = /** @class */ (function (_super) {
  40362. __extends(ComponentRef_, _super);
  40363. function ComponentRef_(_view, _viewRef, _component) {
  40364. var _this = _super.call(this) || this;
  40365. _this._view = _view;
  40366. _this._viewRef = _viewRef;
  40367. _this._component = _component;
  40368. _this._elDef = _this._view.def.nodes[0];
  40369. _this.hostView = _viewRef;
  40370. _this.changeDetectorRef = _viewRef;
  40371. _this.instance = _component;
  40372. return _this;
  40373. }
  40374. Object.defineProperty(ComponentRef_.prototype, "location", {
  40375. get: function () {
  40376. return new ElementRef(asElementData(this._view, this._elDef.nodeIndex).renderElement);
  40377. },
  40378. enumerable: true,
  40379. configurable: true
  40380. });
  40381. Object.defineProperty(ComponentRef_.prototype, "injector", {
  40382. get: function () { return new Injector_(this._view, this._elDef); },
  40383. enumerable: true,
  40384. configurable: true
  40385. });
  40386. Object.defineProperty(ComponentRef_.prototype, "componentType", {
  40387. get: function () { return this._component.constructor; },
  40388. enumerable: true,
  40389. configurable: true
  40390. });
  40391. ComponentRef_.prototype.destroy = function () { this._viewRef.destroy(); };
  40392. ComponentRef_.prototype.onDestroy = function (callback) { this._viewRef.onDestroy(callback); };
  40393. return ComponentRef_;
  40394. }(ComponentRef));
  40395. function createViewContainerData(view, elDef, elData) {
  40396. return new ViewContainerRef_(view, elDef, elData);
  40397. }
  40398. var ViewContainerRef_ = /** @class */ (function () {
  40399. function ViewContainerRef_(_view, _elDef, _data) {
  40400. this._view = _view;
  40401. this._elDef = _elDef;
  40402. this._data = _data;
  40403. /**
  40404. * @internal
  40405. */
  40406. this._embeddedViews = [];
  40407. }
  40408. Object.defineProperty(ViewContainerRef_.prototype, "element", {
  40409. get: function () { return new ElementRef(this._data.renderElement); },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. Object.defineProperty(ViewContainerRef_.prototype, "injector", {
  40414. get: function () { return new Injector_(this._view, this._elDef); },
  40415. enumerable: true,
  40416. configurable: true
  40417. });
  40418. Object.defineProperty(ViewContainerRef_.prototype, "parentInjector", {
  40419. /** @deprecated No replacement */
  40420. get: function () {
  40421. var view = this._view;
  40422. var elDef = this._elDef.parent;
  40423. while (!elDef && view) {
  40424. elDef = viewParentEl(view);
  40425. view = view.parent;
  40426. }
  40427. return view ? new Injector_(view, elDef) : new Injector_(this._view, null);
  40428. },
  40429. enumerable: true,
  40430. configurable: true
  40431. });
  40432. ViewContainerRef_.prototype.clear = function () {
  40433. var len = this._embeddedViews.length;
  40434. for (var i = len - 1; i >= 0; i--) {
  40435. var view = detachEmbeddedView(this._data, i);
  40436. Services.destroyView(view);
  40437. }
  40438. };
  40439. ViewContainerRef_.prototype.get = function (index) {
  40440. var view = this._embeddedViews[index];
  40441. if (view) {
  40442. var ref = new ViewRef_(view);
  40443. ref.attachToViewContainerRef(this);
  40444. return ref;
  40445. }
  40446. return null;
  40447. };
  40448. Object.defineProperty(ViewContainerRef_.prototype, "length", {
  40449. get: function () { return this._embeddedViews.length; },
  40450. enumerable: true,
  40451. configurable: true
  40452. });
  40453. ViewContainerRef_.prototype.createEmbeddedView = function (templateRef, context, index) {
  40454. var viewRef = templateRef.createEmbeddedView(context || {});
  40455. this.insert(viewRef, index);
  40456. return viewRef;
  40457. };
  40458. ViewContainerRef_.prototype.createComponent = function (componentFactory, index, injector, projectableNodes, ngModuleRef) {
  40459. var contextInjector = injector || this.parentInjector;
  40460. if (!ngModuleRef && !(componentFactory instanceof ComponentFactoryBoundToModule)) {
  40461. ngModuleRef = contextInjector.get(NgModuleRef);
  40462. }
  40463. var componentRef = componentFactory.create(contextInjector, projectableNodes, undefined, ngModuleRef);
  40464. this.insert(componentRef.hostView, index);
  40465. return componentRef;
  40466. };
  40467. ViewContainerRef_.prototype.insert = function (viewRef, index) {
  40468. if (viewRef.destroyed) {
  40469. throw new Error('Cannot insert a destroyed View in a ViewContainer!');
  40470. }
  40471. var viewRef_ = viewRef;
  40472. var viewData = viewRef_._view;
  40473. attachEmbeddedView(this._view, this._data, index, viewData);
  40474. viewRef_.attachToViewContainerRef(this);
  40475. return viewRef;
  40476. };
  40477. ViewContainerRef_.prototype.move = function (viewRef, currentIndex) {
  40478. if (viewRef.destroyed) {
  40479. throw new Error('Cannot move a destroyed View in a ViewContainer!');
  40480. }
  40481. var previousIndex = this._embeddedViews.indexOf(viewRef._view);
  40482. moveEmbeddedView(this._data, previousIndex, currentIndex);
  40483. return viewRef;
  40484. };
  40485. ViewContainerRef_.prototype.indexOf = function (viewRef) {
  40486. return this._embeddedViews.indexOf(viewRef._view);
  40487. };
  40488. ViewContainerRef_.prototype.remove = function (index) {
  40489. var viewData = detachEmbeddedView(this._data, index);
  40490. if (viewData) {
  40491. Services.destroyView(viewData);
  40492. }
  40493. };
  40494. ViewContainerRef_.prototype.detach = function (index) {
  40495. var view = detachEmbeddedView(this._data, index);
  40496. return view ? new ViewRef_(view) : null;
  40497. };
  40498. return ViewContainerRef_;
  40499. }());
  40500. function createChangeDetectorRef(view) {
  40501. return new ViewRef_(view);
  40502. }
  40503. var ViewRef_ = /** @class */ (function () {
  40504. function ViewRef_(_view) {
  40505. this._view = _view;
  40506. this._viewContainerRef = null;
  40507. this._appRef = null;
  40508. }
  40509. Object.defineProperty(ViewRef_.prototype, "rootNodes", {
  40510. get: function () { return rootRenderNodes(this._view); },
  40511. enumerable: true,
  40512. configurable: true
  40513. });
  40514. Object.defineProperty(ViewRef_.prototype, "context", {
  40515. get: function () { return this._view.context; },
  40516. enumerable: true,
  40517. configurable: true
  40518. });
  40519. Object.defineProperty(ViewRef_.prototype, "destroyed", {
  40520. get: function () { return (this._view.state & 128 /* Destroyed */) !== 0; },
  40521. enumerable: true,
  40522. configurable: true
  40523. });
  40524. ViewRef_.prototype.markForCheck = function () { markParentViewsForCheck(this._view); };
  40525. ViewRef_.prototype.detach = function () { this._view.state &= ~4 /* Attached */; };
  40526. ViewRef_.prototype.detectChanges = function () {
  40527. var fs = this._view.root.rendererFactory;
  40528. if (fs.begin) {
  40529. fs.begin();
  40530. }
  40531. try {
  40532. Services.checkAndUpdateView(this._view);
  40533. }
  40534. finally {
  40535. if (fs.end) {
  40536. fs.end();
  40537. }
  40538. }
  40539. };
  40540. ViewRef_.prototype.checkNoChanges = function () { Services.checkNoChangesView(this._view); };
  40541. ViewRef_.prototype.reattach = function () { this._view.state |= 4 /* Attached */; };
  40542. ViewRef_.prototype.onDestroy = function (callback) {
  40543. if (!this._view.disposables) {
  40544. this._view.disposables = [];
  40545. }
  40546. this._view.disposables.push(callback);
  40547. };
  40548. ViewRef_.prototype.destroy = function () {
  40549. if (this._appRef) {
  40550. this._appRef.detachView(this);
  40551. }
  40552. else if (this._viewContainerRef) {
  40553. this._viewContainerRef.detach(this._viewContainerRef.indexOf(this));
  40554. }
  40555. Services.destroyView(this._view);
  40556. };
  40557. ViewRef_.prototype.detachFromAppRef = function () {
  40558. this._appRef = null;
  40559. renderDetachView$1(this._view);
  40560. Services.dirtyParentQueries(this._view);
  40561. };
  40562. ViewRef_.prototype.attachToAppRef = function (appRef) {
  40563. if (this._viewContainerRef) {
  40564. throw new Error('This view is already attached to a ViewContainer!');
  40565. }
  40566. this._appRef = appRef;
  40567. };
  40568. ViewRef_.prototype.attachToViewContainerRef = function (vcRef) {
  40569. if (this._appRef) {
  40570. throw new Error('This view is already attached directly to the ApplicationRef!');
  40571. }
  40572. this._viewContainerRef = vcRef;
  40573. };
  40574. return ViewRef_;
  40575. }());
  40576. function createTemplateData(view, def) {
  40577. return new TemplateRef_(view, def);
  40578. }
  40579. var TemplateRef_ = /** @class */ (function (_super) {
  40580. __extends(TemplateRef_, _super);
  40581. function TemplateRef_(_parentView, _def) {
  40582. var _this = _super.call(this) || this;
  40583. _this._parentView = _parentView;
  40584. _this._def = _def;
  40585. return _this;
  40586. }
  40587. TemplateRef_.prototype.createEmbeddedView = function (context) {
  40588. return new ViewRef_(Services.createEmbeddedView(this._parentView, this._def, this._def.element.template, context));
  40589. };
  40590. Object.defineProperty(TemplateRef_.prototype, "elementRef", {
  40591. get: function () {
  40592. return new ElementRef(asElementData(this._parentView, this._def.nodeIndex).renderElement);
  40593. },
  40594. enumerable: true,
  40595. configurable: true
  40596. });
  40597. return TemplateRef_;
  40598. }(TemplateRef));
  40599. function createInjector$1(view, elDef) {
  40600. return new Injector_(view, elDef);
  40601. }
  40602. var Injector_ = /** @class */ (function () {
  40603. function Injector_(view, elDef) {
  40604. this.view = view;
  40605. this.elDef = elDef;
  40606. }
  40607. Injector_.prototype.get = function (token, notFoundValue) {
  40608. if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
  40609. var allowPrivateServices = this.elDef ? (this.elDef.flags & 33554432 /* ComponentView */) !== 0 : false;
  40610. return Services.resolveDep(this.view, this.elDef, allowPrivateServices, { flags: 0 /* None */, token: token, tokenKey: tokenKey(token) }, notFoundValue);
  40611. };
  40612. return Injector_;
  40613. }());
  40614. function createRendererV1(view) {
  40615. return new RendererAdapter(view.renderer);
  40616. }
  40617. var RendererAdapter = /** @class */ (function () {
  40618. function RendererAdapter(delegate) {
  40619. this.delegate = delegate;
  40620. }
  40621. RendererAdapter.prototype.selectRootElement = function (selectorOrNode) {
  40622. return this.delegate.selectRootElement(selectorOrNode);
  40623. };
  40624. RendererAdapter.prototype.createElement = function (parent, namespaceAndName) {
  40625. var _a = __read(splitNamespace(namespaceAndName), 2), ns = _a[0], name = _a[1];
  40626. var el = this.delegate.createElement(name, ns);
  40627. if (parent) {
  40628. this.delegate.appendChild(parent, el);
  40629. }
  40630. return el;
  40631. };
  40632. RendererAdapter.prototype.createViewRoot = function (hostElement) { return hostElement; };
  40633. RendererAdapter.prototype.createTemplateAnchor = function (parentElement) {
  40634. var comment = this.delegate.createComment('');
  40635. if (parentElement) {
  40636. this.delegate.appendChild(parentElement, comment);
  40637. }
  40638. return comment;
  40639. };
  40640. RendererAdapter.prototype.createText = function (parentElement, value) {
  40641. var node = this.delegate.createText(value);
  40642. if (parentElement) {
  40643. this.delegate.appendChild(parentElement, node);
  40644. }
  40645. return node;
  40646. };
  40647. RendererAdapter.prototype.projectNodes = function (parentElement, nodes) {
  40648. for (var i = 0; i < nodes.length; i++) {
  40649. this.delegate.appendChild(parentElement, nodes[i]);
  40650. }
  40651. };
  40652. RendererAdapter.prototype.attachViewAfter = function (node, viewRootNodes) {
  40653. var parentElement = this.delegate.parentNode(node);
  40654. var nextSibling = this.delegate.nextSibling(node);
  40655. for (var i = 0; i < viewRootNodes.length; i++) {
  40656. this.delegate.insertBefore(parentElement, viewRootNodes[i], nextSibling);
  40657. }
  40658. };
  40659. RendererAdapter.prototype.detachView = function (viewRootNodes) {
  40660. for (var i = 0; i < viewRootNodes.length; i++) {
  40661. var node = viewRootNodes[i];
  40662. var parentElement = this.delegate.parentNode(node);
  40663. this.delegate.removeChild(parentElement, node);
  40664. }
  40665. };
  40666. RendererAdapter.prototype.destroyView = function (hostElement, viewAllNodes) {
  40667. for (var i = 0; i < viewAllNodes.length; i++) {
  40668. this.delegate.destroyNode(viewAllNodes[i]);
  40669. }
  40670. };
  40671. RendererAdapter.prototype.listen = function (renderElement, name, callback) {
  40672. return this.delegate.listen(renderElement, name, callback);
  40673. };
  40674. RendererAdapter.prototype.listenGlobal = function (target, name, callback) {
  40675. return this.delegate.listen(target, name, callback);
  40676. };
  40677. RendererAdapter.prototype.setElementProperty = function (renderElement, propertyName, propertyValue) {
  40678. this.delegate.setProperty(renderElement, propertyName, propertyValue);
  40679. };
  40680. RendererAdapter.prototype.setElementAttribute = function (renderElement, namespaceAndName, attributeValue) {
  40681. var _a = __read(splitNamespace(namespaceAndName), 2), ns = _a[0], name = _a[1];
  40682. if (attributeValue != null) {
  40683. this.delegate.setAttribute(renderElement, name, attributeValue, ns);
  40684. }
  40685. else {
  40686. this.delegate.removeAttribute(renderElement, name, ns);
  40687. }
  40688. };
  40689. RendererAdapter.prototype.setBindingDebugInfo = function (renderElement, propertyName, propertyValue) { };
  40690. RendererAdapter.prototype.setElementClass = function (renderElement, className, isAdd) {
  40691. if (isAdd) {
  40692. this.delegate.addClass(renderElement, className);
  40693. }
  40694. else {
  40695. this.delegate.removeClass(renderElement, className);
  40696. }
  40697. };
  40698. RendererAdapter.prototype.setElementStyle = function (renderElement, styleName, styleValue) {
  40699. if (styleValue != null) {
  40700. this.delegate.setStyle(renderElement, styleName, styleValue);
  40701. }
  40702. else {
  40703. this.delegate.removeStyle(renderElement, styleName);
  40704. }
  40705. };
  40706. RendererAdapter.prototype.invokeElementMethod = function (renderElement, methodName, args) {
  40707. renderElement[methodName].apply(renderElement, args);
  40708. };
  40709. RendererAdapter.prototype.setText = function (renderNode, text) { this.delegate.setValue(renderNode, text); };
  40710. RendererAdapter.prototype.animate = function () { throw new Error('Renderer.animate is no longer supported!'); };
  40711. return RendererAdapter;
  40712. }());
  40713. function createNgModuleRef(moduleType, parent, bootstrapComponents, def) {
  40714. return new NgModuleRef_(moduleType, parent, bootstrapComponents, def);
  40715. }
  40716. var NgModuleRef_ = /** @class */ (function () {
  40717. function NgModuleRef_(_moduleType, _parent, _bootstrapComponents, _def) {
  40718. this._moduleType = _moduleType;
  40719. this._parent = _parent;
  40720. this._bootstrapComponents = _bootstrapComponents;
  40721. this._def = _def;
  40722. this._destroyListeners = [];
  40723. this._destroyed = false;
  40724. this.injector = this;
  40725. initNgModule(this);
  40726. }
  40727. NgModuleRef_.prototype.get = function (token, notFoundValue, injectFlags) {
  40728. if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
  40729. if (injectFlags === void 0) { injectFlags = InjectFlags.Default; }
  40730. var flags = 0 /* None */;
  40731. if (injectFlags & InjectFlags.SkipSelf) {
  40732. flags |= 1 /* SkipSelf */;
  40733. }
  40734. else if (injectFlags & InjectFlags.Self) {
  40735. flags |= 4 /* Self */;
  40736. }
  40737. return resolveNgModuleDep(this, { token: token, tokenKey: tokenKey(token), flags: flags }, notFoundValue);
  40738. };
  40739. Object.defineProperty(NgModuleRef_.prototype, "instance", {
  40740. get: function () { return this.get(this._moduleType); },
  40741. enumerable: true,
  40742. configurable: true
  40743. });
  40744. Object.defineProperty(NgModuleRef_.prototype, "componentFactoryResolver", {
  40745. get: function () { return this.get(ComponentFactoryResolver); },
  40746. enumerable: true,
  40747. configurable: true
  40748. });
  40749. NgModuleRef_.prototype.destroy = function () {
  40750. if (this._destroyed) {
  40751. throw new Error("The ng module " + stringify$1(this.instance.constructor) + " has already been destroyed.");
  40752. }
  40753. this._destroyed = true;
  40754. callNgModuleLifecycle(this, 131072 /* OnDestroy */);
  40755. this._destroyListeners.forEach(function (listener) { return listener(); });
  40756. };
  40757. NgModuleRef_.prototype.onDestroy = function (callback) { this._destroyListeners.push(callback); };
  40758. return NgModuleRef_;
  40759. }());
  40760. /**
  40761. * @license
  40762. * Copyright Google Inc. All Rights Reserved.
  40763. *
  40764. * Use of this source code is governed by an MIT-style license that can be
  40765. * found in the LICENSE file at https://angular.io/license
  40766. */
  40767. var RendererV1TokenKey = tokenKey(Renderer);
  40768. var Renderer2TokenKey = tokenKey(Renderer2);
  40769. var ElementRefTokenKey = tokenKey(ElementRef);
  40770. var ViewContainerRefTokenKey = tokenKey(ViewContainerRef);
  40771. var TemplateRefTokenKey = tokenKey(TemplateRef);
  40772. var ChangeDetectorRefTokenKey = tokenKey(ChangeDetectorRef);
  40773. var InjectorRefTokenKey$1 = tokenKey(Injector);
  40774. var INJECTORRefTokenKey$1 = tokenKey(INJECTOR);
  40775. function createProviderInstance(view, def) {
  40776. return _createProviderInstance$1(view, def);
  40777. }
  40778. function createPipeInstance(view, def) {
  40779. // deps are looked up from component.
  40780. var compView = view;
  40781. while (compView.parent && !isComponentView(compView)) {
  40782. compView = compView.parent;
  40783. }
  40784. // pipes can see the private services of the component
  40785. var allowPrivateServices = true;
  40786. // pipes are always eager and classes!
  40787. return createClass(compView.parent, viewParentEl(compView), allowPrivateServices, def.provider.value, def.provider.deps);
  40788. }
  40789. function createDirectiveInstance(view, def) {
  40790. // components can see other private services, other directives can't.
  40791. var allowPrivateServices = (def.flags & 32768 /* Component */) > 0;
  40792. // directives are always eager and classes!
  40793. var instance = createClass(view, def.parent, allowPrivateServices, def.provider.value, def.provider.deps);
  40794. if (def.outputs.length) {
  40795. for (var i = 0; i < def.outputs.length; i++) {
  40796. var output = def.outputs[i];
  40797. var outputObservable = instance[output.propName];
  40798. if (isObservable(outputObservable)) {
  40799. var subscription = outputObservable.subscribe(eventHandlerClosure(view, def.parent.nodeIndex, output.eventName));
  40800. view.disposables[def.outputIndex + i] = subscription.unsubscribe.bind(subscription);
  40801. }
  40802. else {
  40803. throw new Error("@Output " + output.propName + " not initialized in '" + instance.constructor.name + "'.");
  40804. }
  40805. }
  40806. }
  40807. return instance;
  40808. }
  40809. function eventHandlerClosure(view, index, eventName) {
  40810. return function (event) { return dispatchEvent(view, index, eventName, event); };
  40811. }
  40812. function checkAndUpdateDirectiveInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  40813. var providerData = asProviderData(view, def.nodeIndex);
  40814. var directive = providerData.instance;
  40815. var changed = false;
  40816. var changes = undefined;
  40817. var bindLen = def.bindings.length;
  40818. if (bindLen > 0 && checkBinding(view, def, 0, v0)) {
  40819. changed = true;
  40820. changes = updateProp(view, providerData, def, 0, v0, changes);
  40821. }
  40822. if (bindLen > 1 && checkBinding(view, def, 1, v1)) {
  40823. changed = true;
  40824. changes = updateProp(view, providerData, def, 1, v1, changes);
  40825. }
  40826. if (bindLen > 2 && checkBinding(view, def, 2, v2)) {
  40827. changed = true;
  40828. changes = updateProp(view, providerData, def, 2, v2, changes);
  40829. }
  40830. if (bindLen > 3 && checkBinding(view, def, 3, v3)) {
  40831. changed = true;
  40832. changes = updateProp(view, providerData, def, 3, v3, changes);
  40833. }
  40834. if (bindLen > 4 && checkBinding(view, def, 4, v4)) {
  40835. changed = true;
  40836. changes = updateProp(view, providerData, def, 4, v4, changes);
  40837. }
  40838. if (bindLen > 5 && checkBinding(view, def, 5, v5)) {
  40839. changed = true;
  40840. changes = updateProp(view, providerData, def, 5, v5, changes);
  40841. }
  40842. if (bindLen > 6 && checkBinding(view, def, 6, v6)) {
  40843. changed = true;
  40844. changes = updateProp(view, providerData, def, 6, v6, changes);
  40845. }
  40846. if (bindLen > 7 && checkBinding(view, def, 7, v7)) {
  40847. changed = true;
  40848. changes = updateProp(view, providerData, def, 7, v7, changes);
  40849. }
  40850. if (bindLen > 8 && checkBinding(view, def, 8, v8)) {
  40851. changed = true;
  40852. changes = updateProp(view, providerData, def, 8, v8, changes);
  40853. }
  40854. if (bindLen > 9 && checkBinding(view, def, 9, v9)) {
  40855. changed = true;
  40856. changes = updateProp(view, providerData, def, 9, v9, changes);
  40857. }
  40858. if (changes) {
  40859. directive.ngOnChanges(changes);
  40860. }
  40861. if ((def.flags & 65536 /* OnInit */) &&
  40862. shouldCallLifecycleInitHook(view, 256 /* InitState_CallingOnInit */, def.nodeIndex)) {
  40863. directive.ngOnInit();
  40864. }
  40865. if (def.flags & 262144 /* DoCheck */) {
  40866. directive.ngDoCheck();
  40867. }
  40868. return changed;
  40869. }
  40870. function checkAndUpdateDirectiveDynamic(view, def, values) {
  40871. var providerData = asProviderData(view, def.nodeIndex);
  40872. var directive = providerData.instance;
  40873. var changed = false;
  40874. var changes = undefined;
  40875. for (var i = 0; i < values.length; i++) {
  40876. if (checkBinding(view, def, i, values[i])) {
  40877. changed = true;
  40878. changes = updateProp(view, providerData, def, i, values[i], changes);
  40879. }
  40880. }
  40881. if (changes) {
  40882. directive.ngOnChanges(changes);
  40883. }
  40884. if ((def.flags & 65536 /* OnInit */) &&
  40885. shouldCallLifecycleInitHook(view, 256 /* InitState_CallingOnInit */, def.nodeIndex)) {
  40886. directive.ngOnInit();
  40887. }
  40888. if (def.flags & 262144 /* DoCheck */) {
  40889. directive.ngDoCheck();
  40890. }
  40891. return changed;
  40892. }
  40893. function _createProviderInstance$1(view, def) {
  40894. // private services can see other private services
  40895. var allowPrivateServices = (def.flags & 8192 /* PrivateProvider */) > 0;
  40896. var providerDef = def.provider;
  40897. switch (def.flags & 201347067 /* Types */) {
  40898. case 512 /* TypeClassProvider */:
  40899. return createClass(view, def.parent, allowPrivateServices, providerDef.value, providerDef.deps);
  40900. case 1024 /* TypeFactoryProvider */:
  40901. return callFactory(view, def.parent, allowPrivateServices, providerDef.value, providerDef.deps);
  40902. case 2048 /* TypeUseExistingProvider */:
  40903. return resolveDep(view, def.parent, allowPrivateServices, providerDef.deps[0]);
  40904. case 256 /* TypeValueProvider */:
  40905. return providerDef.value;
  40906. }
  40907. }
  40908. function createClass(view, elDef, allowPrivateServices, ctor, deps) {
  40909. var len = deps.length;
  40910. switch (len) {
  40911. case 0:
  40912. return new ctor();
  40913. case 1:
  40914. return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]));
  40915. case 2:
  40916. return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
  40917. case 3:
  40918. return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
  40919. default:
  40920. var depValues = new Array(len);
  40921. for (var i = 0; i < len; i++) {
  40922. depValues[i] = resolveDep(view, elDef, allowPrivateServices, deps[i]);
  40923. }
  40924. return new (ctor.bind.apply(ctor, __spread([void 0], depValues)))();
  40925. }
  40926. }
  40927. function callFactory(view, elDef, allowPrivateServices, factory, deps) {
  40928. var len = deps.length;
  40929. switch (len) {
  40930. case 0:
  40931. return factory();
  40932. case 1:
  40933. return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]));
  40934. case 2:
  40935. return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
  40936. case 3:
  40937. return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
  40938. default:
  40939. var depValues = Array(len);
  40940. for (var i = 0; i < len; i++) {
  40941. depValues[i] = resolveDep(view, elDef, allowPrivateServices, deps[i]);
  40942. }
  40943. return factory.apply(void 0, __spread(depValues));
  40944. }
  40945. }
  40946. // This default value is when checking the hierarchy for a token.
  40947. //
  40948. // It means both:
  40949. // - the token is not provided by the current injector,
  40950. // - only the element injectors should be checked (ie do not check module injectors
  40951. //
  40952. // mod1
  40953. // /
  40954. // el1 mod2
  40955. // \ /
  40956. // el2
  40957. //
  40958. // When requesting el2.injector.get(token), we should check in the following order and return the
  40959. // first found value:
  40960. // - el2.injector.get(token, default)
  40961. // - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
  40962. // - mod2.injector.get(token, default)
  40963. var NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
  40964. function resolveDep(view, elDef, allowPrivateServices, depDef, notFoundValue) {
  40965. if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
  40966. if (depDef.flags & 8 /* Value */) {
  40967. return depDef.token;
  40968. }
  40969. var startView = view;
  40970. if (depDef.flags & 2 /* Optional */) {
  40971. notFoundValue = null;
  40972. }
  40973. var tokenKey = depDef.tokenKey;
  40974. if (tokenKey === ChangeDetectorRefTokenKey) {
  40975. // directives on the same element as a component should be able to control the change detector
  40976. // of that component as well.
  40977. allowPrivateServices = !!(elDef && elDef.element.componentView);
  40978. }
  40979. if (elDef && (depDef.flags & 1 /* SkipSelf */)) {
  40980. allowPrivateServices = false;
  40981. elDef = elDef.parent;
  40982. }
  40983. var searchView = view;
  40984. while (searchView) {
  40985. if (elDef) {
  40986. switch (tokenKey) {
  40987. case RendererV1TokenKey: {
  40988. var compView = findCompView(searchView, elDef, allowPrivateServices);
  40989. return createRendererV1(compView);
  40990. }
  40991. case Renderer2TokenKey: {
  40992. var compView = findCompView(searchView, elDef, allowPrivateServices);
  40993. return compView.renderer;
  40994. }
  40995. case ElementRefTokenKey:
  40996. return new ElementRef(asElementData(searchView, elDef.nodeIndex).renderElement);
  40997. case ViewContainerRefTokenKey:
  40998. return asElementData(searchView, elDef.nodeIndex).viewContainer;
  40999. case TemplateRefTokenKey: {
  41000. if (elDef.element.template) {
  41001. return asElementData(searchView, elDef.nodeIndex).template;
  41002. }
  41003. break;
  41004. }
  41005. case ChangeDetectorRefTokenKey: {
  41006. var cdView = findCompView(searchView, elDef, allowPrivateServices);
  41007. return createChangeDetectorRef(cdView);
  41008. }
  41009. case InjectorRefTokenKey$1:
  41010. case INJECTORRefTokenKey$1:
  41011. return createInjector$1(searchView, elDef);
  41012. default:
  41013. var providerDef_1 = (allowPrivateServices ? elDef.element.allProviders :
  41014. elDef.element.publicProviders)[tokenKey];
  41015. if (providerDef_1) {
  41016. var providerData = asProviderData(searchView, providerDef_1.nodeIndex);
  41017. if (!providerData) {
  41018. providerData = { instance: _createProviderInstance$1(searchView, providerDef_1) };
  41019. searchView.nodes[providerDef_1.nodeIndex] = providerData;
  41020. }
  41021. return providerData.instance;
  41022. }
  41023. }
  41024. }
  41025. allowPrivateServices = isComponentView(searchView);
  41026. elDef = viewParentEl(searchView);
  41027. searchView = searchView.parent;
  41028. if (depDef.flags & 4 /* Self */) {
  41029. searchView = null;
  41030. }
  41031. }
  41032. var value = startView.root.injector.get(depDef.token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR);
  41033. if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
  41034. notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
  41035. // Return the value from the root element injector when
  41036. // - it provides it
  41037. // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  41038. // - the module injector should not be checked
  41039. // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  41040. return value;
  41041. }
  41042. return startView.root.ngModule.injector.get(depDef.token, notFoundValue);
  41043. }
  41044. function findCompView(view, elDef, allowPrivateServices) {
  41045. var compView;
  41046. if (allowPrivateServices) {
  41047. compView = asElementData(view, elDef.nodeIndex).componentView;
  41048. }
  41049. else {
  41050. compView = view;
  41051. while (compView.parent && !isComponentView(compView)) {
  41052. compView = compView.parent;
  41053. }
  41054. }
  41055. return compView;
  41056. }
  41057. function updateProp(view, providerData, def, bindingIdx, value, changes) {
  41058. if (def.flags & 32768 /* Component */) {
  41059. var compView = asElementData(view, def.parent.nodeIndex).componentView;
  41060. if (compView.def.flags & 2 /* OnPush */) {
  41061. compView.state |= 8 /* ChecksEnabled */;
  41062. }
  41063. }
  41064. var binding = def.bindings[bindingIdx];
  41065. var propName = binding.name;
  41066. // Note: This is still safe with Closure Compiler as
  41067. // the user passed in the property name as an object has to `providerDef`,
  41068. // so Closure Compiler will have renamed the property correctly already.
  41069. providerData.instance[propName] = value;
  41070. if (def.flags & 524288 /* OnChanges */) {
  41071. changes = changes || {};
  41072. var oldValue = WrappedValue.unwrap(view.oldValues[def.bindingIndex + bindingIdx]);
  41073. var binding_1 = def.bindings[bindingIdx];
  41074. changes[binding_1.nonMinifiedName] =
  41075. new SimpleChange(oldValue, value, (view.state & 2 /* FirstCheck */) !== 0);
  41076. }
  41077. view.oldValues[def.bindingIndex + bindingIdx] = value;
  41078. return changes;
  41079. }
  41080. // This function calls the ngAfterContentCheck, ngAfterContentInit,
  41081. // ngAfterViewCheck, and ngAfterViewInit lifecycle hooks (depending on the node
  41082. // flags in lifecycle). Unlike ngDoCheck, ngOnChanges and ngOnInit, which are
  41083. // called during a pre-order traversal of the view tree (that is calling the
  41084. // parent hooks before the child hooks) these events are sent in using a
  41085. // post-order traversal of the tree (children before parents). This changes the
  41086. // meaning of initIndex in the view state. For ngOnInit, initIndex tracks the
  41087. // expected nodeIndex which a ngOnInit should be called. When sending
  41088. // ngAfterContentInit and ngAfterViewInit it is the expected count of
  41089. // ngAfterContentInit or ngAfterViewInit methods that have been called. This
  41090. // ensure that despite being called recursively or after picking up after an
  41091. // exception, the ngAfterContentInit or ngAfterViewInit will be called on the
  41092. // correct nodes. Consider for example, the following (where E is an element
  41093. // and D is a directive)
  41094. // Tree: pre-order index post-order index
  41095. // E1 0 6
  41096. // E2 1 1
  41097. // D3 2 0
  41098. // E4 3 5
  41099. // E5 4 4
  41100. // E6 5 2
  41101. // E7 6 3
  41102. // As can be seen, the post-order index has an unclear relationship to the
  41103. // pre-order index (postOrderIndex === preOrderIndex - parentCount +
  41104. // childCount). Since number of calls to ngAfterContentInit and ngAfterViewInit
  41105. // are stable (will be the same for the same view regardless of exceptions or
  41106. // recursion) we just need to count them which will roughly correspond to the
  41107. // post-order index (it skips elements and directives that do not have
  41108. // lifecycle hooks).
  41109. //
  41110. // For example, if an exception is raised in the E6.onAfterViewInit() the
  41111. // initIndex is left at 3 (by shouldCallLifecycleInitHook() which set it to
  41112. // initIndex + 1). When checkAndUpdateView() is called again D3, E2 and E6 will
  41113. // not have their ngAfterViewInit() called but, starting with E7, the rest of
  41114. // the view will begin getting ngAfterViewInit() called until a check and
  41115. // pass is complete.
  41116. //
  41117. // This algorthim also handles recursion. Consider if E4's ngAfterViewInit()
  41118. // indirectly calls E1's ChangeDetectorRef.detectChanges(). The expected
  41119. // initIndex is set to 6, the recusive checkAndUpdateView() starts walk again.
  41120. // D3, E2, E6, E7, E5 and E4 are skipped, ngAfterViewInit() is called on E1.
  41121. // When the recursion returns the initIndex will be 7 so E1 is skipped as it
  41122. // has already been called in the recursively called checkAnUpdateView().
  41123. function callLifecycleHooksChildrenFirst(view, lifecycles) {
  41124. if (!(view.def.nodeFlags & lifecycles)) {
  41125. return;
  41126. }
  41127. var nodes = view.def.nodes;
  41128. var initIndex = 0;
  41129. for (var i = 0; i < nodes.length; i++) {
  41130. var nodeDef = nodes[i];
  41131. var parent_1 = nodeDef.parent;
  41132. if (!parent_1 && nodeDef.flags & lifecycles) {
  41133. // matching root node (e.g. a pipe)
  41134. callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
  41135. }
  41136. if ((nodeDef.childFlags & lifecycles) === 0) {
  41137. // no child matches one of the lifecycles
  41138. i += nodeDef.childCount;
  41139. }
  41140. while (parent_1 && (parent_1.flags & 1 /* TypeElement */) &&
  41141. i === parent_1.nodeIndex + parent_1.childCount) {
  41142. // last child of an element
  41143. if (parent_1.directChildFlags & lifecycles) {
  41144. initIndex = callElementProvidersLifecycles(view, parent_1, lifecycles, initIndex);
  41145. }
  41146. parent_1 = parent_1.parent;
  41147. }
  41148. }
  41149. }
  41150. function callElementProvidersLifecycles(view, elDef, lifecycles, initIndex) {
  41151. for (var i = elDef.nodeIndex + 1; i <= elDef.nodeIndex + elDef.childCount; i++) {
  41152. var nodeDef = view.def.nodes[i];
  41153. if (nodeDef.flags & lifecycles) {
  41154. callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
  41155. }
  41156. // only visit direct children
  41157. i += nodeDef.childCount;
  41158. }
  41159. return initIndex;
  41160. }
  41161. function callProviderLifecycles(view, index, lifecycles, initIndex) {
  41162. var providerData = asProviderData(view, index);
  41163. if (!providerData) {
  41164. return;
  41165. }
  41166. var provider = providerData.instance;
  41167. if (!provider) {
  41168. return;
  41169. }
  41170. Services.setCurrentNode(view, index);
  41171. if (lifecycles & 1048576 /* AfterContentInit */ &&
  41172. shouldCallLifecycleInitHook(view, 512 /* InitState_CallingAfterContentInit */, initIndex)) {
  41173. provider.ngAfterContentInit();
  41174. }
  41175. if (lifecycles & 2097152 /* AfterContentChecked */) {
  41176. provider.ngAfterContentChecked();
  41177. }
  41178. if (lifecycles & 4194304 /* AfterViewInit */ &&
  41179. shouldCallLifecycleInitHook(view, 768 /* InitState_CallingAfterViewInit */, initIndex)) {
  41180. provider.ngAfterViewInit();
  41181. }
  41182. if (lifecycles & 8388608 /* AfterViewChecked */) {
  41183. provider.ngAfterViewChecked();
  41184. }
  41185. if (lifecycles & 131072 /* OnDestroy */) {
  41186. provider.ngOnDestroy();
  41187. }
  41188. }
  41189. /**
  41190. * @license
  41191. * Copyright Google Inc. All Rights Reserved.
  41192. *
  41193. * Use of this source code is governed by an MIT-style license that can be
  41194. * found in the LICENSE file at https://angular.io/license
  41195. */
  41196. var ComponentFactoryResolver$1 = /** @class */ (function (_super) {
  41197. __extends(ComponentFactoryResolver, _super);
  41198. /**
  41199. * @param ngModule The NgModuleRef to which all resolved factories are bound.
  41200. */
  41201. function ComponentFactoryResolver(ngModule) {
  41202. var _this = _super.call(this) || this;
  41203. _this.ngModule = ngModule;
  41204. return _this;
  41205. }
  41206. ComponentFactoryResolver.prototype.resolveComponentFactory = function (component) {
  41207. ngDevMode && assertComponentType(component);
  41208. var componentDef = getComponentDef(component);
  41209. return new ComponentFactory$1(componentDef, this.ngModule);
  41210. };
  41211. return ComponentFactoryResolver;
  41212. }(ComponentFactoryResolver));
  41213. function toRefArray(map) {
  41214. var array = [];
  41215. for (var nonMinified in map) {
  41216. if (map.hasOwnProperty(nonMinified)) {
  41217. var minified = map[nonMinified];
  41218. array.push({ propName: minified, templateName: nonMinified });
  41219. }
  41220. }
  41221. return array;
  41222. }
  41223. /**
  41224. * Default {@link RootContext} for all components rendered with {@link renderComponent}.
  41225. */
  41226. var ROOT_CONTEXT = new InjectionToken('ROOT_CONTEXT_TOKEN', { providedIn: 'root', factory: function () { return createRootContext(ɵɵinject(SCHEDULER)); } });
  41227. /**
  41228. * A change detection scheduler token for {@link RootContext}. This token is the default value used
  41229. * for the default `RootContext` found in the {@link ROOT_CONTEXT} token.
  41230. */
  41231. var SCHEDULER = new InjectionToken('SCHEDULER_TOKEN', {
  41232. providedIn: 'root',
  41233. factory: function () { return defaultScheduler; },
  41234. });
  41235. function createChainedInjector(rootViewInjector, moduleInjector) {
  41236. return {
  41237. get: function (token, notFoundValue, flags) {
  41238. var value = rootViewInjector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags);
  41239. if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
  41240. notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
  41241. // Return the value from the root element injector when
  41242. // - it provides it
  41243. // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  41244. // - the module injector should not be checked
  41245. // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  41246. return value;
  41247. }
  41248. return moduleInjector.get(token, notFoundValue, flags);
  41249. }
  41250. };
  41251. }
  41252. /**
  41253. * Render3 implementation of {@link viewEngine_ComponentFactory}.
  41254. */
  41255. var ComponentFactory$1 = /** @class */ (function (_super) {
  41256. __extends(ComponentFactory, _super);
  41257. /**
  41258. * @param componentDef The component definition.
  41259. * @param ngModule The NgModuleRef to which the factory is bound.
  41260. */
  41261. function ComponentFactory(componentDef, ngModule) {
  41262. var _this = _super.call(this) || this;
  41263. _this.componentDef = componentDef;
  41264. _this.ngModule = ngModule;
  41265. _this.componentType = componentDef.type;
  41266. _this.selector = componentDef.selectors[0][0];
  41267. _this.ngContentSelectors =
  41268. componentDef.ngContentSelectors ? componentDef.ngContentSelectors : [];
  41269. _this.isBoundToModule = !!ngModule;
  41270. return _this;
  41271. }
  41272. Object.defineProperty(ComponentFactory.prototype, "inputs", {
  41273. get: function () {
  41274. return toRefArray(this.componentDef.inputs);
  41275. },
  41276. enumerable: true,
  41277. configurable: true
  41278. });
  41279. Object.defineProperty(ComponentFactory.prototype, "outputs", {
  41280. get: function () {
  41281. return toRefArray(this.componentDef.outputs);
  41282. },
  41283. enumerable: true,
  41284. configurable: true
  41285. });
  41286. ComponentFactory.prototype.create = function (injector, projectableNodes, rootSelectorOrNode, ngModule) {
  41287. var isInternalRootView = rootSelectorOrNode === undefined;
  41288. ngModule = ngModule || this.ngModule;
  41289. var rootViewInjector = ngModule ? createChainedInjector(injector, ngModule.injector) : injector;
  41290. var rendererFactory = rootViewInjector.get(RendererFactory2, domRendererFactory3);
  41291. var sanitizer = rootViewInjector.get(Sanitizer, null);
  41292. var hostRNode = isInternalRootView ?
  41293. elementCreate(this.selector, rendererFactory.createRenderer(null, this.componentDef)) :
  41294. locateHostElement(rendererFactory, rootSelectorOrNode);
  41295. var rootFlags = this.componentDef.onPush ? 64 /* Dirty */ | 512 /* IsRoot */ :
  41296. 16 /* CheckAlways */ | 512 /* IsRoot */;
  41297. // Check whether this Component needs to be isolated from other components, i.e. whether it
  41298. // should be placed into its own (empty) root context or existing root context should be used.
  41299. // Note: this is internal-only convention and might change in the future, so it should not be
  41300. // relied upon externally.
  41301. var isIsolated = typeof rootSelectorOrNode === 'string' &&
  41302. /^#root-ng-internal-isolated-\d+/.test(rootSelectorOrNode);
  41303. var rootContext = (isInternalRootView || isIsolated) ?
  41304. createRootContext() :
  41305. rootViewInjector.get(ROOT_CONTEXT);
  41306. var renderer = rendererFactory.createRenderer(hostRNode, this.componentDef);
  41307. if (rootSelectorOrNode && hostRNode) {
  41308. ngDevMode && ngDevMode.rendererSetAttribute++;
  41309. isProceduralRenderer(renderer) ?
  41310. renderer.setAttribute(hostRNode, 'ng-version', VERSION$2.full) :
  41311. hostRNode.setAttribute('ng-version', VERSION$2.full);
  41312. }
  41313. // Create the root view. Uses empty TView and ContentTemplate.
  41314. var rootLView = createLView(null, createTView(-1, null, 1, 0, null, null, null, null), rootContext, rootFlags, null, null, rendererFactory, renderer, sanitizer, rootViewInjector);
  41315. // rootView is the parent when bootstrapping
  41316. var oldLView = enterView(rootLView, null);
  41317. var component;
  41318. var tElementNode;
  41319. // Will become true if the `try` block executes with no errors.
  41320. var safeToRunHooks = false;
  41321. try {
  41322. var componentView = createRootComponentView(hostRNode, this.componentDef, rootLView, rendererFactory, renderer);
  41323. tElementNode = getTNode(0, rootLView);
  41324. if (projectableNodes) {
  41325. // projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
  41326. // case). Here we do normalize passed data structure to be an array of arrays to avoid
  41327. // complex checks down the line.
  41328. tElementNode.projection =
  41329. projectableNodes.map(function (nodesforSlot) { return Array.from(nodesforSlot); });
  41330. }
  41331. // TODO: should LifecycleHooksFeature and other host features be generated by the compiler and
  41332. // executed here?
  41333. // Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref
  41334. component = createRootComponent(componentView, this.componentDef, rootLView, rootContext, [LifecycleHooksFeature]);
  41335. addToViewTree(rootLView, componentView);
  41336. refreshDescendantViews(rootLView);
  41337. safeToRunHooks = true;
  41338. }
  41339. finally {
  41340. leaveView(oldLView, safeToRunHooks);
  41341. }
  41342. var componentRef = new ComponentRef$1(this.componentType, component, createElementRef(ElementRef, tElementNode, rootLView), rootLView, tElementNode);
  41343. if (isInternalRootView) {
  41344. // The host element of the internal root view is attached to the component's host view node
  41345. componentRef.hostView._tViewNode.child = tElementNode;
  41346. }
  41347. return componentRef;
  41348. };
  41349. return ComponentFactory;
  41350. }(ComponentFactory));
  41351. var componentFactoryResolver = new ComponentFactoryResolver$1();
  41352. /**
  41353. * Represents an instance of a Component created via a {@link ComponentFactory}.
  41354. *
  41355. * `ComponentRef` provides access to the Component Instance as well other objects related to this
  41356. * Component Instance and allows you to destroy the Component Instance via the {@link #destroy}
  41357. * method.
  41358. *
  41359. */
  41360. var ComponentRef$1 = /** @class */ (function (_super) {
  41361. __extends(ComponentRef, _super);
  41362. function ComponentRef(componentType, instance, location, _rootLView, _tNode) {
  41363. var _this = _super.call(this) || this;
  41364. _this.location = location;
  41365. _this._rootLView = _rootLView;
  41366. _this._tNode = _tNode;
  41367. _this.destroyCbs = [];
  41368. _this.instance = instance;
  41369. _this.hostView = _this.changeDetectorRef = new RootViewRef(_rootLView);
  41370. _this.hostView._tViewNode = assignTViewNodeToLView(_rootLView[TVIEW], null, -1, _rootLView);
  41371. _this.componentType = componentType;
  41372. return _this;
  41373. }
  41374. Object.defineProperty(ComponentRef.prototype, "injector", {
  41375. get: function () { return new NodeInjector(this._tNode, this._rootLView); },
  41376. enumerable: true,
  41377. configurable: true
  41378. });
  41379. ComponentRef.prototype.destroy = function () {
  41380. if (this.destroyCbs) {
  41381. this.destroyCbs.forEach(function (fn) { return fn(); });
  41382. this.destroyCbs = null;
  41383. !this.hostView.destroyed && this.hostView.destroy();
  41384. }
  41385. };
  41386. ComponentRef.prototype.onDestroy = function (callback) {
  41387. if (this.destroyCbs) {
  41388. this.destroyCbs.push(callback);
  41389. }
  41390. };
  41391. return ComponentRef;
  41392. }(ComponentRef));
  41393. /**
  41394. * @license
  41395. * Copyright Google Inc. All Rights Reserved.
  41396. *
  41397. * Use of this source code is governed by an MIT-style license that can be
  41398. * found in the LICENSE file at https://angular.io/license
  41399. */
  41400. /**
  41401. * NOTE: changes to the `ngI18nClosureMode` name must be synced with `compiler-cli/src/tooling.ts`.
  41402. */
  41403. if (typeof ngI18nClosureMode === 'undefined') {
  41404. // These property accesses can be ignored because ngI18nClosureMode will be set to false
  41405. // when optimizing code and the whole if statement will be dropped.
  41406. // Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
  41407. // NOTE: we need to have it in IIFE so that the tree-shaker is happy.
  41408. (function () {
  41409. // tslint:disable-next-line:no-toplevel-property-access
  41410. _global$1['ngI18nClosureMode'] =
  41411. // TODO(FW-1250): validate that this actually, you know, works.
  41412. // tslint:disable-next-line:no-toplevel-property-access
  41413. typeof goog !== 'undefined' && typeof goog.getMsg === 'function';
  41414. })();
  41415. }
  41416. /**
  41417. * @license
  41418. * Copyright Google Inc. All Rights Reserved.
  41419. *
  41420. * Use of this source code is governed by an MIT-style license that can be
  41421. * found in the LICENSE file at https://angular.io/license
  41422. */
  41423. /**
  41424. * Index of each type of locale data from the locale data array
  41425. */
  41426. var LocaleDataIndex;
  41427. (function (LocaleDataIndex) {
  41428. LocaleDataIndex[LocaleDataIndex["LocaleId"] = 0] = "LocaleId";
  41429. LocaleDataIndex[LocaleDataIndex["DayPeriodsFormat"] = 1] = "DayPeriodsFormat";
  41430. LocaleDataIndex[LocaleDataIndex["DayPeriodsStandalone"] = 2] = "DayPeriodsStandalone";
  41431. LocaleDataIndex[LocaleDataIndex["DaysFormat"] = 3] = "DaysFormat";
  41432. LocaleDataIndex[LocaleDataIndex["DaysStandalone"] = 4] = "DaysStandalone";
  41433. LocaleDataIndex[LocaleDataIndex["MonthsFormat"] = 5] = "MonthsFormat";
  41434. LocaleDataIndex[LocaleDataIndex["MonthsStandalone"] = 6] = "MonthsStandalone";
  41435. LocaleDataIndex[LocaleDataIndex["Eras"] = 7] = "Eras";
  41436. LocaleDataIndex[LocaleDataIndex["FirstDayOfWeek"] = 8] = "FirstDayOfWeek";
  41437. LocaleDataIndex[LocaleDataIndex["WeekendRange"] = 9] = "WeekendRange";
  41438. LocaleDataIndex[LocaleDataIndex["DateFormat"] = 10] = "DateFormat";
  41439. LocaleDataIndex[LocaleDataIndex["TimeFormat"] = 11] = "TimeFormat";
  41440. LocaleDataIndex[LocaleDataIndex["DateTimeFormat"] = 12] = "DateTimeFormat";
  41441. LocaleDataIndex[LocaleDataIndex["NumberSymbols"] = 13] = "NumberSymbols";
  41442. LocaleDataIndex[LocaleDataIndex["NumberFormats"] = 14] = "NumberFormats";
  41443. LocaleDataIndex[LocaleDataIndex["CurrencySymbol"] = 15] = "CurrencySymbol";
  41444. LocaleDataIndex[LocaleDataIndex["CurrencyName"] = 16] = "CurrencyName";
  41445. LocaleDataIndex[LocaleDataIndex["Currencies"] = 17] = "Currencies";
  41446. LocaleDataIndex[LocaleDataIndex["PluralCase"] = 18] = "PluralCase";
  41447. LocaleDataIndex[LocaleDataIndex["ExtraData"] = 19] = "ExtraData";
  41448. })(LocaleDataIndex || (LocaleDataIndex = {}));
  41449. /**
  41450. * @license
  41451. * Copyright Google Inc. All Rights Reserved.
  41452. *
  41453. * Use of this source code is governed by an MIT-style license that can be
  41454. * found in the LICENSE file at https://angular.io/license
  41455. */
  41456. /**
  41457. * @license
  41458. * Copyright Google Inc. All Rights Reserved.
  41459. *
  41460. * Use of this source code is governed by an MIT-style license that can be
  41461. * found in the LICENSE file at https://angular.io/license
  41462. */
  41463. /**
  41464. * @license
  41465. * Copyright Google Inc. All Rights Reserved.
  41466. *
  41467. * Use of this source code is governed by an MIT-style license that can be
  41468. * found in the LICENSE file at https://angular.io/license
  41469. */
  41470. /**
  41471. * @license
  41472. * Copyright Google Inc. All Rights Reserved.
  41473. *
  41474. * Use of this source code is governed by an MIT-style license that can be
  41475. * found in the LICENSE file at https://angular.io/license
  41476. */
  41477. /**
  41478. * Flattens an array.
  41479. */
  41480. function flatten$2(list, dst) {
  41481. if (dst === undefined)
  41482. dst = list;
  41483. for (var i = 0; i < list.length; i++) {
  41484. var item = list[i];
  41485. if (Array.isArray(item)) {
  41486. // we need to inline it.
  41487. if (dst === list) {
  41488. // Our assumption that the list was already flat was wrong and
  41489. // we need to clone flat since we need to write to it.
  41490. dst = list.slice(0, i);
  41491. }
  41492. flatten$2(item, dst);
  41493. }
  41494. else if (dst !== list) {
  41495. dst.push(item);
  41496. }
  41497. }
  41498. return dst;
  41499. }
  41500. /**
  41501. * @license
  41502. * Copyright Google Inc. All Rights Reserved.
  41503. *
  41504. * Use of this source code is governed by an MIT-style license that can be
  41505. * found in the LICENSE file at https://angular.io/license
  41506. */
  41507. /**
  41508. * The locale id that the application is currently using (for translations and ICU expressions).
  41509. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  41510. * but is now defined as a global value.
  41511. */
  41512. var DEFAULT_LOCALE_ID = 'en-US';
  41513. var LOCALE_ID = DEFAULT_LOCALE_ID;
  41514. /**
  41515. * Sets the locale id that will be used for translations and ICU expressions.
  41516. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  41517. * but is now defined as a global value.
  41518. *
  41519. * @param localeId
  41520. */
  41521. function setLocaleId(localeId) {
  41522. LOCALE_ID = localeId.toLowerCase().replace(/_/g, '-');
  41523. }
  41524. /**
  41525. * @license
  41526. * Copyright Google Inc. All Rights Reserved.
  41527. *
  41528. * Use of this source code is governed by an MIT-style license that can be
  41529. * found in the LICENSE file at https://angular.io/license
  41530. */
  41531. /**
  41532. * Map of module-id to the corresponding NgModule.
  41533. * - In pre Ivy we track NgModuleFactory,
  41534. * - In post Ivy we track the NgModuleType
  41535. */
  41536. var modules = new Map();
  41537. function assertSameOrNotExisting(id, type, incoming) {
  41538. if (type && type !== incoming) {
  41539. throw new Error("Duplicate module registered for " + id + " - " + stringify$1(type) + " vs " + stringify$1(type.name));
  41540. }
  41541. }
  41542. function registerNgModuleType(ngModuleType) {
  41543. if (ngModuleType.ngModuleDef.id !== null) {
  41544. var id = ngModuleType.ngModuleDef.id;
  41545. var existing = modules.get(id);
  41546. assertSameOrNotExisting(id, existing, ngModuleType);
  41547. modules.set(id, ngModuleType);
  41548. }
  41549. var imports = ngModuleType.ngModuleDef.imports;
  41550. if (imports instanceof Function) {
  41551. imports = imports();
  41552. }
  41553. if (imports) {
  41554. imports.forEach(function (i) { return registerNgModuleType(i); });
  41555. }
  41556. }
  41557. /**
  41558. * @license
  41559. * Copyright Google Inc. All Rights Reserved.
  41560. *
  41561. * Use of this source code is governed by an MIT-style license that can be
  41562. * found in the LICENSE file at https://angular.io/license
  41563. */
  41564. var COMPONENT_FACTORY_RESOLVER = {
  41565. provide: ComponentFactoryResolver,
  41566. useClass: ComponentFactoryResolver$1,
  41567. deps: [NgModuleRef],
  41568. };
  41569. var NgModuleRef$1 = /** @class */ (function (_super) {
  41570. __extends(NgModuleRef$1, _super);
  41571. function NgModuleRef$1(ngModuleType, _parent) {
  41572. var _this = _super.call(this) || this;
  41573. _this._parent = _parent;
  41574. // tslint:disable-next-line:require-internal-with-underscore
  41575. _this._bootstrapComponents = [];
  41576. _this.injector = _this;
  41577. _this.destroyCbs = [];
  41578. var ngModuleDef = getNgModuleDef(ngModuleType);
  41579. ngDevMode && assertDefined(ngModuleDef, "NgModule '" + stringify$1(ngModuleType) + "' is not a subtype of 'NgModuleType'.");
  41580. var ngLocaleIdDef = getNgLocaleIdDef(ngModuleType);
  41581. if (ngLocaleIdDef) {
  41582. setLocaleId(ngLocaleIdDef);
  41583. }
  41584. _this._bootstrapComponents = maybeUnwrapFn(ngModuleDef.bootstrap);
  41585. var additionalProviders = [
  41586. {
  41587. provide: NgModuleRef,
  41588. useValue: _this,
  41589. },
  41590. COMPONENT_FACTORY_RESOLVER
  41591. ];
  41592. _this._r3Injector = createInjector(ngModuleType, _parent, additionalProviders, stringify$1(ngModuleType));
  41593. _this.instance = _this.get(ngModuleType);
  41594. return _this;
  41595. }
  41596. NgModuleRef$1.prototype.get = function (token, notFoundValue, injectFlags) {
  41597. if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; }
  41598. if (injectFlags === void 0) { injectFlags = InjectFlags.Default; }
  41599. if (token === Injector || token === NgModuleRef || token === INJECTOR) {
  41600. return this;
  41601. }
  41602. return this._r3Injector.get(token, notFoundValue, injectFlags);
  41603. };
  41604. Object.defineProperty(NgModuleRef$1.prototype, "componentFactoryResolver", {
  41605. get: function () {
  41606. return this.get(ComponentFactoryResolver);
  41607. },
  41608. enumerable: true,
  41609. configurable: true
  41610. });
  41611. NgModuleRef$1.prototype.destroy = function () {
  41612. ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
  41613. var injector = this._r3Injector;
  41614. !injector.destroyed && injector.destroy();
  41615. this.destroyCbs.forEach(function (fn) { return fn(); });
  41616. this.destroyCbs = null;
  41617. };
  41618. NgModuleRef$1.prototype.onDestroy = function (callback) {
  41619. ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
  41620. this.destroyCbs.push(callback);
  41621. };
  41622. return NgModuleRef$1;
  41623. }(NgModuleRef));
  41624. var NgModuleFactory$1 = /** @class */ (function (_super) {
  41625. __extends(NgModuleFactory, _super);
  41626. function NgModuleFactory(moduleType) {
  41627. var _this = _super.call(this) || this;
  41628. _this.moduleType = moduleType;
  41629. var ngModuleDef = getNgModuleDef(moduleType);
  41630. if (ngModuleDef !== null) {
  41631. // Register the NgModule with Angular's module registry. The location (and hence timing) of
  41632. // this call is critical to ensure this works correctly (modules get registered when expected)
  41633. // without bloating bundles (modules are registered when otherwise not referenced).
  41634. //
  41635. // In View Engine, registration occurs in the .ngfactory.js file as a side effect. This has
  41636. // several practical consequences:
  41637. //
  41638. // - If an .ngfactory file is not imported from, the module won't be registered (and can be
  41639. // tree shaken).
  41640. // - If an .ngfactory file is imported from, the module will be registered even if an instance
  41641. // is not actually created (via `create` below).
  41642. // - Since an .ngfactory file in View Engine references the .ngfactory files of the NgModule's
  41643. // imports,
  41644. //
  41645. // In Ivy, things are a bit different. .ngfactory files still exist for compatibility, but are
  41646. // not a required API to use - there are other ways to obtain an NgModuleFactory for a given
  41647. // NgModule. Thus, relying on a side effect in the .ngfactory file is not sufficient. Instead,
  41648. // the side effect of registration is added here, in the constructor of NgModuleFactory,
  41649. // ensuring no matter how a factory is created, the module is registered correctly.
  41650. //
  41651. // An alternative would be to include the registration side effect inline following the actual
  41652. // NgModule definition. This also has the correct timing, but breaks tree-shaking - modules
  41653. // will be registered and retained even if they're otherwise never referenced.
  41654. registerNgModuleType(moduleType);
  41655. }
  41656. return _this;
  41657. }
  41658. NgModuleFactory.prototype.create = function (parentInjector) {
  41659. return new NgModuleRef$1(this.moduleType, parentInjector);
  41660. };
  41661. return NgModuleFactory;
  41662. }(NgModuleFactory));
  41663. /**
  41664. * @license
  41665. * Copyright Google Inc. All Rights Reserved.
  41666. *
  41667. * Use of this source code is governed by an MIT-style license that can be
  41668. * found in the LICENSE file at https://angular.io/license
  41669. */
  41670. /**
  41671. * @license
  41672. * Copyright Google Inc. All Rights Reserved.
  41673. *
  41674. * Use of this source code is governed by an MIT-style license that can be
  41675. * found in the LICENSE file at https://angular.io/license
  41676. */
  41677. /**
  41678. * @license
  41679. * Copyright Google Inc. All Rights Reserved.
  41680. *
  41681. * Use of this source code is governed by an MIT-style license that can be
  41682. * found in the LICENSE file at https://angular.io/license
  41683. */
  41684. function isFunction(x) {
  41685. return typeof x === 'function';
  41686. }
  41687. let _enable_super_gross_mode_that_will_cause_bad_things = false;
  41688. const config = {
  41689. Promise: undefined,
  41690. set useDeprecatedSynchronousErrorHandling(value) {
  41691. if (value) {
  41692. const error = new Error();
  41693. console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
  41694. }
  41695. else if (_enable_super_gross_mode_that_will_cause_bad_things) {
  41696. console.log('RxJS: Back to a better error behavior. Thank you. <3');
  41697. }
  41698. _enable_super_gross_mode_that_will_cause_bad_things = value;
  41699. },
  41700. get useDeprecatedSynchronousErrorHandling() {
  41701. return _enable_super_gross_mode_that_will_cause_bad_things;
  41702. },
  41703. };
  41704. function hostReportError(err) {
  41705. setTimeout(() => { throw err; });
  41706. }
  41707. const empty$1 = {
  41708. closed: true,
  41709. next(value) { },
  41710. error(err) {
  41711. if (config.useDeprecatedSynchronousErrorHandling) {
  41712. throw err;
  41713. }
  41714. else {
  41715. hostReportError(err);
  41716. }
  41717. },
  41718. complete() { }
  41719. };
  41720. const isArray = Array.isArray || ((x) => x && typeof x.length === 'number');
  41721. function isObject(x) {
  41722. return x !== null && typeof x === 'object';
  41723. }
  41724. function UnsubscriptionErrorImpl(errors) {
  41725. Error.call(this);
  41726. this.message = errors ?
  41727. `${errors.length} errors occurred during unsubscription:
  41728. ${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\n ')}` : '';
  41729. this.name = 'UnsubscriptionError';
  41730. this.errors = errors;
  41731. return this;
  41732. }
  41733. UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);
  41734. const UnsubscriptionError = UnsubscriptionErrorImpl;
  41735. class Subscription {
  41736. constructor(unsubscribe) {
  41737. this.closed = false;
  41738. this._parent = null;
  41739. this._parents = null;
  41740. this._subscriptions = null;
  41741. if (unsubscribe) {
  41742. this._unsubscribe = unsubscribe;
  41743. }
  41744. }
  41745. unsubscribe() {
  41746. let hasErrors = false;
  41747. let errors;
  41748. if (this.closed) {
  41749. return;
  41750. }
  41751. let { _parent, _parents, _unsubscribe, _subscriptions } = this;
  41752. this.closed = true;
  41753. this._parent = null;
  41754. this._parents = null;
  41755. this._subscriptions = null;
  41756. let index = -1;
  41757. let len = _parents ? _parents.length : 0;
  41758. while (_parent) {
  41759. _parent.remove(this);
  41760. _parent = ++index < len && _parents[index] || null;
  41761. }
  41762. if (isFunction(_unsubscribe)) {
  41763. try {
  41764. _unsubscribe.call(this);
  41765. }
  41766. catch (e) {
  41767. hasErrors = true;
  41768. errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
  41769. }
  41770. }
  41771. if (isArray(_subscriptions)) {
  41772. index = -1;
  41773. len = _subscriptions.length;
  41774. while (++index < len) {
  41775. const sub = _subscriptions[index];
  41776. if (isObject(sub)) {
  41777. try {
  41778. sub.unsubscribe();
  41779. }
  41780. catch (e) {
  41781. hasErrors = true;
  41782. errors = errors || [];
  41783. if (e instanceof UnsubscriptionError) {
  41784. errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
  41785. }
  41786. else {
  41787. errors.push(e);
  41788. }
  41789. }
  41790. }
  41791. }
  41792. }
  41793. if (hasErrors) {
  41794. throw new UnsubscriptionError(errors);
  41795. }
  41796. }
  41797. add(teardown) {
  41798. let subscription = teardown;
  41799. switch (typeof teardown) {
  41800. case 'function':
  41801. subscription = new Subscription(teardown);
  41802. case 'object':
  41803. if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
  41804. return subscription;
  41805. }
  41806. else if (this.closed) {
  41807. subscription.unsubscribe();
  41808. return subscription;
  41809. }
  41810. else if (!(subscription instanceof Subscription)) {
  41811. const tmp = subscription;
  41812. subscription = new Subscription();
  41813. subscription._subscriptions = [tmp];
  41814. }
  41815. break;
  41816. default: {
  41817. if (!teardown) {
  41818. return Subscription.EMPTY;
  41819. }
  41820. throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
  41821. }
  41822. }
  41823. if (subscription._addParent(this)) {
  41824. const subscriptions = this._subscriptions;
  41825. if (subscriptions) {
  41826. subscriptions.push(subscription);
  41827. }
  41828. else {
  41829. this._subscriptions = [subscription];
  41830. }
  41831. }
  41832. return subscription;
  41833. }
  41834. remove(subscription) {
  41835. const subscriptions = this._subscriptions;
  41836. if (subscriptions) {
  41837. const subscriptionIndex = subscriptions.indexOf(subscription);
  41838. if (subscriptionIndex !== -1) {
  41839. subscriptions.splice(subscriptionIndex, 1);
  41840. }
  41841. }
  41842. }
  41843. _addParent(parent) {
  41844. let { _parent, _parents } = this;
  41845. if (_parent === parent) {
  41846. return false;
  41847. }
  41848. else if (!_parent) {
  41849. this._parent = parent;
  41850. return true;
  41851. }
  41852. else if (!_parents) {
  41853. this._parents = [parent];
  41854. return true;
  41855. }
  41856. else if (_parents.indexOf(parent) === -1) {
  41857. _parents.push(parent);
  41858. return true;
  41859. }
  41860. return false;
  41861. }
  41862. }
  41863. Subscription.EMPTY = (function (empty) {
  41864. empty.closed = true;
  41865. return empty;
  41866. }(new Subscription()));
  41867. function flattenUnsubscriptionErrors(errors) {
  41868. return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);
  41869. }
  41870. const rxSubscriber = typeof Symbol === 'function'
  41871. ? Symbol('rxSubscriber')
  41872. : '@@rxSubscriber_' + Math.random();
  41873. class Subscriber extends Subscription {
  41874. constructor(destinationOrNext, error, complete) {
  41875. super();
  41876. this.syncErrorValue = null;
  41877. this.syncErrorThrown = false;
  41878. this.syncErrorThrowable = false;
  41879. this.isStopped = false;
  41880. switch (arguments.length) {
  41881. case 0:
  41882. this.destination = empty$1;
  41883. break;
  41884. case 1:
  41885. if (!destinationOrNext) {
  41886. this.destination = empty$1;
  41887. break;
  41888. }
  41889. if (typeof destinationOrNext === 'object') {
  41890. if (destinationOrNext instanceof Subscriber) {
  41891. this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
  41892. this.destination = destinationOrNext;
  41893. destinationOrNext.add(this);
  41894. }
  41895. else {
  41896. this.syncErrorThrowable = true;
  41897. this.destination = new SafeSubscriber(this, destinationOrNext);
  41898. }
  41899. break;
  41900. }
  41901. default:
  41902. this.syncErrorThrowable = true;
  41903. this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
  41904. break;
  41905. }
  41906. }
  41907. [rxSubscriber]() { return this; }
  41908. static create(next, error, complete) {
  41909. const subscriber = new Subscriber(next, error, complete);
  41910. subscriber.syncErrorThrowable = false;
  41911. return subscriber;
  41912. }
  41913. next(value) {
  41914. if (!this.isStopped) {
  41915. this._next(value);
  41916. }
  41917. }
  41918. error(err) {
  41919. if (!this.isStopped) {
  41920. this.isStopped = true;
  41921. this._error(err);
  41922. }
  41923. }
  41924. complete() {
  41925. if (!this.isStopped) {
  41926. this.isStopped = true;
  41927. this._complete();
  41928. }
  41929. }
  41930. unsubscribe() {
  41931. if (this.closed) {
  41932. return;
  41933. }
  41934. this.isStopped = true;
  41935. super.unsubscribe();
  41936. }
  41937. _next(value) {
  41938. this.destination.next(value);
  41939. }
  41940. _error(err) {
  41941. this.destination.error(err);
  41942. this.unsubscribe();
  41943. }
  41944. _complete() {
  41945. this.destination.complete();
  41946. this.unsubscribe();
  41947. }
  41948. _unsubscribeAndRecycle() {
  41949. const { _parent, _parents } = this;
  41950. this._parent = null;
  41951. this._parents = null;
  41952. this.unsubscribe();
  41953. this.closed = false;
  41954. this.isStopped = false;
  41955. this._parent = _parent;
  41956. this._parents = _parents;
  41957. return this;
  41958. }
  41959. }
  41960. class SafeSubscriber extends Subscriber {
  41961. constructor(_parentSubscriber, observerOrNext, error, complete) {
  41962. super();
  41963. this._parentSubscriber = _parentSubscriber;
  41964. let next;
  41965. let context = this;
  41966. if (isFunction(observerOrNext)) {
  41967. next = observerOrNext;
  41968. }
  41969. else if (observerOrNext) {
  41970. next = observerOrNext.next;
  41971. error = observerOrNext.error;
  41972. complete = observerOrNext.complete;
  41973. if (observerOrNext !== empty$1) {
  41974. context = Object.create(observerOrNext);
  41975. if (isFunction(context.unsubscribe)) {
  41976. this.add(context.unsubscribe.bind(context));
  41977. }
  41978. context.unsubscribe = this.unsubscribe.bind(this);
  41979. }
  41980. }
  41981. this._context = context;
  41982. this._next = next;
  41983. this._error = error;
  41984. this._complete = complete;
  41985. }
  41986. next(value) {
  41987. if (!this.isStopped && this._next) {
  41988. const { _parentSubscriber } = this;
  41989. if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
  41990. this.__tryOrUnsub(this._next, value);
  41991. }
  41992. else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
  41993. this.unsubscribe();
  41994. }
  41995. }
  41996. }
  41997. error(err) {
  41998. if (!this.isStopped) {
  41999. const { _parentSubscriber } = this;
  42000. const { useDeprecatedSynchronousErrorHandling } = config;
  42001. if (this._error) {
  42002. if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
  42003. this.__tryOrUnsub(this._error, err);
  42004. this.unsubscribe();
  42005. }
  42006. else {
  42007. this.__tryOrSetError(_parentSubscriber, this._error, err);
  42008. this.unsubscribe();
  42009. }
  42010. }
  42011. else if (!_parentSubscriber.syncErrorThrowable) {
  42012. this.unsubscribe();
  42013. if (useDeprecatedSynchronousErrorHandling) {
  42014. throw err;
  42015. }
  42016. hostReportError(err);
  42017. }
  42018. else {
  42019. if (useDeprecatedSynchronousErrorHandling) {
  42020. _parentSubscriber.syncErrorValue = err;
  42021. _parentSubscriber.syncErrorThrown = true;
  42022. }
  42023. else {
  42024. hostReportError(err);
  42025. }
  42026. this.unsubscribe();
  42027. }
  42028. }
  42029. }
  42030. complete() {
  42031. if (!this.isStopped) {
  42032. const { _parentSubscriber } = this;
  42033. if (this._complete) {
  42034. const wrappedComplete = () => this._complete.call(this._context);
  42035. if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
  42036. this.__tryOrUnsub(wrappedComplete);
  42037. this.unsubscribe();
  42038. }
  42039. else {
  42040. this.__tryOrSetError(_parentSubscriber, wrappedComplete);
  42041. this.unsubscribe();
  42042. }
  42043. }
  42044. else {
  42045. this.unsubscribe();
  42046. }
  42047. }
  42048. }
  42049. __tryOrUnsub(fn, value) {
  42050. try {
  42051. fn.call(this._context, value);
  42052. }
  42053. catch (err) {
  42054. this.unsubscribe();
  42055. if (config.useDeprecatedSynchronousErrorHandling) {
  42056. throw err;
  42057. }
  42058. else {
  42059. hostReportError(err);
  42060. }
  42061. }
  42062. }
  42063. __tryOrSetError(parent, fn, value) {
  42064. if (!config.useDeprecatedSynchronousErrorHandling) {
  42065. throw new Error('bad call');
  42066. }
  42067. try {
  42068. fn.call(this._context, value);
  42069. }
  42070. catch (err) {
  42071. if (config.useDeprecatedSynchronousErrorHandling) {
  42072. parent.syncErrorValue = err;
  42073. parent.syncErrorThrown = true;
  42074. return true;
  42075. }
  42076. else {
  42077. hostReportError(err);
  42078. return true;
  42079. }
  42080. }
  42081. return false;
  42082. }
  42083. _unsubscribe() {
  42084. const { _parentSubscriber } = this;
  42085. this._context = null;
  42086. this._parentSubscriber = null;
  42087. _parentSubscriber.unsubscribe();
  42088. }
  42089. }
  42090. function canReportError(observer) {
  42091. while (observer) {
  42092. const { closed, destination, isStopped } = observer;
  42093. if (closed || isStopped) {
  42094. return false;
  42095. }
  42096. else if (destination && destination instanceof Subscriber) {
  42097. observer = destination;
  42098. }
  42099. else {
  42100. observer = null;
  42101. }
  42102. }
  42103. return true;
  42104. }
  42105. function toSubscriber(nextOrObserver, error, complete) {
  42106. if (nextOrObserver) {
  42107. if (nextOrObserver instanceof Subscriber) {
  42108. return nextOrObserver;
  42109. }
  42110. if (nextOrObserver[rxSubscriber]) {
  42111. return nextOrObserver[rxSubscriber]();
  42112. }
  42113. }
  42114. if (!nextOrObserver && !error && !complete) {
  42115. return new Subscriber(empty$1);
  42116. }
  42117. return new Subscriber(nextOrObserver, error, complete);
  42118. }
  42119. const observable = typeof Symbol === 'function' && Symbol.observable || '@@observable';
  42120. function noop$1() { }
  42121. function pipeFromArray(fns) {
  42122. if (!fns) {
  42123. return noop$1;
  42124. }
  42125. if (fns.length === 1) {
  42126. return fns[0];
  42127. }
  42128. return function piped(input) {
  42129. return fns.reduce((prev, fn) => fn(prev), input);
  42130. };
  42131. }
  42132. class Observable {
  42133. constructor(subscribe) {
  42134. this._isScalar = false;
  42135. if (subscribe) {
  42136. this._subscribe = subscribe;
  42137. }
  42138. }
  42139. lift(operator) {
  42140. const observable = new Observable();
  42141. observable.source = this;
  42142. observable.operator = operator;
  42143. return observable;
  42144. }
  42145. subscribe(observerOrNext, error, complete) {
  42146. const { operator } = this;
  42147. const sink = toSubscriber(observerOrNext, error, complete);
  42148. if (operator) {
  42149. sink.add(operator.call(sink, this.source));
  42150. }
  42151. else {
  42152. sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
  42153. this._subscribe(sink) :
  42154. this._trySubscribe(sink));
  42155. }
  42156. if (config.useDeprecatedSynchronousErrorHandling) {
  42157. if (sink.syncErrorThrowable) {
  42158. sink.syncErrorThrowable = false;
  42159. if (sink.syncErrorThrown) {
  42160. throw sink.syncErrorValue;
  42161. }
  42162. }
  42163. }
  42164. return sink;
  42165. }
  42166. _trySubscribe(sink) {
  42167. try {
  42168. return this._subscribe(sink);
  42169. }
  42170. catch (err) {
  42171. if (config.useDeprecatedSynchronousErrorHandling) {
  42172. sink.syncErrorThrown = true;
  42173. sink.syncErrorValue = err;
  42174. }
  42175. if (canReportError(sink)) {
  42176. sink.error(err);
  42177. }
  42178. else {
  42179. console.warn(err);
  42180. }
  42181. }
  42182. }
  42183. forEach(next, promiseCtor) {
  42184. promiseCtor = getPromiseCtor(promiseCtor);
  42185. return new promiseCtor((resolve, reject) => {
  42186. let subscription;
  42187. subscription = this.subscribe((value) => {
  42188. try {
  42189. next(value);
  42190. }
  42191. catch (err) {
  42192. reject(err);
  42193. if (subscription) {
  42194. subscription.unsubscribe();
  42195. }
  42196. }
  42197. }, reject, resolve);
  42198. });
  42199. }
  42200. _subscribe(subscriber) {
  42201. const { source } = this;
  42202. return source && source.subscribe(subscriber);
  42203. }
  42204. [observable]() {
  42205. return this;
  42206. }
  42207. pipe(...operations) {
  42208. if (operations.length === 0) {
  42209. return this;
  42210. }
  42211. return pipeFromArray(operations)(this);
  42212. }
  42213. toPromise(promiseCtor) {
  42214. promiseCtor = getPromiseCtor(promiseCtor);
  42215. return new promiseCtor((resolve, reject) => {
  42216. let value;
  42217. this.subscribe((x) => value = x, (err) => reject(err), () => resolve(value));
  42218. });
  42219. }
  42220. }
  42221. Observable.create = (subscribe) => {
  42222. return new Observable(subscribe);
  42223. };
  42224. function getPromiseCtor(promiseCtor) {
  42225. if (!promiseCtor) {
  42226. promiseCtor = Promise;
  42227. }
  42228. if (!promiseCtor) {
  42229. throw new Error('no Promise impl found');
  42230. }
  42231. return promiseCtor;
  42232. }
  42233. function ObjectUnsubscribedErrorImpl() {
  42234. Error.call(this);
  42235. this.message = 'object unsubscribed';
  42236. this.name = 'ObjectUnsubscribedError';
  42237. return this;
  42238. }
  42239. ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
  42240. const ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
  42241. class SubjectSubscription extends Subscription {
  42242. constructor(subject, subscriber) {
  42243. super();
  42244. this.subject = subject;
  42245. this.subscriber = subscriber;
  42246. this.closed = false;
  42247. }
  42248. unsubscribe() {
  42249. if (this.closed) {
  42250. return;
  42251. }
  42252. this.closed = true;
  42253. const subject = this.subject;
  42254. const observers = subject.observers;
  42255. this.subject = null;
  42256. if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
  42257. return;
  42258. }
  42259. const subscriberIndex = observers.indexOf(this.subscriber);
  42260. if (subscriberIndex !== -1) {
  42261. observers.splice(subscriberIndex, 1);
  42262. }
  42263. }
  42264. }
  42265. class SubjectSubscriber extends Subscriber {
  42266. constructor(destination) {
  42267. super(destination);
  42268. this.destination = destination;
  42269. }
  42270. }
  42271. class Subject extends Observable {
  42272. constructor() {
  42273. super();
  42274. this.observers = [];
  42275. this.closed = false;
  42276. this.isStopped = false;
  42277. this.hasError = false;
  42278. this.thrownError = null;
  42279. }
  42280. [rxSubscriber]() {
  42281. return new SubjectSubscriber(this);
  42282. }
  42283. lift(operator) {
  42284. const subject = new AnonymousSubject(this, this);
  42285. subject.operator = operator;
  42286. return subject;
  42287. }
  42288. next(value) {
  42289. if (this.closed) {
  42290. throw new ObjectUnsubscribedError();
  42291. }
  42292. if (!this.isStopped) {
  42293. const { observers } = this;
  42294. const len = observers.length;
  42295. const copy = observers.slice();
  42296. for (let i = 0; i < len; i++) {
  42297. copy[i].next(value);
  42298. }
  42299. }
  42300. }
  42301. error(err) {
  42302. if (this.closed) {
  42303. throw new ObjectUnsubscribedError();
  42304. }
  42305. this.hasError = true;
  42306. this.thrownError = err;
  42307. this.isStopped = true;
  42308. const { observers } = this;
  42309. const len = observers.length;
  42310. const copy = observers.slice();
  42311. for (let i = 0; i < len; i++) {
  42312. copy[i].error(err);
  42313. }
  42314. this.observers.length = 0;
  42315. }
  42316. complete() {
  42317. if (this.closed) {
  42318. throw new ObjectUnsubscribedError();
  42319. }
  42320. this.isStopped = true;
  42321. const { observers } = this;
  42322. const len = observers.length;
  42323. const copy = observers.slice();
  42324. for (let i = 0; i < len; i++) {
  42325. copy[i].complete();
  42326. }
  42327. this.observers.length = 0;
  42328. }
  42329. unsubscribe() {
  42330. this.isStopped = true;
  42331. this.closed = true;
  42332. this.observers = null;
  42333. }
  42334. _trySubscribe(subscriber) {
  42335. if (this.closed) {
  42336. throw new ObjectUnsubscribedError();
  42337. }
  42338. else {
  42339. return super._trySubscribe(subscriber);
  42340. }
  42341. }
  42342. _subscribe(subscriber) {
  42343. if (this.closed) {
  42344. throw new ObjectUnsubscribedError();
  42345. }
  42346. else if (this.hasError) {
  42347. subscriber.error(this.thrownError);
  42348. return Subscription.EMPTY;
  42349. }
  42350. else if (this.isStopped) {
  42351. subscriber.complete();
  42352. return Subscription.EMPTY;
  42353. }
  42354. else {
  42355. this.observers.push(subscriber);
  42356. return new SubjectSubscription(this, subscriber);
  42357. }
  42358. }
  42359. asObservable() {
  42360. const observable = new Observable();
  42361. observable.source = this;
  42362. return observable;
  42363. }
  42364. }
  42365. Subject.create = (destination, source) => {
  42366. return new AnonymousSubject(destination, source);
  42367. };
  42368. class AnonymousSubject extends Subject {
  42369. constructor(destination, source) {
  42370. super();
  42371. this.destination = destination;
  42372. this.source = source;
  42373. }
  42374. next(value) {
  42375. const { destination } = this;
  42376. if (destination && destination.next) {
  42377. destination.next(value);
  42378. }
  42379. }
  42380. error(err) {
  42381. const { destination } = this;
  42382. if (destination && destination.error) {
  42383. this.destination.error(err);
  42384. }
  42385. }
  42386. complete() {
  42387. const { destination } = this;
  42388. if (destination && destination.complete) {
  42389. this.destination.complete();
  42390. }
  42391. }
  42392. _subscribe(subscriber) {
  42393. const { source } = this;
  42394. if (source) {
  42395. return this.source.subscribe(subscriber);
  42396. }
  42397. else {
  42398. return Subscription.EMPTY;
  42399. }
  42400. }
  42401. }
  42402. function refCount() {
  42403. return function refCountOperatorFunction(source) {
  42404. return source.lift(new RefCountOperator(source));
  42405. };
  42406. }
  42407. class RefCountOperator {
  42408. constructor(connectable) {
  42409. this.connectable = connectable;
  42410. }
  42411. call(subscriber, source) {
  42412. const { connectable } = this;
  42413. connectable._refCount++;
  42414. const refCounter = new RefCountSubscriber(subscriber, connectable);
  42415. const subscription = source.subscribe(refCounter);
  42416. if (!refCounter.closed) {
  42417. refCounter.connection = connectable.connect();
  42418. }
  42419. return subscription;
  42420. }
  42421. }
  42422. class RefCountSubscriber extends Subscriber {
  42423. constructor(destination, connectable) {
  42424. super(destination);
  42425. this.connectable = connectable;
  42426. }
  42427. _unsubscribe() {
  42428. const { connectable } = this;
  42429. if (!connectable) {
  42430. this.connection = null;
  42431. return;
  42432. }
  42433. this.connectable = null;
  42434. const refCount = connectable._refCount;
  42435. if (refCount <= 0) {
  42436. this.connection = null;
  42437. return;
  42438. }
  42439. connectable._refCount = refCount - 1;
  42440. if (refCount > 1) {
  42441. this.connection = null;
  42442. return;
  42443. }
  42444. const { connection } = this;
  42445. const sharedConnection = connectable._connection;
  42446. this.connection = null;
  42447. if (sharedConnection && (!connection || sharedConnection === connection)) {
  42448. sharedConnection.unsubscribe();
  42449. }
  42450. }
  42451. }
  42452. class ConnectableObservable extends Observable {
  42453. constructor(source, subjectFactory) {
  42454. super();
  42455. this.source = source;
  42456. this.subjectFactory = subjectFactory;
  42457. this._refCount = 0;
  42458. this._isComplete = false;
  42459. }
  42460. _subscribe(subscriber) {
  42461. return this.getSubject().subscribe(subscriber);
  42462. }
  42463. getSubject() {
  42464. const subject = this._subject;
  42465. if (!subject || subject.isStopped) {
  42466. this._subject = this.subjectFactory();
  42467. }
  42468. return this._subject;
  42469. }
  42470. connect() {
  42471. let connection = this._connection;
  42472. if (!connection) {
  42473. this._isComplete = false;
  42474. connection = this._connection = new Subscription();
  42475. connection.add(this.source
  42476. .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
  42477. if (connection.closed) {
  42478. this._connection = null;
  42479. connection = Subscription.EMPTY;
  42480. }
  42481. else {
  42482. this._connection = connection;
  42483. }
  42484. }
  42485. return connection;
  42486. }
  42487. refCount() {
  42488. return refCount()(this);
  42489. }
  42490. }
  42491. const connectableProto = ConnectableObservable.prototype;
  42492. const connectableObservableDescriptor = {
  42493. operator: { value: null },
  42494. _refCount: { value: 0, writable: true },
  42495. _subject: { value: null, writable: true },
  42496. _connection: { value: null, writable: true },
  42497. _subscribe: { value: connectableProto._subscribe },
  42498. _isComplete: { value: connectableProto._isComplete, writable: true },
  42499. getSubject: { value: connectableProto.getSubject },
  42500. connect: { value: connectableProto.connect },
  42501. refCount: { value: connectableProto.refCount }
  42502. };
  42503. class ConnectableSubscriber extends SubjectSubscriber {
  42504. constructor(destination, connectable) {
  42505. super(destination);
  42506. this.connectable = connectable;
  42507. }
  42508. _error(err) {
  42509. this._unsubscribe();
  42510. super._error(err);
  42511. }
  42512. _complete() {
  42513. this.connectable._isComplete = true;
  42514. this._unsubscribe();
  42515. super._complete();
  42516. }
  42517. _unsubscribe() {
  42518. const connectable = this.connectable;
  42519. if (connectable) {
  42520. this.connectable = null;
  42521. const connection = connectable._connection;
  42522. connectable._refCount = 0;
  42523. connectable._subject = null;
  42524. connectable._connection = null;
  42525. if (connection) {
  42526. connection.unsubscribe();
  42527. }
  42528. }
  42529. }
  42530. }
  42531. class Action extends Subscription {
  42532. constructor(scheduler, work) {
  42533. super();
  42534. }
  42535. schedule(state, delay = 0) {
  42536. return this;
  42537. }
  42538. }
  42539. class AsyncAction extends Action {
  42540. constructor(scheduler, work) {
  42541. super(scheduler, work);
  42542. this.scheduler = scheduler;
  42543. this.work = work;
  42544. this.pending = false;
  42545. }
  42546. schedule(state, delay = 0) {
  42547. if (this.closed) {
  42548. return this;
  42549. }
  42550. this.state = state;
  42551. const id = this.id;
  42552. const scheduler = this.scheduler;
  42553. if (id != null) {
  42554. this.id = this.recycleAsyncId(scheduler, id, delay);
  42555. }
  42556. this.pending = true;
  42557. this.delay = delay;
  42558. this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
  42559. return this;
  42560. }
  42561. requestAsyncId(scheduler, id, delay = 0) {
  42562. return setInterval(scheduler.flush.bind(scheduler, this), delay);
  42563. }
  42564. recycleAsyncId(scheduler, id, delay = 0) {
  42565. if (delay !== null && this.delay === delay && this.pending === false) {
  42566. return id;
  42567. }
  42568. clearInterval(id);
  42569. return undefined;
  42570. }
  42571. execute(state, delay) {
  42572. if (this.closed) {
  42573. return new Error('executing a cancelled action');
  42574. }
  42575. this.pending = false;
  42576. const error = this._execute(state, delay);
  42577. if (error) {
  42578. return error;
  42579. }
  42580. else if (this.pending === false && this.id != null) {
  42581. this.id = this.recycleAsyncId(this.scheduler, this.id, null);
  42582. }
  42583. }
  42584. _execute(state, delay) {
  42585. let errored = false;
  42586. let errorValue = undefined;
  42587. try {
  42588. this.work(state);
  42589. }
  42590. catch (e) {
  42591. errored = true;
  42592. errorValue = !!e && e || new Error(e);
  42593. }
  42594. if (errored) {
  42595. this.unsubscribe();
  42596. return errorValue;
  42597. }
  42598. }
  42599. _unsubscribe() {
  42600. const id = this.id;
  42601. const scheduler = this.scheduler;
  42602. const actions = scheduler.actions;
  42603. const index = actions.indexOf(this);
  42604. this.work = null;
  42605. this.state = null;
  42606. this.pending = false;
  42607. this.scheduler = null;
  42608. if (index !== -1) {
  42609. actions.splice(index, 1);
  42610. }
  42611. if (id != null) {
  42612. this.id = this.recycleAsyncId(scheduler, id, null);
  42613. }
  42614. this.delay = null;
  42615. }
  42616. }
  42617. class QueueAction extends AsyncAction {
  42618. constructor(scheduler, work) {
  42619. super(scheduler, work);
  42620. this.scheduler = scheduler;
  42621. this.work = work;
  42622. }
  42623. schedule(state, delay = 0) {
  42624. if (delay > 0) {
  42625. return super.schedule(state, delay);
  42626. }
  42627. this.delay = delay;
  42628. this.state = state;
  42629. this.scheduler.flush(this);
  42630. return this;
  42631. }
  42632. execute(state, delay) {
  42633. return (delay > 0 || this.closed) ?
  42634. super.execute(state, delay) :
  42635. this._execute(state, delay);
  42636. }
  42637. requestAsyncId(scheduler, id, delay = 0) {
  42638. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  42639. return super.requestAsyncId(scheduler, id, delay);
  42640. }
  42641. return scheduler.flush(this);
  42642. }
  42643. }
  42644. class Scheduler {
  42645. constructor(SchedulerAction, now = Scheduler.now) {
  42646. this.SchedulerAction = SchedulerAction;
  42647. this.now = now;
  42648. }
  42649. schedule(work, delay = 0, state) {
  42650. return new this.SchedulerAction(this, work).schedule(state, delay);
  42651. }
  42652. }
  42653. Scheduler.now = () => Date.now();
  42654. class AsyncScheduler extends Scheduler {
  42655. constructor(SchedulerAction, now = Scheduler.now) {
  42656. super(SchedulerAction, () => {
  42657. if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
  42658. return AsyncScheduler.delegate.now();
  42659. }
  42660. else {
  42661. return now();
  42662. }
  42663. });
  42664. this.actions = [];
  42665. this.active = false;
  42666. this.scheduled = undefined;
  42667. }
  42668. schedule(work, delay = 0, state) {
  42669. if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
  42670. return AsyncScheduler.delegate.schedule(work, delay, state);
  42671. }
  42672. else {
  42673. return super.schedule(work, delay, state);
  42674. }
  42675. }
  42676. flush(action) {
  42677. const { actions } = this;
  42678. if (this.active) {
  42679. actions.push(action);
  42680. return;
  42681. }
  42682. let error;
  42683. this.active = true;
  42684. do {
  42685. if (error = action.execute(action.state, action.delay)) {
  42686. break;
  42687. }
  42688. } while (action = actions.shift());
  42689. this.active = false;
  42690. if (error) {
  42691. while (action = actions.shift()) {
  42692. action.unsubscribe();
  42693. }
  42694. throw error;
  42695. }
  42696. }
  42697. }
  42698. class QueueScheduler extends AsyncScheduler {
  42699. }
  42700. const queue = new QueueScheduler(QueueAction);
  42701. function isScheduler(value) {
  42702. return value && typeof value.schedule === 'function';
  42703. }
  42704. const subscribeToArray = (array) => (subscriber) => {
  42705. for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {
  42706. subscriber.next(array[i]);
  42707. }
  42708. if (!subscriber.closed) {
  42709. subscriber.complete();
  42710. }
  42711. };
  42712. function fromArray(input, scheduler) {
  42713. if (!scheduler) {
  42714. return new Observable(subscribeToArray(input));
  42715. }
  42716. else {
  42717. return new Observable(subscriber => {
  42718. const sub = new Subscription();
  42719. let i = 0;
  42720. sub.add(scheduler.schedule(function () {
  42721. if (i === input.length) {
  42722. subscriber.complete();
  42723. return;
  42724. }
  42725. subscriber.next(input[i++]);
  42726. if (!subscriber.closed) {
  42727. sub.add(this.schedule());
  42728. }
  42729. }));
  42730. return sub;
  42731. });
  42732. }
  42733. }
  42734. var NotificationKind;
  42735. (function (NotificationKind) {
  42736. NotificationKind["NEXT"] = "N";
  42737. NotificationKind["ERROR"] = "E";
  42738. NotificationKind["COMPLETE"] = "C";
  42739. })(NotificationKind || (NotificationKind = {}));
  42740. let nextHandle = 1;
  42741. const tasksByHandle = {};
  42742. function runIfPresent(handle) {
  42743. const cb = tasksByHandle[handle];
  42744. if (cb) {
  42745. cb();
  42746. }
  42747. }
  42748. const Immediate = {
  42749. setImmediate(cb) {
  42750. const handle = nextHandle++;
  42751. tasksByHandle[handle] = cb;
  42752. Promise.resolve().then(() => runIfPresent(handle));
  42753. return handle;
  42754. },
  42755. clearImmediate(handle) {
  42756. delete tasksByHandle[handle];
  42757. },
  42758. };
  42759. class AsapAction extends AsyncAction {
  42760. constructor(scheduler, work) {
  42761. super(scheduler, work);
  42762. this.scheduler = scheduler;
  42763. this.work = work;
  42764. }
  42765. requestAsyncId(scheduler, id, delay = 0) {
  42766. if (delay !== null && delay > 0) {
  42767. return super.requestAsyncId(scheduler, id, delay);
  42768. }
  42769. scheduler.actions.push(this);
  42770. return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
  42771. }
  42772. recycleAsyncId(scheduler, id, delay = 0) {
  42773. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  42774. return super.recycleAsyncId(scheduler, id, delay);
  42775. }
  42776. if (scheduler.actions.length === 0) {
  42777. Immediate.clearImmediate(id);
  42778. scheduler.scheduled = undefined;
  42779. }
  42780. return undefined;
  42781. }
  42782. }
  42783. class AsapScheduler extends AsyncScheduler {
  42784. flush(action) {
  42785. this.active = true;
  42786. this.scheduled = undefined;
  42787. const { actions } = this;
  42788. let error;
  42789. let index = -1;
  42790. let count = actions.length;
  42791. action = action || actions.shift();
  42792. do {
  42793. if (error = action.execute(action.state, action.delay)) {
  42794. break;
  42795. }
  42796. } while (++index < count && (action = actions.shift()));
  42797. this.active = false;
  42798. if (error) {
  42799. while (++index < count && (action = actions.shift())) {
  42800. action.unsubscribe();
  42801. }
  42802. throw error;
  42803. }
  42804. }
  42805. }
  42806. const asap = new AsapScheduler(AsapAction);
  42807. const async = new AsyncScheduler(AsyncAction);
  42808. class AnimationFrameAction extends AsyncAction {
  42809. constructor(scheduler, work) {
  42810. super(scheduler, work);
  42811. this.scheduler = scheduler;
  42812. this.work = work;
  42813. }
  42814. requestAsyncId(scheduler, id, delay = 0) {
  42815. if (delay !== null && delay > 0) {
  42816. return super.requestAsyncId(scheduler, id, delay);
  42817. }
  42818. scheduler.actions.push(this);
  42819. return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(() => scheduler.flush(null)));
  42820. }
  42821. recycleAsyncId(scheduler, id, delay = 0) {
  42822. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  42823. return super.recycleAsyncId(scheduler, id, delay);
  42824. }
  42825. if (scheduler.actions.length === 0) {
  42826. cancelAnimationFrame(id);
  42827. scheduler.scheduled = undefined;
  42828. }
  42829. return undefined;
  42830. }
  42831. }
  42832. class AnimationFrameScheduler extends AsyncScheduler {
  42833. flush(action) {
  42834. this.active = true;
  42835. this.scheduled = undefined;
  42836. const { actions } = this;
  42837. let error;
  42838. let index = -1;
  42839. let count = actions.length;
  42840. action = action || actions.shift();
  42841. do {
  42842. if (error = action.execute(action.state, action.delay)) {
  42843. break;
  42844. }
  42845. } while (++index < count && (action = actions.shift()));
  42846. this.active = false;
  42847. if (error) {
  42848. while (++index < count && (action = actions.shift())) {
  42849. action.unsubscribe();
  42850. }
  42851. throw error;
  42852. }
  42853. }
  42854. }
  42855. const animationFrame = new AnimationFrameScheduler(AnimationFrameAction);
  42856. function identity(x) {
  42857. return x;
  42858. }
  42859. function map(project, thisArg) {
  42860. return function mapOperation(source) {
  42861. if (typeof project !== 'function') {
  42862. throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
  42863. }
  42864. return source.lift(new MapOperator(project, thisArg));
  42865. };
  42866. }
  42867. class MapOperator {
  42868. constructor(project, thisArg) {
  42869. this.project = project;
  42870. this.thisArg = thisArg;
  42871. }
  42872. call(subscriber, source) {
  42873. return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
  42874. }
  42875. }
  42876. class MapSubscriber extends Subscriber {
  42877. constructor(destination, project, thisArg) {
  42878. super(destination);
  42879. this.project = project;
  42880. this.count = 0;
  42881. this.thisArg = thisArg || this;
  42882. }
  42883. _next(value) {
  42884. let result;
  42885. try {
  42886. result = this.project.call(this.thisArg, value, this.count++);
  42887. }
  42888. catch (err) {
  42889. this.destination.error(err);
  42890. return;
  42891. }
  42892. this.destination.next(result);
  42893. }
  42894. }
  42895. class OuterSubscriber extends Subscriber {
  42896. notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  42897. this.destination.next(innerValue);
  42898. }
  42899. notifyError(error, innerSub) {
  42900. this.destination.error(error);
  42901. }
  42902. notifyComplete(innerSub) {
  42903. this.destination.complete();
  42904. }
  42905. }
  42906. class InnerSubscriber extends Subscriber {
  42907. constructor(parent, outerValue, outerIndex) {
  42908. super();
  42909. this.parent = parent;
  42910. this.outerValue = outerValue;
  42911. this.outerIndex = outerIndex;
  42912. this.index = 0;
  42913. }
  42914. _next(value) {
  42915. this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
  42916. }
  42917. _error(error) {
  42918. this.parent.notifyError(error, this);
  42919. this.unsubscribe();
  42920. }
  42921. _complete() {
  42922. this.parent.notifyComplete(this);
  42923. this.unsubscribe();
  42924. }
  42925. }
  42926. const subscribeToPromise = (promise) => (subscriber) => {
  42927. promise.then((value) => {
  42928. if (!subscriber.closed) {
  42929. subscriber.next(value);
  42930. subscriber.complete();
  42931. }
  42932. }, (err) => subscriber.error(err))
  42933. .then(null, hostReportError);
  42934. return subscriber;
  42935. };
  42936. function getSymbolIterator$1() {
  42937. if (typeof Symbol !== 'function' || !Symbol.iterator) {
  42938. return '@@iterator';
  42939. }
  42940. return Symbol.iterator;
  42941. }
  42942. const iterator = getSymbolIterator$1();
  42943. const subscribeToIterable = (iterable) => (subscriber) => {
  42944. const iterator$1 = iterable[iterator]();
  42945. do {
  42946. const item = iterator$1.next();
  42947. if (item.done) {
  42948. subscriber.complete();
  42949. break;
  42950. }
  42951. subscriber.next(item.value);
  42952. if (subscriber.closed) {
  42953. break;
  42954. }
  42955. } while (true);
  42956. if (typeof iterator$1.return === 'function') {
  42957. subscriber.add(() => {
  42958. if (iterator$1.return) {
  42959. iterator$1.return();
  42960. }
  42961. });
  42962. }
  42963. return subscriber;
  42964. };
  42965. const subscribeToObservable = (obj) => (subscriber) => {
  42966. const obs = obj[observable]();
  42967. if (typeof obs.subscribe !== 'function') {
  42968. throw new TypeError('Provided object does not correctly implement Symbol.observable');
  42969. }
  42970. else {
  42971. return obs.subscribe(subscriber);
  42972. }
  42973. };
  42974. const isArrayLike = ((x) => x && typeof x.length === 'number' && typeof x !== 'function');
  42975. function isPromise$2(value) {
  42976. return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
  42977. }
  42978. const subscribeTo = (result) => {
  42979. if (result instanceof Observable) {
  42980. return (subscriber) => {
  42981. if (result._isScalar) {
  42982. subscriber.next(result.value);
  42983. subscriber.complete();
  42984. return undefined;
  42985. }
  42986. else {
  42987. return result.subscribe(subscriber);
  42988. }
  42989. };
  42990. }
  42991. else if (!!result && typeof result[observable] === 'function') {
  42992. return subscribeToObservable(result);
  42993. }
  42994. else if (isArrayLike(result)) {
  42995. return subscribeToArray(result);
  42996. }
  42997. else if (isPromise$2(result)) {
  42998. return subscribeToPromise(result);
  42999. }
  43000. else if (!!result && typeof result[iterator] === 'function') {
  43001. return subscribeToIterable(result);
  43002. }
  43003. else {
  43004. const value = isObject(result) ? 'an invalid object' : `'${result}'`;
  43005. const msg = `You provided ${value} where a stream was expected.`
  43006. + ' You can provide an Observable, Promise, Array, or Iterable.';
  43007. throw new TypeError(msg);
  43008. }
  43009. };
  43010. function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination = new InnerSubscriber(outerSubscriber, outerValue, outerIndex)) {
  43011. if (destination.closed) {
  43012. return;
  43013. }
  43014. return subscribeTo(result)(destination);
  43015. }
  43016. function isInteropObservable(input) {
  43017. return input && typeof input[observable] === 'function';
  43018. }
  43019. function isIterable(input) {
  43020. return input && typeof input[iterator] === 'function';
  43021. }
  43022. function fromPromise(input, scheduler) {
  43023. if (!scheduler) {
  43024. return new Observable(subscribeToPromise(input));
  43025. }
  43026. else {
  43027. return new Observable(subscriber => {
  43028. const sub = new Subscription();
  43029. sub.add(scheduler.schedule(() => input.then(value => {
  43030. sub.add(scheduler.schedule(() => {
  43031. subscriber.next(value);
  43032. sub.add(scheduler.schedule(() => subscriber.complete()));
  43033. }));
  43034. }, err => {
  43035. sub.add(scheduler.schedule(() => subscriber.error(err)));
  43036. })));
  43037. return sub;
  43038. });
  43039. }
  43040. }
  43041. function fromIterable(input, scheduler) {
  43042. if (!input) {
  43043. throw new Error('Iterable cannot be null');
  43044. }
  43045. if (!scheduler) {
  43046. return new Observable(subscribeToIterable(input));
  43047. }
  43048. else {
  43049. return new Observable(subscriber => {
  43050. const sub = new Subscription();
  43051. let iterator$1;
  43052. sub.add(() => {
  43053. if (iterator$1 && typeof iterator$1.return === 'function') {
  43054. iterator$1.return();
  43055. }
  43056. });
  43057. sub.add(scheduler.schedule(() => {
  43058. iterator$1 = input[iterator]();
  43059. sub.add(scheduler.schedule(function () {
  43060. if (subscriber.closed) {
  43061. return;
  43062. }
  43063. let value;
  43064. let done;
  43065. try {
  43066. const result = iterator$1.next();
  43067. value = result.value;
  43068. done = result.done;
  43069. }
  43070. catch (err) {
  43071. subscriber.error(err);
  43072. return;
  43073. }
  43074. if (done) {
  43075. subscriber.complete();
  43076. }
  43077. else {
  43078. subscriber.next(value);
  43079. this.schedule();
  43080. }
  43081. }));
  43082. }));
  43083. return sub;
  43084. });
  43085. }
  43086. }
  43087. function fromObservable(input, scheduler) {
  43088. if (!scheduler) {
  43089. return new Observable(subscribeToObservable(input));
  43090. }
  43091. else {
  43092. return new Observable(subscriber => {
  43093. const sub = new Subscription();
  43094. sub.add(scheduler.schedule(() => {
  43095. const observable$1 = input[observable]();
  43096. sub.add(observable$1.subscribe({
  43097. next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },
  43098. error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },
  43099. complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },
  43100. }));
  43101. }));
  43102. return sub;
  43103. });
  43104. }
  43105. }
  43106. function from(input, scheduler) {
  43107. if (!scheduler) {
  43108. if (input instanceof Observable) {
  43109. return input;
  43110. }
  43111. return new Observable(subscribeTo(input));
  43112. }
  43113. if (input != null) {
  43114. if (isInteropObservable(input)) {
  43115. return fromObservable(input, scheduler);
  43116. }
  43117. else if (isPromise$2(input)) {
  43118. return fromPromise(input, scheduler);
  43119. }
  43120. else if (isArrayLike(input)) {
  43121. return fromArray(input, scheduler);
  43122. }
  43123. else if (isIterable(input) || typeof input === 'string') {
  43124. return fromIterable(input, scheduler);
  43125. }
  43126. }
  43127. throw new TypeError((input !== null && typeof input || input) + ' is not observable');
  43128. }
  43129. function mergeMap(project, resultSelector, concurrent = Number.POSITIVE_INFINITY) {
  43130. if (typeof resultSelector === 'function') {
  43131. return (source) => source.pipe(mergeMap((a, i) => from(project(a, i)).pipe(map((b, ii) => resultSelector(a, b, i, ii))), concurrent));
  43132. }
  43133. else if (typeof resultSelector === 'number') {
  43134. concurrent = resultSelector;
  43135. }
  43136. return (source) => source.lift(new MergeMapOperator(project, concurrent));
  43137. }
  43138. class MergeMapOperator {
  43139. constructor(project, concurrent = Number.POSITIVE_INFINITY) {
  43140. this.project = project;
  43141. this.concurrent = concurrent;
  43142. }
  43143. call(observer, source) {
  43144. return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
  43145. }
  43146. }
  43147. class MergeMapSubscriber extends OuterSubscriber {
  43148. constructor(destination, project, concurrent = Number.POSITIVE_INFINITY) {
  43149. super(destination);
  43150. this.project = project;
  43151. this.concurrent = concurrent;
  43152. this.hasCompleted = false;
  43153. this.buffer = [];
  43154. this.active = 0;
  43155. this.index = 0;
  43156. }
  43157. _next(value) {
  43158. if (this.active < this.concurrent) {
  43159. this._tryNext(value);
  43160. }
  43161. else {
  43162. this.buffer.push(value);
  43163. }
  43164. }
  43165. _tryNext(value) {
  43166. let result;
  43167. const index = this.index++;
  43168. try {
  43169. result = this.project(value, index);
  43170. }
  43171. catch (err) {
  43172. this.destination.error(err);
  43173. return;
  43174. }
  43175. this.active++;
  43176. this._innerSub(result, value, index);
  43177. }
  43178. _innerSub(ish, value, index) {
  43179. const innerSubscriber = new InnerSubscriber(this, undefined, undefined);
  43180. const destination = this.destination;
  43181. destination.add(innerSubscriber);
  43182. subscribeToResult(this, ish, value, index, innerSubscriber);
  43183. }
  43184. _complete() {
  43185. this.hasCompleted = true;
  43186. if (this.active === 0 && this.buffer.length === 0) {
  43187. this.destination.complete();
  43188. }
  43189. this.unsubscribe();
  43190. }
  43191. notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  43192. this.destination.next(innerValue);
  43193. }
  43194. notifyComplete(innerSub) {
  43195. const buffer = this.buffer;
  43196. this.remove(innerSub);
  43197. this.active--;
  43198. if (buffer.length > 0) {
  43199. this._next(buffer.shift());
  43200. }
  43201. else if (this.active === 0 && this.hasCompleted) {
  43202. this.destination.complete();
  43203. }
  43204. }
  43205. }
  43206. function mergeAll(concurrent = Number.POSITIVE_INFINITY) {
  43207. return mergeMap(identity, concurrent);
  43208. }
  43209. function merge$1(...observables) {
  43210. let concurrent = Number.POSITIVE_INFINITY;
  43211. let scheduler = null;
  43212. let last = observables[observables.length - 1];
  43213. if (isScheduler(last)) {
  43214. scheduler = observables.pop();
  43215. if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
  43216. concurrent = observables.pop();
  43217. }
  43218. }
  43219. else if (typeof last === 'number') {
  43220. concurrent = observables.pop();
  43221. }
  43222. if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {
  43223. return observables[0];
  43224. }
  43225. return mergeAll(concurrent)(fromArray(observables, scheduler));
  43226. }
  43227. /**
  43228. * @license
  43229. * Copyright Google Inc. All Rights Reserved.
  43230. *
  43231. * Use of this source code is governed by an MIT-style license that can be
  43232. * found in the LICENSE file at https://angular.io/license
  43233. */
  43234. /**
  43235. * Use in directives and components to emit custom events synchronously
  43236. * or asynchronously, and register handlers for those events by subscribing
  43237. * to an instance.
  43238. *
  43239. * @usageNotes
  43240. *
  43241. * In the following example, a component defines two output properties
  43242. * that create event emitters. When the title is clicked, the emitter
  43243. * emits an open or close event to toggle the current visibility state.
  43244. *
  43245. * ```html
  43246. * @Component({
  43247. * selector: 'zippy',
  43248. * template: `
  43249. * <div class="zippy">
  43250. * <div (click)="toggle()">Toggle</div>
  43251. * <div [hidden]="!visible">
  43252. * <ng-content></ng-content>
  43253. * </div>
  43254. * </div>`})
  43255. * export class Zippy {
  43256. * visible: boolean = true;
  43257. * @Output() open: EventEmitter<any> = new EventEmitter();
  43258. * @Output() close: EventEmitter<any> = new EventEmitter();
  43259. *
  43260. * toggle() {
  43261. * this.visible = !this.visible;
  43262. * if (this.visible) {
  43263. * this.open.emit(null);
  43264. * } else {
  43265. * this.close.emit(null);
  43266. * }
  43267. * }
  43268. * }
  43269. * ```
  43270. *
  43271. * Access the event object with the `$event` argument passed to the output event
  43272. * handler:
  43273. *
  43274. * ```html
  43275. * <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>
  43276. * ```
  43277. *
  43278. * @publicApi
  43279. */
  43280. var EventEmitter = /** @class */ (function (_super) {
  43281. __extends(EventEmitter, _super);
  43282. /**
  43283. * Creates an instance of this class that can
  43284. * deliver events synchronously or asynchronously.
  43285. *
  43286. * @param isAsync When true, deliver events asynchronously.
  43287. *
  43288. */
  43289. function EventEmitter(isAsync) {
  43290. if (isAsync === void 0) { isAsync = false; }
  43291. var _this = _super.call(this) || this;
  43292. _this.__isAsync = isAsync;
  43293. return _this;
  43294. }
  43295. /**
  43296. * Emits an event containing a given value.
  43297. * @param value The value to emit.
  43298. */
  43299. EventEmitter.prototype.emit = function (value) { _super.prototype.next.call(this, value); };
  43300. /**
  43301. * Registers handlers for events emitted by this instance.
  43302. * @param generatorOrNext When supplied, a custom handler for emitted events.
  43303. * @param error When supplied, a custom handler for an error notification
  43304. * from this emitter.
  43305. * @param complete When supplied, a custom handler for a completion
  43306. * notification from this emitter.
  43307. */
  43308. EventEmitter.prototype.subscribe = function (generatorOrNext, error, complete) {
  43309. var schedulerFn;
  43310. var errorFn = function (err) { return null; };
  43311. var completeFn = function () { return null; };
  43312. if (generatorOrNext && typeof generatorOrNext === 'object') {
  43313. schedulerFn = this.__isAsync ? function (value) {
  43314. setTimeout(function () { return generatorOrNext.next(value); });
  43315. } : function (value) { generatorOrNext.next(value); };
  43316. if (generatorOrNext.error) {
  43317. errorFn = this.__isAsync ? function (err) { setTimeout(function () { return generatorOrNext.error(err); }); } :
  43318. function (err) { generatorOrNext.error(err); };
  43319. }
  43320. if (generatorOrNext.complete) {
  43321. completeFn = this.__isAsync ? function () { setTimeout(function () { return generatorOrNext.complete(); }); } :
  43322. function () { generatorOrNext.complete(); };
  43323. }
  43324. }
  43325. else {
  43326. schedulerFn = this.__isAsync ? function (value) { setTimeout(function () { return generatorOrNext(value); }); } :
  43327. function (value) { generatorOrNext(value); };
  43328. if (error) {
  43329. errorFn =
  43330. this.__isAsync ? function (err) { setTimeout(function () { return error(err); }); } : function (err) { error(err); };
  43331. }
  43332. if (complete) {
  43333. completeFn =
  43334. this.__isAsync ? function () { setTimeout(function () { return complete(); }); } : function () { complete(); };
  43335. }
  43336. }
  43337. var sink = _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn);
  43338. if (generatorOrNext instanceof Subscription) {
  43339. generatorOrNext.add(sink);
  43340. }
  43341. return sink;
  43342. };
  43343. return EventEmitter;
  43344. }(Subject));
  43345. /**
  43346. * @license
  43347. * Copyright Google Inc. All Rights Reserved.
  43348. *
  43349. * Use of this source code is governed by an MIT-style license that can be
  43350. * found in the LICENSE file at https://angular.io/license
  43351. */
  43352. function symbolIterator() {
  43353. return this._results[getSymbolIterator()]();
  43354. }
  43355. /**
  43356. * An unmodifiable list of items that Angular keeps up to date when the state
  43357. * of the application changes.
  43358. *
  43359. * The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}
  43360. * provide.
  43361. *
  43362. * Implements an iterable interface, therefore it can be used in both ES6
  43363. * javascript `for (var i of items)` loops as well as in Angular templates with
  43364. * `*ngFor="let i of myList"`.
  43365. *
  43366. * Changes can be observed by subscribing to the changes `Observable`.
  43367. *
  43368. * NOTE: In the future this class will implement an `Observable` interface.
  43369. *
  43370. * @usageNotes
  43371. * ### Example
  43372. * ```typescript
  43373. * @Component({...})
  43374. * class Container {
  43375. * @ViewChildren(Item) items:QueryList<Item>;
  43376. * }
  43377. * ```
  43378. *
  43379. * @publicApi
  43380. */
  43381. var QueryList = /** @class */ (function () {
  43382. function QueryList() {
  43383. this.dirty = true;
  43384. this._results = [];
  43385. this.changes = new EventEmitter();
  43386. this.length = 0;
  43387. // This function should be declared on the prototype, but doing so there will cause the class
  43388. // declaration to have side-effects and become not tree-shakable. For this reason we do it in
  43389. // the constructor.
  43390. // [getSymbolIterator()](): Iterator<T> { ... }
  43391. var symbol = getSymbolIterator();
  43392. var proto = QueryList.prototype;
  43393. if (!proto[symbol])
  43394. proto[symbol] = symbolIterator;
  43395. }
  43396. /**
  43397. * See
  43398. * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
  43399. */
  43400. QueryList.prototype.map = function (fn) { return this._results.map(fn); };
  43401. /**
  43402. * See
  43403. * [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
  43404. */
  43405. QueryList.prototype.filter = function (fn) {
  43406. return this._results.filter(fn);
  43407. };
  43408. /**
  43409. * See
  43410. * [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
  43411. */
  43412. QueryList.prototype.find = function (fn) {
  43413. return this._results.find(fn);
  43414. };
  43415. /**
  43416. * See
  43417. * [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
  43418. */
  43419. QueryList.prototype.reduce = function (fn, init) {
  43420. return this._results.reduce(fn, init);
  43421. };
  43422. /**
  43423. * See
  43424. * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
  43425. */
  43426. QueryList.prototype.forEach = function (fn) { this._results.forEach(fn); };
  43427. /**
  43428. * See
  43429. * [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
  43430. */
  43431. QueryList.prototype.some = function (fn) {
  43432. return this._results.some(fn);
  43433. };
  43434. /**
  43435. * Returns a copy of the internal results list as an Array.
  43436. */
  43437. QueryList.prototype.toArray = function () { return this._results.slice(); };
  43438. QueryList.prototype.toString = function () { return this._results.toString(); };
  43439. /**
  43440. * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
  43441. * on change detection, it will not notify of changes to the queries, unless a new change
  43442. * occurs.
  43443. *
  43444. * @param resultsTree The results tree to store
  43445. */
  43446. QueryList.prototype.reset = function (resultsTree) {
  43447. this._results = flatten$2(resultsTree);
  43448. this.dirty = false;
  43449. this.length = this._results.length;
  43450. this.last = this._results[this.length - 1];
  43451. this.first = this._results[0];
  43452. };
  43453. /**
  43454. * Triggers a change event by emitting on the `changes` {@link EventEmitter}.
  43455. */
  43456. QueryList.prototype.notifyOnChanges = function () { this.changes.emit(this); };
  43457. /** internal */
  43458. QueryList.prototype.setDirty = function () { this.dirty = true; };
  43459. /** internal */
  43460. QueryList.prototype.destroy = function () {
  43461. this.changes.complete();
  43462. this.changes.unsubscribe();
  43463. };
  43464. return QueryList;
  43465. }());
  43466. /**
  43467. * @license
  43468. * Copyright Google Inc. All Rights Reserved.
  43469. *
  43470. * Use of this source code is governed by an MIT-style license that can be
  43471. * found in the LICENSE file at https://angular.io/license
  43472. */
  43473. /**
  43474. * @license
  43475. * Copyright Google Inc. All Rights Reserved.
  43476. *
  43477. * Use of this source code is governed by an MIT-style license that can be
  43478. * found in the LICENSE file at https://angular.io/license
  43479. */
  43480. /**
  43481. * @license
  43482. * Copyright Google Inc. All Rights Reserved.
  43483. *
  43484. * Use of this source code is governed by an MIT-style license that can be
  43485. * found in the LICENSE file at https://angular.io/license
  43486. */
  43487. /**
  43488. * @license
  43489. * Copyright Google Inc. All Rights Reserved.
  43490. *
  43491. * Use of this source code is governed by an MIT-style license that can be
  43492. * found in the LICENSE file at https://angular.io/license
  43493. */
  43494. /**
  43495. * @license
  43496. * Copyright Google Inc. All Rights Reserved.
  43497. *
  43498. * Use of this source code is governed by an MIT-style license that can be
  43499. * found in the LICENSE file at https://angular.io/license
  43500. */
  43501. /**
  43502. * @license
  43503. * Copyright Google Inc. All Rights Reserved.
  43504. *
  43505. * Use of this source code is governed by an MIT-style license that can be
  43506. * found in the LICENSE file at https://angular.io/license
  43507. */
  43508. /**
  43509. * @license
  43510. * Copyright Google Inc. All Rights Reserved.
  43511. *
  43512. * Use of this source code is governed by an MIT-style license that can be
  43513. * found in the LICENSE file at https://angular.io/license
  43514. */
  43515. /**
  43516. * @license
  43517. * Copyright Google Inc. All Rights Reserved.
  43518. *
  43519. * Use of this source code is governed by an MIT-style license that can be
  43520. * found in the LICENSE file at https://angular.io/license
  43521. */
  43522. /**
  43523. * @license
  43524. * Copyright Google Inc. All Rights Reserved.
  43525. *
  43526. * Use of this source code is governed by an MIT-style license that can be
  43527. * found in the LICENSE file at https://angular.io/license
  43528. */
  43529. /**
  43530. * @license
  43531. * Copyright Google Inc. All Rights Reserved.
  43532. *
  43533. * Use of this source code is governed by an MIT-style license that can be
  43534. * found in the LICENSE file at https://angular.io/license
  43535. */
  43536. var ɵ0$9 = function (dir) {
  43537. if (dir === void 0) { dir = {}; }
  43538. return dir;
  43539. }, ɵ1$2 = function (type, meta) { return SWITCH_COMPILE_DIRECTIVE(type, meta); };
  43540. /**
  43541. * Type of the Directive metadata.
  43542. *
  43543. * @publicApi
  43544. */
  43545. var Directive = makeDecorator('Directive', ɵ0$9, undefined, undefined, ɵ1$2);
  43546. var ɵ2$1 = function (c) {
  43547. if (c === void 0) { c = {}; }
  43548. return (__assign({ changeDetection: ChangeDetectionStrategy$1.Default }, c));
  43549. }, ɵ3$1 = function (type, meta) { return SWITCH_COMPILE_COMPONENT(type, meta); };
  43550. /**
  43551. * Component decorator and metadata.
  43552. *
  43553. * @Annotation
  43554. * @publicApi
  43555. */
  43556. var Component = makeDecorator('Component', ɵ2$1, Directive, undefined, ɵ3$1);
  43557. var ɵ4 = function (p) { return (__assign({ pure: true }, p)); }, ɵ5 = function (type, meta) { return SWITCH_COMPILE_PIPE(type, meta); };
  43558. /**
  43559. * @Annotation
  43560. * @publicApi
  43561. */
  43562. var Pipe = makeDecorator('Pipe', ɵ4, undefined, undefined, ɵ5);
  43563. var ɵ6 = function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); };
  43564. /**
  43565. * @Annotation
  43566. * @publicApi
  43567. */
  43568. var Input = makePropDecorator('Input', ɵ6);
  43569. var ɵ7 = function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); };
  43570. /**
  43571. * @Annotation
  43572. * @publicApi
  43573. */
  43574. var Output = makePropDecorator('Output', ɵ7);
  43575. var ɵ8 = function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); };
  43576. /**
  43577. * @Annotation
  43578. * @publicApi
  43579. */
  43580. var HostBinding = makePropDecorator('HostBinding', ɵ8);
  43581. var ɵ9 = function (eventName, args) { return ({ eventName: eventName, args: args }); };
  43582. /**
  43583. * Decorator that binds a DOM event to a host listener and supplies configuration metadata.
  43584. * Angular invokes the supplied handler method when the host element emits the specified event,
  43585. * and updates the bound element with the result.
  43586. *
  43587. * If the handler method returns false, applies `preventDefault` on the bound element.
  43588. *
  43589. * @usageNotes
  43590. *
  43591. * The following example declares a directive
  43592. * that attaches a click listener to a button and counts clicks.
  43593. *
  43594. * ```ts
  43595. * @Directive({selector: 'button[counting]'})
  43596. * class CountClicks {
  43597. * numberOfClicks = 0;
  43598. *
  43599. * @HostListener('click', ['$event.target'])
  43600. * onClick(btn) {
  43601. * console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
  43602. * }
  43603. * }
  43604. *
  43605. * @Component({
  43606. * selector: 'app',
  43607. * template: '<button counting>Increment</button>',
  43608. * })
  43609. * class App {}
  43610. * ```
  43611. *
  43612. * @Annotation
  43613. * @publicApi
  43614. */
  43615. var HostListener = makePropDecorator('HostListener', ɵ9);
  43616. var SWITCH_COMPILE_COMPONENT__PRE_R3__ = noop;
  43617. var SWITCH_COMPILE_DIRECTIVE__PRE_R3__ = noop;
  43618. var SWITCH_COMPILE_PIPE__PRE_R3__ = noop;
  43619. var SWITCH_COMPILE_COMPONENT = SWITCH_COMPILE_COMPONENT__PRE_R3__;
  43620. var SWITCH_COMPILE_DIRECTIVE = SWITCH_COMPILE_DIRECTIVE__PRE_R3__;
  43621. var SWITCH_COMPILE_PIPE = SWITCH_COMPILE_PIPE__PRE_R3__;
  43622. /**
  43623. * @license
  43624. * Copyright Google Inc. All Rights Reserved.
  43625. *
  43626. * Use of this source code is governed by an MIT-style license that can be
  43627. * found in the LICENSE file at https://angular.io/license
  43628. */
  43629. var ɵ0$a = function (ngModule) { return ngModule; }, ɵ1$3 =
  43630. /**
  43631. * Decorator that marks the following class as an NgModule, and supplies
  43632. * configuration metadata for it.
  43633. *
  43634. * * The `declarations` and `entryComponents` options configure the compiler
  43635. * with information about what belongs to the NgModule.
  43636. * * The `providers` options configures the NgModule's injector to provide
  43637. * dependencies the NgModule members.
  43638. * * The `imports` and `exports` options bring in members from other modules, and make
  43639. * this module's members available to others.
  43640. */
  43641. function (type, meta) { return SWITCH_COMPILE_NGMODULE(type, meta); };
  43642. /**
  43643. * @Annotation
  43644. * @publicApi
  43645. */
  43646. var NgModule = makeDecorator('NgModule', ɵ0$a, undefined, undefined, ɵ1$3);
  43647. function preR3NgModuleCompile(moduleType, metadata) {
  43648. var imports = (metadata && metadata.imports) || [];
  43649. if (metadata && metadata.exports) {
  43650. imports = __spread(imports, [metadata.exports]);
  43651. }
  43652. moduleType.ngInjectorDef = ɵɵdefineInjector({
  43653. factory: convertInjectableProviderToFactory(moduleType, { useClass: moduleType }),
  43654. providers: metadata && metadata.providers,
  43655. imports: imports,
  43656. });
  43657. }
  43658. var SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
  43659. var SWITCH_COMPILE_NGMODULE = SWITCH_COMPILE_NGMODULE__PRE_R3__;
  43660. /**
  43661. * @license
  43662. * Copyright Google Inc. All Rights Reserved.
  43663. *
  43664. * Use of this source code is governed by an MIT-style license that can be
  43665. * found in the LICENSE file at https://angular.io/license
  43666. */
  43667. function multicast(subjectOrSubjectFactory, selector) {
  43668. return function multicastOperatorFunction(source) {
  43669. let subjectFactory;
  43670. if (typeof subjectOrSubjectFactory === 'function') {
  43671. subjectFactory = subjectOrSubjectFactory;
  43672. }
  43673. else {
  43674. subjectFactory = function subjectFactory() {
  43675. return subjectOrSubjectFactory;
  43676. };
  43677. }
  43678. if (typeof selector === 'function') {
  43679. return source.lift(new MulticastOperator(subjectFactory, selector));
  43680. }
  43681. const connectable = Object.create(source, connectableObservableDescriptor);
  43682. connectable.source = source;
  43683. connectable.subjectFactory = subjectFactory;
  43684. return connectable;
  43685. };
  43686. }
  43687. class MulticastOperator {
  43688. constructor(subjectFactory, selector) {
  43689. this.subjectFactory = subjectFactory;
  43690. this.selector = selector;
  43691. }
  43692. call(subscriber, source) {
  43693. const { selector } = this;
  43694. const subject = this.subjectFactory();
  43695. const subscription = selector(subject).subscribe(subscriber);
  43696. subscription.add(source.subscribe(subject));
  43697. return subscription;
  43698. }
  43699. }
  43700. function shareSubjectFactory() {
  43701. return new Subject();
  43702. }
  43703. function share() {
  43704. return (source) => refCount()(multicast(shareSubjectFactory)(source));
  43705. }
  43706. /**
  43707. * @license
  43708. * Copyright Google Inc. All Rights Reserved.
  43709. *
  43710. * Use of this source code is governed by an MIT-style license that can be
  43711. * found in the LICENSE file at https://angular.io/license
  43712. */
  43713. /**
  43714. * A function that will be executed when an application is initialized.
  43715. *
  43716. * @publicApi
  43717. */
  43718. var APP_INITIALIZER = new InjectionToken('Application Initializer');
  43719. /**
  43720. * A class that reflects the state of running {@link APP_INITIALIZER}s.
  43721. *
  43722. * @publicApi
  43723. */
  43724. var ApplicationInitStatus = /** @class */ (function () {
  43725. function ApplicationInitStatus(appInits) {
  43726. var _this = this;
  43727. this.appInits = appInits;
  43728. this.initialized = false;
  43729. this.done = false;
  43730. this.donePromise = new Promise(function (res, rej) {
  43731. _this.resolve = res;
  43732. _this.reject = rej;
  43733. });
  43734. }
  43735. /** @internal */
  43736. ApplicationInitStatus.prototype.runInitializers = function () {
  43737. var _this = this;
  43738. if (this.initialized) {
  43739. return;
  43740. }
  43741. var asyncInitPromises = [];
  43742. var complete = function () {
  43743. _this.done = true;
  43744. _this.resolve();
  43745. };
  43746. if (this.appInits) {
  43747. for (var i = 0; i < this.appInits.length; i++) {
  43748. var initResult = this.appInits[i]();
  43749. if (isPromise$1(initResult)) {
  43750. asyncInitPromises.push(initResult);
  43751. }
  43752. }
  43753. }
  43754. Promise.all(asyncInitPromises).then(function () { complete(); }).catch(function (e) { _this.reject(e); });
  43755. if (asyncInitPromises.length === 0) {
  43756. complete();
  43757. }
  43758. this.initialized = true;
  43759. };
  43760. ApplicationInitStatus = __decorate([
  43761. Injectable(),
  43762. __param(0, Inject(APP_INITIALIZER)), __param(0, Optional()),
  43763. __metadata("design:paramtypes", [Array])
  43764. ], ApplicationInitStatus);
  43765. return ApplicationInitStatus;
  43766. }());
  43767. /**
  43768. * @license
  43769. * Copyright Google Inc. All Rights Reserved.
  43770. *
  43771. * Use of this source code is governed by an MIT-style license that can be
  43772. * found in the LICENSE file at https://angular.io/license
  43773. */
  43774. /**
  43775. * A DI Token representing a unique string id assigned to the application by Angular and used
  43776. * primarily for prefixing application attributes and CSS styles when
  43777. * {@link ViewEncapsulation#Emulated ViewEncapsulation.Emulated} is being used.
  43778. *
  43779. * If you need to avoid randomly generated value to be used as an application id, you can provide
  43780. * a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector}
  43781. * using this token.
  43782. * @publicApi
  43783. */
  43784. var APP_ID = new InjectionToken('AppId');
  43785. function _appIdRandomProviderFactory() {
  43786. return "" + _randomChar() + _randomChar() + _randomChar();
  43787. }
  43788. /**
  43789. * Providers that will generate a random APP_ID_TOKEN.
  43790. * @publicApi
  43791. */
  43792. var APP_ID_RANDOM_PROVIDER = {
  43793. provide: APP_ID,
  43794. useFactory: _appIdRandomProviderFactory,
  43795. deps: [],
  43796. };
  43797. function _randomChar() {
  43798. return String.fromCharCode(97 + Math.floor(Math.random() * 25));
  43799. }
  43800. /**
  43801. * A function that will be executed when a platform is initialized.
  43802. * @publicApi
  43803. */
  43804. var PLATFORM_INITIALIZER = new InjectionToken('Platform Initializer');
  43805. /**
  43806. * A token that indicates an opaque platform id.
  43807. * @publicApi
  43808. */
  43809. var PLATFORM_ID = new InjectionToken('Platform ID');
  43810. /**
  43811. * All callbacks provided via this token will be called for every component that is bootstrapped.
  43812. * Signature of the callback:
  43813. *
  43814. * `(componentRef: ComponentRef) => void`.
  43815. *
  43816. * @publicApi
  43817. */
  43818. var APP_BOOTSTRAP_LISTENER = new InjectionToken('appBootstrapListener');
  43819. /**
  43820. * A token which indicates the root directory of the application
  43821. * @publicApi
  43822. */
  43823. var PACKAGE_ROOT_URL = new InjectionToken('Application Packages Root URL');
  43824. /**
  43825. * @license
  43826. * Copyright Google Inc. All Rights Reserved.
  43827. *
  43828. * Use of this source code is governed by an MIT-style license that can be
  43829. * found in the LICENSE file at https://angular.io/license
  43830. */
  43831. var Console = /** @class */ (function () {
  43832. function Console() {
  43833. }
  43834. Console.prototype.log = function (message) {
  43835. // tslint:disable-next-line:no-console
  43836. console.log(message);
  43837. };
  43838. // Note: for reporting errors use `DOM.logError()` as it is platform specific
  43839. Console.prototype.warn = function (message) {
  43840. // tslint:disable-next-line:no-console
  43841. console.warn(message);
  43842. };
  43843. Console = __decorate([
  43844. Injectable()
  43845. ], Console);
  43846. return Console;
  43847. }());
  43848. /**
  43849. * @license
  43850. * Copyright Google Inc. All Rights Reserved.
  43851. *
  43852. * Use of this source code is governed by an MIT-style license that can be
  43853. * found in the LICENSE file at https://angular.io/license
  43854. */
  43855. /**
  43856. * Provide this token to set the locale of your application.
  43857. * It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe,
  43858. * DecimalPipe and PercentPipe) and by ICU expressions.
  43859. *
  43860. * See the [i18n guide](guide/i18n#setting-up-locale) for more information.
  43861. *
  43862. * @usageNotes
  43863. * ### Example
  43864. *
  43865. * ```typescript
  43866. * import { LOCALE_ID } from '@angular/core';
  43867. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  43868. * import { AppModule } from './app/app.module';
  43869. *
  43870. * platformBrowserDynamic().bootstrapModule(AppModule, {
  43871. * providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
  43872. * });
  43873. * ```
  43874. *
  43875. * @publicApi
  43876. */
  43877. var LOCALE_ID$1 = new InjectionToken('LocaleId');
  43878. /**
  43879. * Use this token at bootstrap to provide the content of your translation file (`xtb`,
  43880. * `xlf` or `xlf2`) when you want to translate your application in another language.
  43881. *
  43882. * See the [i18n guide](guide/i18n#merge) for more information.
  43883. *
  43884. * @usageNotes
  43885. * ### Example
  43886. *
  43887. * ```typescript
  43888. * import { TRANSLATIONS } from '@angular/core';
  43889. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  43890. * import { AppModule } from './app/app.module';
  43891. *
  43892. * // content of your translation file
  43893. * const translations = '....';
  43894. *
  43895. * platformBrowserDynamic().bootstrapModule(AppModule, {
  43896. * providers: [{provide: TRANSLATIONS, useValue: translations }]
  43897. * });
  43898. * ```
  43899. *
  43900. * @publicApi
  43901. */
  43902. var TRANSLATIONS = new InjectionToken('Translations');
  43903. /**
  43904. * Provide this token at bootstrap to set the format of your {@link TRANSLATIONS}: `xtb`,
  43905. * `xlf` or `xlf2`.
  43906. *
  43907. * See the [i18n guide](guide/i18n#merge) for more information.
  43908. *
  43909. * @usageNotes
  43910. * ### Example
  43911. *
  43912. * ```typescript
  43913. * import { TRANSLATIONS_FORMAT } from '@angular/core';
  43914. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  43915. * import { AppModule } from './app/app.module';
  43916. *
  43917. * platformBrowserDynamic().bootstrapModule(AppModule, {
  43918. * providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }]
  43919. * });
  43920. * ```
  43921. *
  43922. * @publicApi
  43923. */
  43924. var TRANSLATIONS_FORMAT = new InjectionToken('TranslationsFormat');
  43925. /**
  43926. * Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy
  43927. * that the compiler should use in case of missing translations:
  43928. * - Error: throw if you have missing translations.
  43929. * - Warning (default): show a warning in the console and/or shell.
  43930. * - Ignore: do nothing.
  43931. *
  43932. * See the [i18n guide](guide/i18n#missing-translation) for more information.
  43933. *
  43934. * @usageNotes
  43935. * ### Example
  43936. * ```typescript
  43937. * import { MissingTranslationStrategy } from '@angular/core';
  43938. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  43939. * import { AppModule } from './app/app.module';
  43940. *
  43941. * platformBrowserDynamic().bootstrapModule(AppModule, {
  43942. * missingTranslation: MissingTranslationStrategy.Error
  43943. * });
  43944. * ```
  43945. *
  43946. * @publicApi
  43947. */
  43948. var MissingTranslationStrategy$1;
  43949. (function (MissingTranslationStrategy) {
  43950. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  43951. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  43952. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  43953. })(MissingTranslationStrategy$1 || (MissingTranslationStrategy$1 = {}));
  43954. /**
  43955. * @license
  43956. * Copyright Google Inc. All Rights Reserved.
  43957. *
  43958. * Use of this source code is governed by an MIT-style license that can be
  43959. * found in the LICENSE file at https://angular.io/license
  43960. */
  43961. function _throwError() {
  43962. throw new Error("Runtime compiler is not loaded");
  43963. }
  43964. var Compiler_compileModuleSync__PRE_R3__ = _throwError;
  43965. var Compiler_compileModuleSync = Compiler_compileModuleSync__PRE_R3__;
  43966. var Compiler_compileModuleAsync__PRE_R3__ = _throwError;
  43967. var Compiler_compileModuleAsync = Compiler_compileModuleAsync__PRE_R3__;
  43968. var Compiler_compileModuleAndAllComponentsSync__PRE_R3__ = _throwError;
  43969. var Compiler_compileModuleAndAllComponentsSync = Compiler_compileModuleAndAllComponentsSync__PRE_R3__;
  43970. var Compiler_compileModuleAndAllComponentsAsync__PRE_R3__ = _throwError;
  43971. var Compiler_compileModuleAndAllComponentsAsync = Compiler_compileModuleAndAllComponentsAsync__PRE_R3__;
  43972. /**
  43973. * Low-level service for running the angular compiler during runtime
  43974. * to create {@link ComponentFactory}s, which
  43975. * can later be used to create and render a Component instance.
  43976. *
  43977. * Each `@NgModule` provides an own `Compiler` to its injector,
  43978. * that will use the directives/pipes of the ng module for compilation
  43979. * of components.
  43980. *
  43981. * @publicApi
  43982. */
  43983. var Compiler = /** @class */ (function () {
  43984. function Compiler() {
  43985. /**
  43986. * Compiles the given NgModule and all of its components. All templates of the components listed
  43987. * in `entryComponents` have to be inlined.
  43988. */
  43989. this.compileModuleSync = Compiler_compileModuleSync;
  43990. /**
  43991. * Compiles the given NgModule and all of its components
  43992. */
  43993. this.compileModuleAsync = Compiler_compileModuleAsync;
  43994. /**
  43995. * Same as {@link #compileModuleSync} but also creates ComponentFactories for all components.
  43996. */
  43997. this.compileModuleAndAllComponentsSync = Compiler_compileModuleAndAllComponentsSync;
  43998. /**
  43999. * Same as {@link #compileModuleAsync} but also creates ComponentFactories for all components.
  44000. */
  44001. this.compileModuleAndAllComponentsAsync = Compiler_compileModuleAndAllComponentsAsync;
  44002. }
  44003. /**
  44004. * Clears all caches.
  44005. */
  44006. Compiler.prototype.clearCache = function () { };
  44007. /**
  44008. * Clears the cache for the given component/ngModule.
  44009. */
  44010. Compiler.prototype.clearCacheFor = function (type) { };
  44011. /**
  44012. * Returns the id for a given NgModule, if one is defined and known to the compiler.
  44013. */
  44014. Compiler.prototype.getModuleId = function (moduleType) { return undefined; };
  44015. Compiler = __decorate([
  44016. Injectable()
  44017. ], Compiler);
  44018. return Compiler;
  44019. }());
  44020. /**
  44021. * Token to provide CompilerOptions in the platform injector.
  44022. *
  44023. * @publicApi
  44024. */
  44025. var COMPILER_OPTIONS = new InjectionToken('compilerOptions');
  44026. /**
  44027. * A factory for creating a Compiler
  44028. *
  44029. * @publicApi
  44030. */
  44031. var CompilerFactory = /** @class */ (function () {
  44032. function CompilerFactory() {
  44033. }
  44034. return CompilerFactory;
  44035. }());
  44036. /**
  44037. * @license
  44038. * Copyright Google Inc. All Rights Reserved.
  44039. *
  44040. * Use of this source code is governed by an MIT-style license that can be
  44041. * found in the LICENSE file at https://angular.io/license
  44042. */
  44043. var trace;
  44044. var events;
  44045. function detectWTF() {
  44046. var wtf = _global$1 /** TODO #9100 */['wtf'];
  44047. if (wtf) {
  44048. trace = wtf['trace'];
  44049. if (trace) {
  44050. events = trace['events'];
  44051. return true;
  44052. }
  44053. }
  44054. return false;
  44055. }
  44056. function createScope(signature, flags) {
  44057. if (flags === void 0) { flags = null; }
  44058. return events.createScope(signature, flags);
  44059. }
  44060. function leave(scope, returnValue) {
  44061. trace.leaveScope(scope, returnValue);
  44062. return returnValue;
  44063. }
  44064. /**
  44065. * @license
  44066. * Copyright Google Inc. All Rights Reserved.
  44067. *
  44068. * Use of this source code is governed by an MIT-style license that can be
  44069. * found in the LICENSE file at https://angular.io/license
  44070. */
  44071. /**
  44072. * True if WTF is enabled.
  44073. */
  44074. var wtfEnabled = detectWTF();
  44075. function noopScope(arg0, arg1) {
  44076. return null;
  44077. }
  44078. /**
  44079. * Create trace scope.
  44080. *
  44081. * Scopes must be strictly nested and are analogous to stack frames, but
  44082. * do not have to follow the stack frames. Instead it is recommended that they follow logical
  44083. * nesting. You may want to use
  44084. * [Event
  44085. * Signatures](http://google.github.io/tracing-framework/instrumenting-code.html#custom-events)
  44086. * as they are defined in WTF.
  44087. *
  44088. * Used to mark scope entry. The return value is used to leave the scope.
  44089. *
  44090. * var myScope = wtfCreateScope('MyClass#myMethod(ascii someVal)');
  44091. *
  44092. * someMethod() {
  44093. * var s = myScope('Foo'); // 'Foo' gets stored in tracing UI
  44094. * // DO SOME WORK HERE
  44095. * return wtfLeave(s, 123); // Return value 123
  44096. * }
  44097. *
  44098. * Note, adding try-finally block around the work to ensure that `wtfLeave` gets called can
  44099. * negatively impact the performance of your application. For this reason we recommend that
  44100. * you don't add them to ensure that `wtfLeave` gets called. In production `wtfLeave` is a noop and
  44101. * so try-finally block has no value. When debugging perf issues, skipping `wtfLeave`, do to
  44102. * exception, will produce incorrect trace, but presence of exception signifies logic error which
  44103. * needs to be fixed before the app should be profiled. Add try-finally only when you expect that
  44104. * an exception is expected during normal execution while profiling.
  44105. *
  44106. * @publicApi
  44107. * @deprecated the Web Tracing Framework is no longer supported in Angular
  44108. */
  44109. var wtfCreateScope = wtfEnabled ? createScope : function (signature, flags) { return noopScope; };
  44110. /**
  44111. * Used to mark end of Scope.
  44112. *
  44113. * - `scope` to end.
  44114. * - `returnValue` (optional) to be passed to the WTF.
  44115. *
  44116. * Returns the `returnValue for easy chaining.
  44117. * @publicApi
  44118. * @deprecated the Web Tracing Framework is no longer supported in Angular
  44119. */
  44120. var wtfLeave = wtfEnabled ? leave : function (s, r) { return r; };
  44121. /**
  44122. * @license
  44123. * Copyright Google Inc. All Rights Reserved.
  44124. *
  44125. * Use of this source code is governed by an MIT-style license that can be
  44126. * found in the LICENSE file at https://angular.io/license
  44127. */
  44128. var promise = (function () { return Promise.resolve(0); })();
  44129. function scheduleMicroTask(fn) {
  44130. if (typeof Zone === 'undefined') {
  44131. // use promise to schedule microTask instead of use Zone
  44132. promise.then(function () { fn && fn.apply(null, null); });
  44133. }
  44134. else {
  44135. Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
  44136. }
  44137. }
  44138. /**
  44139. * @license
  44140. * Copyright Google Inc. All Rights Reserved.
  44141. *
  44142. * Use of this source code is governed by an MIT-style license that can be
  44143. * found in the LICENSE file at https://angular.io/license
  44144. */
  44145. /**
  44146. * An injectable service for executing work inside or outside of the Angular zone.
  44147. *
  44148. * The most common use of this service is to optimize performance when starting a work consisting of
  44149. * one or more asynchronous tasks that don't require UI updates or error handling to be handled by
  44150. * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
  44151. * can reenter the Angular zone via {@link #run}.
  44152. *
  44153. * <!-- TODO: add/fix links to:
  44154. * - docs explaining zones and the use of zones in Angular and change-detection
  44155. * - link to runOutsideAngular/run (throughout this file!)
  44156. * -->
  44157. *
  44158. * @usageNotes
  44159. * ### Example
  44160. *
  44161. * ```
  44162. * import {Component, NgZone} from '@angular/core';
  44163. * import {NgIf} from '@angular/common';
  44164. *
  44165. * @Component({
  44166. * selector: 'ng-zone-demo',
  44167. * template: `
  44168. * <h2>Demo: NgZone</h2>
  44169. *
  44170. * <p>Progress: {{progress}}%</p>
  44171. * <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
  44172. *
  44173. * <button (click)="processWithinAngularZone()">Process within Angular zone</button>
  44174. * <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
  44175. * `,
  44176. * })
  44177. * export class NgZoneDemo {
  44178. * progress: number = 0;
  44179. * label: string;
  44180. *
  44181. * constructor(private _ngZone: NgZone) {}
  44182. *
  44183. * // Loop inside the Angular zone
  44184. * // so the UI DOES refresh after each setTimeout cycle
  44185. * processWithinAngularZone() {
  44186. * this.label = 'inside';
  44187. * this.progress = 0;
  44188. * this._increaseProgress(() => console.log('Inside Done!'));
  44189. * }
  44190. *
  44191. * // Loop outside of the Angular zone
  44192. * // so the UI DOES NOT refresh after each setTimeout cycle
  44193. * processOutsideOfAngularZone() {
  44194. * this.label = 'outside';
  44195. * this.progress = 0;
  44196. * this._ngZone.runOutsideAngular(() => {
  44197. * this._increaseProgress(() => {
  44198. * // reenter the Angular zone and display done
  44199. * this._ngZone.run(() => { console.log('Outside Done!'); });
  44200. * });
  44201. * });
  44202. * }
  44203. *
  44204. * _increaseProgress(doneCallback: () => void) {
  44205. * this.progress += 1;
  44206. * console.log(`Current progress: ${this.progress}%`);
  44207. *
  44208. * if (this.progress < 100) {
  44209. * window.setTimeout(() => this._increaseProgress(doneCallback), 10);
  44210. * } else {
  44211. * doneCallback();
  44212. * }
  44213. * }
  44214. * }
  44215. * ```
  44216. *
  44217. * @publicApi
  44218. */
  44219. var NgZone = /** @class */ (function () {
  44220. function NgZone(_a) {
  44221. var _b = _a.enableLongStackTrace, enableLongStackTrace = _b === void 0 ? false : _b;
  44222. this.hasPendingMicrotasks = false;
  44223. this.hasPendingMacrotasks = false;
  44224. /**
  44225. * Whether there are no outstanding microtasks or macrotasks.
  44226. */
  44227. this.isStable = true;
  44228. /**
  44229. * Notifies when code enters Angular Zone. This gets fired first on VM Turn.
  44230. */
  44231. this.onUnstable = new EventEmitter(false);
  44232. /**
  44233. * Notifies when there is no more microtasks enqueued in the current VM Turn.
  44234. * This is a hint for Angular to do change detection, which may enqueue more microtasks.
  44235. * For this reason this event can fire multiple times per VM Turn.
  44236. */
  44237. this.onMicrotaskEmpty = new EventEmitter(false);
  44238. /**
  44239. * Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
  44240. * implies we are about to relinquish VM turn.
  44241. * This event gets called just once.
  44242. */
  44243. this.onStable = new EventEmitter(false);
  44244. /**
  44245. * Notifies that an error has been delivered.
  44246. */
  44247. this.onError = new EventEmitter(false);
  44248. if (typeof Zone == 'undefined') {
  44249. throw new Error("In this configuration Angular requires Zone.js");
  44250. }
  44251. Zone.assertZonePatched();
  44252. var self = this;
  44253. self._nesting = 0;
  44254. self._outer = self._inner = Zone.current;
  44255. if (Zone['wtfZoneSpec']) {
  44256. self._inner = self._inner.fork(Zone['wtfZoneSpec']);
  44257. }
  44258. if (Zone['TaskTrackingZoneSpec']) {
  44259. self._inner = self._inner.fork(new Zone['TaskTrackingZoneSpec']);
  44260. }
  44261. if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {
  44262. self._inner = self._inner.fork(Zone['longStackTraceZoneSpec']);
  44263. }
  44264. forkInnerZoneWithAngularBehavior(self);
  44265. }
  44266. NgZone.isInAngularZone = function () { return Zone.current.get('isAngularZone') === true; };
  44267. NgZone.assertInAngularZone = function () {
  44268. if (!NgZone.isInAngularZone()) {
  44269. throw new Error('Expected to be in Angular Zone, but it is not!');
  44270. }
  44271. };
  44272. NgZone.assertNotInAngularZone = function () {
  44273. if (NgZone.isInAngularZone()) {
  44274. throw new Error('Expected to not be in Angular Zone, but it is!');
  44275. }
  44276. };
  44277. /**
  44278. * Executes the `fn` function synchronously within the Angular zone and returns value returned by
  44279. * the function.
  44280. *
  44281. * Running functions via `run` allows you to reenter Angular zone from a task that was executed
  44282. * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
  44283. *
  44284. * Any future tasks or microtasks scheduled from within this function will continue executing from
  44285. * within the Angular zone.
  44286. *
  44287. * If a synchronous error happens it will be rethrown and not reported via `onError`.
  44288. */
  44289. NgZone.prototype.run = function (fn, applyThis, applyArgs) {
  44290. return this._inner.run(fn, applyThis, applyArgs);
  44291. };
  44292. /**
  44293. * Executes the `fn` function synchronously within the Angular zone as a task and returns value
  44294. * returned by the function.
  44295. *
  44296. * Running functions via `run` allows you to reenter Angular zone from a task that was executed
  44297. * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
  44298. *
  44299. * Any future tasks or microtasks scheduled from within this function will continue executing from
  44300. * within the Angular zone.
  44301. *
  44302. * If a synchronous error happens it will be rethrown and not reported via `onError`.
  44303. */
  44304. NgZone.prototype.runTask = function (fn, applyThis, applyArgs, name) {
  44305. var zone = this._inner;
  44306. var task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop$2, noop$2);
  44307. try {
  44308. return zone.runTask(task, applyThis, applyArgs);
  44309. }
  44310. finally {
  44311. zone.cancelTask(task);
  44312. }
  44313. };
  44314. /**
  44315. * Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
  44316. * rethrown.
  44317. */
  44318. NgZone.prototype.runGuarded = function (fn, applyThis, applyArgs) {
  44319. return this._inner.runGuarded(fn, applyThis, applyArgs);
  44320. };
  44321. /**
  44322. * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
  44323. * the function.
  44324. *
  44325. * Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do
  44326. * work that
  44327. * doesn't trigger Angular change-detection or is subject to Angular's error handling.
  44328. *
  44329. * Any future tasks or microtasks scheduled from within this function will continue executing from
  44330. * outside of the Angular zone.
  44331. *
  44332. * Use {@link #run} to reenter the Angular zone and do work that updates the application model.
  44333. */
  44334. NgZone.prototype.runOutsideAngular = function (fn) {
  44335. return this._outer.run(fn);
  44336. };
  44337. return NgZone;
  44338. }());
  44339. function noop$2() { }
  44340. var EMPTY_PAYLOAD = {};
  44341. function checkStable(zone) {
  44342. if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
  44343. try {
  44344. zone._nesting++;
  44345. zone.onMicrotaskEmpty.emit(null);
  44346. }
  44347. finally {
  44348. zone._nesting--;
  44349. if (!zone.hasPendingMicrotasks) {
  44350. try {
  44351. zone.runOutsideAngular(function () { return zone.onStable.emit(null); });
  44352. }
  44353. finally {
  44354. zone.isStable = true;
  44355. }
  44356. }
  44357. }
  44358. }
  44359. }
  44360. function forkInnerZoneWithAngularBehavior(zone) {
  44361. zone._inner = zone._inner.fork({
  44362. name: 'angular',
  44363. properties: { 'isAngularZone': true },
  44364. onInvokeTask: function (delegate, current, target, task, applyThis, applyArgs) {
  44365. try {
  44366. onEnter(zone);
  44367. return delegate.invokeTask(target, task, applyThis, applyArgs);
  44368. }
  44369. finally {
  44370. onLeave(zone);
  44371. }
  44372. },
  44373. onInvoke: function (delegate, current, target, callback, applyThis, applyArgs, source) {
  44374. try {
  44375. onEnter(zone);
  44376. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  44377. }
  44378. finally {
  44379. onLeave(zone);
  44380. }
  44381. },
  44382. onHasTask: function (delegate, current, target, hasTaskState) {
  44383. delegate.hasTask(target, hasTaskState);
  44384. if (current === target) {
  44385. // We are only interested in hasTask events which originate from our zone
  44386. // (A child hasTask event is not interesting to us)
  44387. if (hasTaskState.change == 'microTask') {
  44388. zone.hasPendingMicrotasks = hasTaskState.microTask;
  44389. checkStable(zone);
  44390. }
  44391. else if (hasTaskState.change == 'macroTask') {
  44392. zone.hasPendingMacrotasks = hasTaskState.macroTask;
  44393. }
  44394. }
  44395. },
  44396. onHandleError: function (delegate, current, target, error) {
  44397. delegate.handleError(target, error);
  44398. zone.runOutsideAngular(function () { return zone.onError.emit(error); });
  44399. return false;
  44400. }
  44401. });
  44402. }
  44403. function onEnter(zone) {
  44404. zone._nesting++;
  44405. if (zone.isStable) {
  44406. zone.isStable = false;
  44407. zone.onUnstable.emit(null);
  44408. }
  44409. }
  44410. function onLeave(zone) {
  44411. zone._nesting--;
  44412. checkStable(zone);
  44413. }
  44414. /**
  44415. * Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
  44416. * to framework to perform rendering.
  44417. */
  44418. var NoopNgZone = /** @class */ (function () {
  44419. function NoopNgZone() {
  44420. this.hasPendingMicrotasks = false;
  44421. this.hasPendingMacrotasks = false;
  44422. this.isStable = true;
  44423. this.onUnstable = new EventEmitter();
  44424. this.onMicrotaskEmpty = new EventEmitter();
  44425. this.onStable = new EventEmitter();
  44426. this.onError = new EventEmitter();
  44427. }
  44428. NoopNgZone.prototype.run = function (fn) { return fn(); };
  44429. NoopNgZone.prototype.runGuarded = function (fn) { return fn(); };
  44430. NoopNgZone.prototype.runOutsideAngular = function (fn) { return fn(); };
  44431. NoopNgZone.prototype.runTask = function (fn) { return fn(); };
  44432. return NoopNgZone;
  44433. }());
  44434. /**
  44435. * @license
  44436. * Copyright Google Inc. All Rights Reserved.
  44437. *
  44438. * Use of this source code is governed by an MIT-style license that can be
  44439. * found in the LICENSE file at https://angular.io/license
  44440. */
  44441. /**
  44442. * The Testability service provides testing hooks that can be accessed from
  44443. * the browser and by services such as Protractor. Each bootstrapped Angular
  44444. * application on the page will have an instance of Testability.
  44445. * @publicApi
  44446. */
  44447. var Testability = /** @class */ (function () {
  44448. function Testability(_ngZone) {
  44449. var _this = this;
  44450. this._ngZone = _ngZone;
  44451. this._pendingCount = 0;
  44452. this._isZoneStable = true;
  44453. /**
  44454. * Whether any work was done since the last 'whenStable' callback. This is
  44455. * useful to detect if this could have potentially destabilized another
  44456. * component while it is stabilizing.
  44457. * @internal
  44458. */
  44459. this._didWork = false;
  44460. this._callbacks = [];
  44461. this.taskTrackingZone = null;
  44462. this._watchAngularEvents();
  44463. _ngZone.run(function () {
  44464. _this.taskTrackingZone =
  44465. typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
  44466. });
  44467. }
  44468. Testability.prototype._watchAngularEvents = function () {
  44469. var _this = this;
  44470. this._ngZone.onUnstable.subscribe({
  44471. next: function () {
  44472. _this._didWork = true;
  44473. _this._isZoneStable = false;
  44474. }
  44475. });
  44476. this._ngZone.runOutsideAngular(function () {
  44477. _this._ngZone.onStable.subscribe({
  44478. next: function () {
  44479. NgZone.assertNotInAngularZone();
  44480. scheduleMicroTask(function () {
  44481. _this._isZoneStable = true;
  44482. _this._runCallbacksIfReady();
  44483. });
  44484. }
  44485. });
  44486. });
  44487. };
  44488. /**
  44489. * Increases the number of pending request
  44490. * @deprecated pending requests are now tracked with zones.
  44491. */
  44492. Testability.prototype.increasePendingRequestCount = function () {
  44493. this._pendingCount += 1;
  44494. this._didWork = true;
  44495. return this._pendingCount;
  44496. };
  44497. /**
  44498. * Decreases the number of pending request
  44499. * @deprecated pending requests are now tracked with zones
  44500. */
  44501. Testability.prototype.decreasePendingRequestCount = function () {
  44502. this._pendingCount -= 1;
  44503. if (this._pendingCount < 0) {
  44504. throw new Error('pending async requests below zero');
  44505. }
  44506. this._runCallbacksIfReady();
  44507. return this._pendingCount;
  44508. };
  44509. /**
  44510. * Whether an associated application is stable
  44511. */
  44512. Testability.prototype.isStable = function () {
  44513. return this._isZoneStable && this._pendingCount === 0 && !this._ngZone.hasPendingMacrotasks;
  44514. };
  44515. Testability.prototype._runCallbacksIfReady = function () {
  44516. var _this = this;
  44517. if (this.isStable()) {
  44518. // Schedules the call backs in a new frame so that it is always async.
  44519. scheduleMicroTask(function () {
  44520. while (_this._callbacks.length !== 0) {
  44521. var cb = _this._callbacks.pop();
  44522. clearTimeout(cb.timeoutId);
  44523. cb.doneCb(_this._didWork);
  44524. }
  44525. _this._didWork = false;
  44526. });
  44527. }
  44528. else {
  44529. // Still not stable, send updates.
  44530. var pending_1 = this.getPendingTasks();
  44531. this._callbacks = this._callbacks.filter(function (cb) {
  44532. if (cb.updateCb && cb.updateCb(pending_1)) {
  44533. clearTimeout(cb.timeoutId);
  44534. return false;
  44535. }
  44536. return true;
  44537. });
  44538. this._didWork = true;
  44539. }
  44540. };
  44541. Testability.prototype.getPendingTasks = function () {
  44542. if (!this.taskTrackingZone) {
  44543. return [];
  44544. }
  44545. // Copy the tasks data so that we don't leak tasks.
  44546. return this.taskTrackingZone.macroTasks.map(function (t) {
  44547. return {
  44548. source: t.source,
  44549. // From TaskTrackingZone:
  44550. // https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
  44551. creationLocation: t.creationLocation,
  44552. data: t.data
  44553. };
  44554. });
  44555. };
  44556. Testability.prototype.addCallback = function (cb, timeout, updateCb) {
  44557. var _this = this;
  44558. var timeoutId = -1;
  44559. if (timeout && timeout > 0) {
  44560. timeoutId = setTimeout(function () {
  44561. _this._callbacks = _this._callbacks.filter(function (cb) { return cb.timeoutId !== timeoutId; });
  44562. cb(_this._didWork, _this.getPendingTasks());
  44563. }, timeout);
  44564. }
  44565. this._callbacks.push({ doneCb: cb, timeoutId: timeoutId, updateCb: updateCb });
  44566. };
  44567. /**
  44568. * Wait for the application to be stable with a timeout. If the timeout is reached before that
  44569. * happens, the callback receives a list of the macro tasks that were pending, otherwise null.
  44570. *
  44571. * @param doneCb The callback to invoke when Angular is stable or the timeout expires
  44572. * whichever comes first.
  44573. * @param timeout Optional. The maximum time to wait for Angular to become stable. If not
  44574. * specified, whenStable() will wait forever.
  44575. * @param updateCb Optional. If specified, this callback will be invoked whenever the set of
  44576. * pending macrotasks changes. If this callback returns true doneCb will not be invoked
  44577. * and no further updates will be issued.
  44578. */
  44579. Testability.prototype.whenStable = function (doneCb, timeout, updateCb) {
  44580. if (updateCb && !this.taskTrackingZone) {
  44581. throw new Error('Task tracking zone is required when passing an update callback to ' +
  44582. 'whenStable(). Is "zone.js/dist/task-tracking.js" loaded?');
  44583. }
  44584. // These arguments are 'Function' above to keep the public API simple.
  44585. this.addCallback(doneCb, timeout, updateCb);
  44586. this._runCallbacksIfReady();
  44587. };
  44588. /**
  44589. * Get the number of pending requests
  44590. * @deprecated pending requests are now tracked with zones
  44591. */
  44592. Testability.prototype.getPendingRequestCount = function () { return this._pendingCount; };
  44593. /**
  44594. * Find providers by name
  44595. * @param using The root element to search from
  44596. * @param provider The name of binding variable
  44597. * @param exactMatch Whether using exactMatch
  44598. */
  44599. Testability.prototype.findProviders = function (using, provider, exactMatch) {
  44600. // TODO(juliemr): implement.
  44601. return [];
  44602. };
  44603. Testability = __decorate([
  44604. Injectable(),
  44605. __metadata("design:paramtypes", [NgZone])
  44606. ], Testability);
  44607. return Testability;
  44608. }());
  44609. /**
  44610. * A global registry of {@link Testability} instances for specific elements.
  44611. * @publicApi
  44612. */
  44613. var TestabilityRegistry = /** @class */ (function () {
  44614. function TestabilityRegistry() {
  44615. /** @internal */
  44616. this._applications = new Map();
  44617. _testabilityGetter.addToWindow(this);
  44618. }
  44619. /**
  44620. * Registers an application with a testability hook so that it can be tracked
  44621. * @param token token of application, root element
  44622. * @param testability Testability hook
  44623. */
  44624. TestabilityRegistry.prototype.registerApplication = function (token, testability) {
  44625. this._applications.set(token, testability);
  44626. };
  44627. /**
  44628. * Unregisters an application.
  44629. * @param token token of application, root element
  44630. */
  44631. TestabilityRegistry.prototype.unregisterApplication = function (token) { this._applications.delete(token); };
  44632. /**
  44633. * Unregisters all applications
  44634. */
  44635. TestabilityRegistry.prototype.unregisterAllApplications = function () { this._applications.clear(); };
  44636. /**
  44637. * Get a testability hook associated with the application
  44638. * @param elem root element
  44639. */
  44640. TestabilityRegistry.prototype.getTestability = function (elem) { return this._applications.get(elem) || null; };
  44641. /**
  44642. * Get all registered testabilities
  44643. */
  44644. TestabilityRegistry.prototype.getAllTestabilities = function () { return Array.from(this._applications.values()); };
  44645. /**
  44646. * Get all registered applications(root elements)
  44647. */
  44648. TestabilityRegistry.prototype.getAllRootElements = function () { return Array.from(this._applications.keys()); };
  44649. /**
  44650. * Find testability of a node in the Tree
  44651. * @param elem node
  44652. * @param findInAncestors whether finding testability in ancestors if testability was not found in
  44653. * current node
  44654. */
  44655. TestabilityRegistry.prototype.findTestabilityInTree = function (elem, findInAncestors) {
  44656. if (findInAncestors === void 0) { findInAncestors = true; }
  44657. return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors);
  44658. };
  44659. TestabilityRegistry = __decorate([
  44660. Injectable(),
  44661. __metadata("design:paramtypes", [])
  44662. ], TestabilityRegistry);
  44663. return TestabilityRegistry;
  44664. }());
  44665. var _NoopGetTestability = /** @class */ (function () {
  44666. function _NoopGetTestability() {
  44667. }
  44668. _NoopGetTestability.prototype.addToWindow = function (registry) { };
  44669. _NoopGetTestability.prototype.findTestabilityInTree = function (registry, elem, findInAncestors) {
  44670. return null;
  44671. };
  44672. return _NoopGetTestability;
  44673. }());
  44674. var _testabilityGetter = new _NoopGetTestability();
  44675. /**
  44676. * @license
  44677. * Copyright Google Inc. All Rights Reserved.
  44678. *
  44679. * Use of this source code is governed by an MIT-style license that can be
  44680. * found in the LICENSE file at https://angular.io/license
  44681. */
  44682. var _platform;
  44683. var compileNgModuleFactory = compileNgModuleFactory__PRE_R3__;
  44684. function compileNgModuleFactory__PRE_R3__(injector, options, moduleType) {
  44685. var compilerFactory = injector.get(CompilerFactory);
  44686. var compiler = compilerFactory.createCompiler([options]);
  44687. return compiler.compileModuleAsync(moduleType);
  44688. }
  44689. var isBoundToModule = isBoundToModule__PRE_R3__;
  44690. function isBoundToModule__PRE_R3__(cf) {
  44691. return cf instanceof ComponentFactoryBoundToModule;
  44692. }
  44693. var ALLOW_MULTIPLE_PLATFORMS = new InjectionToken('AllowMultipleToken');
  44694. /**
  44695. * Creates a platform.
  44696. * Platforms have to be eagerly created via this function.
  44697. *
  44698. * @publicApi
  44699. */
  44700. function createPlatform(injector) {
  44701. if (_platform && !_platform.destroyed &&
  44702. !_platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
  44703. throw new Error('There can be only one platform. Destroy the previous one to create a new one.');
  44704. }
  44705. _platform = injector.get(PlatformRef);
  44706. var inits = injector.get(PLATFORM_INITIALIZER, null);
  44707. if (inits)
  44708. inits.forEach(function (init) { return init(); });
  44709. return _platform;
  44710. }
  44711. /**
  44712. * Creates a factory for a platform
  44713. *
  44714. * @publicApi
  44715. */
  44716. function createPlatformFactory(parentPlatformFactory, name, providers) {
  44717. if (providers === void 0) { providers = []; }
  44718. var desc = "Platform: " + name;
  44719. var marker = new InjectionToken(desc);
  44720. return function (extraProviders) {
  44721. if (extraProviders === void 0) { extraProviders = []; }
  44722. var platform = getPlatform();
  44723. if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
  44724. if (parentPlatformFactory) {
  44725. parentPlatformFactory(providers.concat(extraProviders).concat({ provide: marker, useValue: true }));
  44726. }
  44727. else {
  44728. var injectedProviders = providers.concat(extraProviders).concat({ provide: marker, useValue: true });
  44729. createPlatform(Injector.create({ providers: injectedProviders, name: desc }));
  44730. }
  44731. }
  44732. return assertPlatform(marker);
  44733. };
  44734. }
  44735. /**
  44736. * Checks that there currently is a platform which contains the given token as a provider.
  44737. *
  44738. * @publicApi
  44739. */
  44740. function assertPlatform(requiredToken) {
  44741. var platform = getPlatform();
  44742. if (!platform) {
  44743. throw new Error('No platform exists!');
  44744. }
  44745. if (!platform.injector.get(requiredToken, null)) {
  44746. throw new Error('A platform with a different configuration has been created. Please destroy it first.');
  44747. }
  44748. return platform;
  44749. }
  44750. /**
  44751. * Returns the current platform.
  44752. *
  44753. * @publicApi
  44754. */
  44755. function getPlatform() {
  44756. return _platform && !_platform.destroyed ? _platform : null;
  44757. }
  44758. /**
  44759. * The Angular platform is the entry point for Angular on a web page. Each page
  44760. * has exactly one platform, and services (such as reflection) which are common
  44761. * to every Angular application running on the page are bound in its scope.
  44762. *
  44763. * A page's platform is initialized implicitly when a platform is created via a platform factory
  44764. * (e.g. {@link platformBrowser}), or explicitly by calling the {@link createPlatform} function.
  44765. *
  44766. * @publicApi
  44767. */
  44768. var PlatformRef = /** @class */ (function () {
  44769. /** @internal */
  44770. function PlatformRef(_injector) {
  44771. this._injector = _injector;
  44772. this._modules = [];
  44773. this._destroyListeners = [];
  44774. this._destroyed = false;
  44775. }
  44776. /**
  44777. * Creates an instance of an `@NgModule` for the given platform
  44778. * for offline compilation.
  44779. *
  44780. * @usageNotes
  44781. * ### Simple Example
  44782. *
  44783. * ```typescript
  44784. * my_module.ts:
  44785. *
  44786. * @NgModule({
  44787. * imports: [BrowserModule]
  44788. * })
  44789. * class MyModule {}
  44790. *
  44791. * main.ts:
  44792. * import {MyModuleNgFactory} from './my_module.ngfactory';
  44793. * import {platformBrowser} from '@angular/platform-browser';
  44794. *
  44795. * let moduleRef = platformBrowser().bootstrapModuleFactory(MyModuleNgFactory);
  44796. * ```
  44797. */
  44798. PlatformRef.prototype.bootstrapModuleFactory = function (moduleFactory, options) {
  44799. var _this = this;
  44800. // Note: We need to create the NgZone _before_ we instantiate the module,
  44801. // as instantiating the module creates some providers eagerly.
  44802. // So we create a mini parent injector that just contains the new NgZone and
  44803. // pass that as parent to the NgModuleFactory.
  44804. var ngZoneOption = options ? options.ngZone : undefined;
  44805. var ngZone = getNgZone(ngZoneOption);
  44806. var providers = [{ provide: NgZone, useValue: ngZone }];
  44807. // Attention: Don't use ApplicationRef.run here,
  44808. // as we want to be sure that all possible constructor calls are inside `ngZone.run`!
  44809. return ngZone.run(function () {
  44810. var ngZoneInjector = Injector.create({ providers: providers, parent: _this.injector, name: moduleFactory.moduleType.name });
  44811. var moduleRef = moduleFactory.create(ngZoneInjector);
  44812. var exceptionHandler = moduleRef.injector.get(ErrorHandler, null);
  44813. if (!exceptionHandler) {
  44814. throw new Error('No ErrorHandler. Is platform module (BrowserModule) included?');
  44815. }
  44816. // If the `LOCALE_ID` provider is defined at bootstrap we set the value for runtime i18n (ivy)
  44817. var localeId = moduleRef.injector.get(LOCALE_ID$1, DEFAULT_LOCALE_ID);
  44818. setLocaleId(localeId);
  44819. moduleRef.onDestroy(function () { return remove(_this._modules, moduleRef); });
  44820. ngZone.runOutsideAngular(function () { return ngZone.onError.subscribe({ next: function (error) { exceptionHandler.handleError(error); } }); });
  44821. return _callAndReportToErrorHandler(exceptionHandler, ngZone, function () {
  44822. var initStatus = moduleRef.injector.get(ApplicationInitStatus);
  44823. initStatus.runInitializers();
  44824. return initStatus.donePromise.then(function () {
  44825. _this._moduleDoBootstrap(moduleRef);
  44826. return moduleRef;
  44827. });
  44828. });
  44829. });
  44830. };
  44831. /**
  44832. * Creates an instance of an `@NgModule` for a given platform using the given runtime compiler.
  44833. *
  44834. * @usageNotes
  44835. * ### Simple Example
  44836. *
  44837. * ```typescript
  44838. * @NgModule({
  44839. * imports: [BrowserModule]
  44840. * })
  44841. * class MyModule {}
  44842. *
  44843. * let moduleRef = platformBrowser().bootstrapModule(MyModule);
  44844. * ```
  44845. *
  44846. */
  44847. PlatformRef.prototype.bootstrapModule = function (moduleType, compilerOptions) {
  44848. var _this = this;
  44849. if (compilerOptions === void 0) { compilerOptions = []; }
  44850. var options = optionsReducer({}, compilerOptions);
  44851. return compileNgModuleFactory(this.injector, options, moduleType)
  44852. .then(function (moduleFactory) { return _this.bootstrapModuleFactory(moduleFactory, options); });
  44853. };
  44854. PlatformRef.prototype._moduleDoBootstrap = function (moduleRef) {
  44855. var appRef = moduleRef.injector.get(ApplicationRef);
  44856. if (moduleRef._bootstrapComponents.length > 0) {
  44857. moduleRef._bootstrapComponents.forEach(function (f) { return appRef.bootstrap(f); });
  44858. }
  44859. else if (moduleRef.instance.ngDoBootstrap) {
  44860. moduleRef.instance.ngDoBootstrap(appRef);
  44861. }
  44862. else {
  44863. throw new Error("The module " + stringify$1(moduleRef.instance.constructor) + " was bootstrapped, but it does not declare \"@NgModule.bootstrap\" components nor a \"ngDoBootstrap\" method. " +
  44864. "Please define one of these.");
  44865. }
  44866. this._modules.push(moduleRef);
  44867. };
  44868. /**
  44869. * Register a listener to be called when the platform is disposed.
  44870. */
  44871. PlatformRef.prototype.onDestroy = function (callback) { this._destroyListeners.push(callback); };
  44872. Object.defineProperty(PlatformRef.prototype, "injector", {
  44873. /**
  44874. * Retrieve the platform {@link Injector}, which is the parent injector for
  44875. * every Angular application on the page and provides singleton providers.
  44876. */
  44877. get: function () { return this._injector; },
  44878. enumerable: true,
  44879. configurable: true
  44880. });
  44881. /**
  44882. * Destroy the Angular platform and all Angular applications on the page.
  44883. */
  44884. PlatformRef.prototype.destroy = function () {
  44885. if (this._destroyed) {
  44886. throw new Error('The platform has already been destroyed!');
  44887. }
  44888. this._modules.slice().forEach(function (module) { return module.destroy(); });
  44889. this._destroyListeners.forEach(function (listener) { return listener(); });
  44890. this._destroyed = true;
  44891. };
  44892. Object.defineProperty(PlatformRef.prototype, "destroyed", {
  44893. get: function () { return this._destroyed; },
  44894. enumerable: true,
  44895. configurable: true
  44896. });
  44897. PlatformRef = __decorate([
  44898. Injectable(),
  44899. __metadata("design:paramtypes", [Injector])
  44900. ], PlatformRef);
  44901. return PlatformRef;
  44902. }());
  44903. function getNgZone(ngZoneOption) {
  44904. var ngZone;
  44905. if (ngZoneOption === 'noop') {
  44906. ngZone = new NoopNgZone();
  44907. }
  44908. else {
  44909. ngZone = (ngZoneOption === 'zone.js' ? undefined : ngZoneOption) ||
  44910. new NgZone({ enableLongStackTrace: isDevMode() });
  44911. }
  44912. return ngZone;
  44913. }
  44914. function _callAndReportToErrorHandler(errorHandler, ngZone, callback) {
  44915. try {
  44916. var result = callback();
  44917. if (isPromise$1(result)) {
  44918. return result.catch(function (e) {
  44919. ngZone.runOutsideAngular(function () { return errorHandler.handleError(e); });
  44920. // rethrow as the exception handler might not do it
  44921. throw e;
  44922. });
  44923. }
  44924. return result;
  44925. }
  44926. catch (e) {
  44927. ngZone.runOutsideAngular(function () { return errorHandler.handleError(e); });
  44928. // rethrow as the exception handler might not do it
  44929. throw e;
  44930. }
  44931. }
  44932. function optionsReducer(dst, objs) {
  44933. if (Array.isArray(objs)) {
  44934. dst = objs.reduce(optionsReducer, dst);
  44935. }
  44936. else {
  44937. dst = __assign({}, dst, objs);
  44938. }
  44939. return dst;
  44940. }
  44941. /**
  44942. * A reference to an Angular application running on a page.
  44943. *
  44944. * @usageNotes
  44945. *
  44946. * {@a is-stable-examples}
  44947. * ### isStable examples and caveats
  44948. *
  44949. * Note two important points about `isStable`, demonstrated in the examples below:
  44950. * - the application will never be stable if you start any kind
  44951. * of recurrent asynchronous task when the application starts
  44952. * (for example for a polling process, started with a `setInterval`, a `setTimeout`
  44953. * or using RxJS operators like `interval`);
  44954. * - the `isStable` Observable runs outside of the Angular zone.
  44955. *
  44956. * Let's imagine that you start a recurrent task
  44957. * (here incrementing a counter, using RxJS `interval`),
  44958. * and at the same time subscribe to `isStable`.
  44959. *
  44960. * ```
  44961. * constructor(appRef: ApplicationRef) {
  44962. * appRef.isStable.pipe(
  44963. * filter(stable => stable)
  44964. * ).subscribe(() => console.log('App is stable now');
  44965. * interval(1000).subscribe(counter => console.log(counter));
  44966. * }
  44967. * ```
  44968. * In this example, `isStable` will never emit `true`,
  44969. * and the trace "App is stable now" will never get logged.
  44970. *
  44971. * If you want to execute something when the app is stable,
  44972. * you have to wait for the application to be stable
  44973. * before starting your polling process.
  44974. *
  44975. * ```
  44976. * constructor(appRef: ApplicationRef) {
  44977. * appRef.isStable.pipe(
  44978. * first(stable => stable),
  44979. * tap(stable => console.log('App is stable now')),
  44980. * switchMap(() => interval(1000))
  44981. * ).subscribe(counter => console.log(counter));
  44982. * }
  44983. * ```
  44984. * In this example, the trace "App is stable now" will be logged
  44985. * and then the counter starts incrementing every second.
  44986. *
  44987. * Note also that this Observable runs outside of the Angular zone,
  44988. * which means that the code in the subscription
  44989. * to this Observable will not trigger the change detection.
  44990. *
  44991. * Let's imagine that instead of logging the counter value,
  44992. * you update a field of your component
  44993. * and display it in its template.
  44994. *
  44995. * ```
  44996. * constructor(appRef: ApplicationRef) {
  44997. * appRef.isStable.pipe(
  44998. * first(stable => stable),
  44999. * switchMap(() => interval(1000))
  45000. * ).subscribe(counter => this.value = counter);
  45001. * }
  45002. * ```
  45003. * As the `isStable` Observable runs outside the zone,
  45004. * the `value` field will be updated properly,
  45005. * but the template will not be refreshed!
  45006. *
  45007. * You'll have to manually trigger the change detection to update the template.
  45008. *
  45009. * ```
  45010. * constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
  45011. * appRef.isStable.pipe(
  45012. * first(stable => stable),
  45013. * switchMap(() => interval(1000))
  45014. * ).subscribe(counter => {
  45015. * this.value = counter;
  45016. * cd.detectChanges();
  45017. * });
  45018. * }
  45019. * ```
  45020. *
  45021. * Or make the subscription callback run inside the zone.
  45022. *
  45023. * ```
  45024. * constructor(appRef: ApplicationRef, zone: NgZone) {
  45025. * appRef.isStable.pipe(
  45026. * first(stable => stable),
  45027. * switchMap(() => interval(1000))
  45028. * ).subscribe(counter => zone.run(() => this.value = counter));
  45029. * }
  45030. * ```
  45031. *
  45032. * @publicApi
  45033. */
  45034. var ApplicationRef = /** @class */ (function () {
  45035. /** @internal */
  45036. function ApplicationRef(_zone, _console, _injector, _exceptionHandler, _componentFactoryResolver, _initStatus) {
  45037. var _this = this;
  45038. this._zone = _zone;
  45039. this._console = _console;
  45040. this._injector = _injector;
  45041. this._exceptionHandler = _exceptionHandler;
  45042. this._componentFactoryResolver = _componentFactoryResolver;
  45043. this._initStatus = _initStatus;
  45044. this._bootstrapListeners = [];
  45045. this._views = [];
  45046. this._runningTick = false;
  45047. this._enforceNoNewChanges = false;
  45048. this._stable = true;
  45049. /**
  45050. * Get a list of component types registered to this application.
  45051. * This list is populated even before the component is created.
  45052. */
  45053. this.componentTypes = [];
  45054. /**
  45055. * Get a list of components registered to this application.
  45056. */
  45057. this.components = [];
  45058. this._enforceNoNewChanges = isDevMode();
  45059. this._zone.onMicrotaskEmpty.subscribe({ next: function () { _this._zone.run(function () { _this.tick(); }); } });
  45060. var isCurrentlyStable = new Observable(function (observer) {
  45061. _this._stable = _this._zone.isStable && !_this._zone.hasPendingMacrotasks &&
  45062. !_this._zone.hasPendingMicrotasks;
  45063. _this._zone.runOutsideAngular(function () {
  45064. observer.next(_this._stable);
  45065. observer.complete();
  45066. });
  45067. });
  45068. var isStable = new Observable(function (observer) {
  45069. // Create the subscription to onStable outside the Angular Zone so that
  45070. // the callback is run outside the Angular Zone.
  45071. var stableSub;
  45072. _this._zone.runOutsideAngular(function () {
  45073. stableSub = _this._zone.onStable.subscribe(function () {
  45074. NgZone.assertNotInAngularZone();
  45075. // Check whether there are no pending macro/micro tasks in the next tick
  45076. // to allow for NgZone to update the state.
  45077. scheduleMicroTask(function () {
  45078. if (!_this._stable && !_this._zone.hasPendingMacrotasks &&
  45079. !_this._zone.hasPendingMicrotasks) {
  45080. _this._stable = true;
  45081. observer.next(true);
  45082. }
  45083. });
  45084. });
  45085. });
  45086. var unstableSub = _this._zone.onUnstable.subscribe(function () {
  45087. NgZone.assertInAngularZone();
  45088. if (_this._stable) {
  45089. _this._stable = false;
  45090. _this._zone.runOutsideAngular(function () { observer.next(false); });
  45091. }
  45092. });
  45093. return function () {
  45094. stableSub.unsubscribe();
  45095. unstableSub.unsubscribe();
  45096. };
  45097. });
  45098. this.isStable =
  45099. merge$1(isCurrentlyStable, isStable.pipe(share()));
  45100. }
  45101. ApplicationRef_1 = ApplicationRef;
  45102. /**
  45103. * Bootstrap a new component at the root level of the application.
  45104. *
  45105. * @usageNotes
  45106. * ### Bootstrap process
  45107. *
  45108. * When bootstrapping a new root component into an application, Angular mounts the
  45109. * specified application component onto DOM elements identified by the componentType's
  45110. * selector and kicks off automatic change detection to finish initializing the component.
  45111. *
  45112. * Optionally, a component can be mounted onto a DOM element that does not match the
  45113. * componentType's selector.
  45114. *
  45115. * ### Example
  45116. * {@example core/ts/platform/platform.ts region='longform'}
  45117. */
  45118. ApplicationRef.prototype.bootstrap = function (componentOrFactory, rootSelectorOrNode) {
  45119. var _this = this;
  45120. if (!this._initStatus.done) {
  45121. throw new Error('Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.');
  45122. }
  45123. var componentFactory;
  45124. if (componentOrFactory instanceof ComponentFactory) {
  45125. componentFactory = componentOrFactory;
  45126. }
  45127. else {
  45128. componentFactory =
  45129. this._componentFactoryResolver.resolveComponentFactory(componentOrFactory);
  45130. }
  45131. this.componentTypes.push(componentFactory.componentType);
  45132. // Create a factory associated with the current module if it's not bound to some other
  45133. var ngModule = isBoundToModule(componentFactory) ? null : this._injector.get(NgModuleRef);
  45134. var selectorOrNode = rootSelectorOrNode || componentFactory.selector;
  45135. var compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
  45136. compRef.onDestroy(function () { _this._unloadComponent(compRef); });
  45137. var testability = compRef.injector.get(Testability, null);
  45138. if (testability) {
  45139. compRef.injector.get(TestabilityRegistry)
  45140. .registerApplication(compRef.location.nativeElement, testability);
  45141. }
  45142. this._loadComponent(compRef);
  45143. if (isDevMode()) {
  45144. this._console.log("Angular is running in the development mode. Call enableProdMode() to enable the production mode.");
  45145. }
  45146. return compRef;
  45147. };
  45148. /**
  45149. * Invoke this method to explicitly process change detection and its side-effects.
  45150. *
  45151. * In development mode, `tick()` also performs a second change detection cycle to ensure that no
  45152. * further changes are detected. If additional changes are picked up during this second cycle,
  45153. * bindings in the app have side-effects that cannot be resolved in a single change detection
  45154. * pass.
  45155. * In this case, Angular throws an error, since an Angular application can only have one change
  45156. * detection pass during which all change detection must complete.
  45157. */
  45158. ApplicationRef.prototype.tick = function () {
  45159. var _this = this;
  45160. var e_1, _a, e_2, _b;
  45161. if (this._runningTick) {
  45162. throw new Error('ApplicationRef.tick is called recursively');
  45163. }
  45164. var scope = ApplicationRef_1._tickScope();
  45165. try {
  45166. this._runningTick = true;
  45167. try {
  45168. for (var _c = __values(this._views), _d = _c.next(); !_d.done; _d = _c.next()) {
  45169. var view = _d.value;
  45170. view.detectChanges();
  45171. }
  45172. }
  45173. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  45174. finally {
  45175. try {
  45176. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  45177. }
  45178. finally { if (e_1) throw e_1.error; }
  45179. }
  45180. if (this._enforceNoNewChanges) {
  45181. try {
  45182. for (var _e = __values(this._views), _f = _e.next(); !_f.done; _f = _e.next()) {
  45183. var view = _f.value;
  45184. view.checkNoChanges();
  45185. }
  45186. }
  45187. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  45188. finally {
  45189. try {
  45190. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  45191. }
  45192. finally { if (e_2) throw e_2.error; }
  45193. }
  45194. }
  45195. }
  45196. catch (e) {
  45197. // Attention: Don't rethrow as it could cancel subscriptions to Observables!
  45198. this._zone.runOutsideAngular(function () { return _this._exceptionHandler.handleError(e); });
  45199. }
  45200. finally {
  45201. this._runningTick = false;
  45202. wtfLeave(scope);
  45203. }
  45204. };
  45205. /**
  45206. * Attaches a view so that it will be dirty checked.
  45207. * The view will be automatically detached when it is destroyed.
  45208. * This will throw if the view is already attached to a ViewContainer.
  45209. */
  45210. ApplicationRef.prototype.attachView = function (viewRef) {
  45211. var view = viewRef;
  45212. this._views.push(view);
  45213. view.attachToAppRef(this);
  45214. };
  45215. /**
  45216. * Detaches a view from dirty checking again.
  45217. */
  45218. ApplicationRef.prototype.detachView = function (viewRef) {
  45219. var view = viewRef;
  45220. remove(this._views, view);
  45221. view.detachFromAppRef();
  45222. };
  45223. ApplicationRef.prototype._loadComponent = function (componentRef) {
  45224. this.attachView(componentRef.hostView);
  45225. this.tick();
  45226. this.components.push(componentRef);
  45227. // Get the listeners lazily to prevent DI cycles.
  45228. var listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
  45229. listeners.forEach(function (listener) { return listener(componentRef); });
  45230. };
  45231. ApplicationRef.prototype._unloadComponent = function (componentRef) {
  45232. this.detachView(componentRef.hostView);
  45233. remove(this.components, componentRef);
  45234. };
  45235. /** @internal */
  45236. ApplicationRef.prototype.ngOnDestroy = function () {
  45237. // TODO(alxhub): Dispose of the NgZone.
  45238. this._views.slice().forEach(function (view) { return view.destroy(); });
  45239. };
  45240. Object.defineProperty(ApplicationRef.prototype, "viewCount", {
  45241. /**
  45242. * Returns the number of attached views.
  45243. */
  45244. get: function () { return this._views.length; },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. var ApplicationRef_1;
  45249. /** @internal */
  45250. ApplicationRef._tickScope = wtfCreateScope('ApplicationRef#tick()');
  45251. ApplicationRef = ApplicationRef_1 = __decorate([
  45252. Injectable(),
  45253. __metadata("design:paramtypes", [NgZone, Console, Injector,
  45254. ErrorHandler,
  45255. ComponentFactoryResolver,
  45256. ApplicationInitStatus])
  45257. ], ApplicationRef);
  45258. return ApplicationRef;
  45259. }());
  45260. function remove(list, el) {
  45261. var index = list.indexOf(el);
  45262. if (index > -1) {
  45263. list.splice(index, 1);
  45264. }
  45265. }
  45266. /**
  45267. * @license
  45268. * Copyright Google Inc. All Rights Reserved.
  45269. *
  45270. * Use of this source code is governed by an MIT-style license that can be
  45271. * found in the LICENSE file at https://angular.io/license
  45272. */
  45273. /**
  45274. * @license
  45275. * Copyright Google Inc. All Rights Reserved.
  45276. *
  45277. * Use of this source code is governed by an MIT-style license that can be
  45278. * found in the LICENSE file at https://angular.io/license
  45279. */
  45280. /**
  45281. * @license
  45282. * Copyright Google Inc. All Rights Reserved.
  45283. *
  45284. * Use of this source code is governed by an MIT-style license that can be
  45285. * found in the LICENSE file at https://angular.io/license
  45286. */
  45287. /**
  45288. * @license
  45289. * Copyright Google Inc. All Rights Reserved.
  45290. *
  45291. * Use of this source code is governed by an MIT-style license that can be
  45292. * found in the LICENSE file at https://angular.io/license
  45293. */
  45294. var SWITCH_IVY_ENABLED__PRE_R3__ = false;
  45295. var ivyEnabled = SWITCH_IVY_ENABLED__PRE_R3__;
  45296. /**
  45297. * @license
  45298. * Copyright Google Inc. All Rights Reserved.
  45299. *
  45300. * Use of this source code is governed by an MIT-style license that can be
  45301. * found in the LICENSE file at https://angular.io/license
  45302. */
  45303. var _SEPARATOR = '#';
  45304. var FACTORY_CLASS_SUFFIX = 'NgFactory';
  45305. /**
  45306. * Configuration for SystemJsNgModuleLoader.
  45307. * token.
  45308. *
  45309. * @publicApi
  45310. * @deprecated the `string` form of `loadChildren` is deprecated, and `SystemJsNgModuleLoaderConfig`
  45311. * is part of its implementation. See `LoadChildren` for more details.
  45312. */
  45313. var SystemJsNgModuleLoaderConfig = /** @class */ (function () {
  45314. function SystemJsNgModuleLoaderConfig() {
  45315. }
  45316. return SystemJsNgModuleLoaderConfig;
  45317. }());
  45318. var DEFAULT_CONFIG = {
  45319. factoryPathPrefix: '',
  45320. factoryPathSuffix: '.ngfactory',
  45321. };
  45322. /**
  45323. * NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory
  45324. * @publicApi
  45325. * @deprecated the `string` form of `loadChildren` is deprecated, and `SystemJsNgModuleLoader` is
  45326. * part of its implementation. See `LoadChildren` for more details.
  45327. */
  45328. var SystemJsNgModuleLoader = /** @class */ (function () {
  45329. function SystemJsNgModuleLoader(_compiler, config) {
  45330. this._compiler = _compiler;
  45331. this._config = config || DEFAULT_CONFIG;
  45332. }
  45333. SystemJsNgModuleLoader.prototype.load = function (path) {
  45334. var legacyOfflineMode = !ivyEnabled && this._compiler instanceof Compiler;
  45335. return legacyOfflineMode ? this.loadFactory(path) : this.loadAndCompile(path);
  45336. };
  45337. SystemJsNgModuleLoader.prototype.loadAndCompile = function (path) {
  45338. var _this = this;
  45339. var _a = __read(path.split(_SEPARATOR), 2), module = _a[0], exportName = _a[1];
  45340. if (exportName === undefined) {
  45341. exportName = 'default';
  45342. }
  45343. return System.import(module)
  45344. .then(function (module) { return module[exportName]; })
  45345. .then(function (type) { return checkNotEmpty(type, module, exportName); })
  45346. .then(function (type) { return _this._compiler.compileModuleAsync(type); });
  45347. };
  45348. SystemJsNgModuleLoader.prototype.loadFactory = function (path) {
  45349. var _a = __read(path.split(_SEPARATOR), 2), module = _a[0], exportName = _a[1];
  45350. var factoryClassSuffix = FACTORY_CLASS_SUFFIX;
  45351. if (exportName === undefined) {
  45352. exportName = 'default';
  45353. factoryClassSuffix = '';
  45354. }
  45355. return System.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)
  45356. .then(function (module) { return module[exportName + factoryClassSuffix]; })
  45357. .then(function (factory) { return checkNotEmpty(factory, module, exportName); });
  45358. };
  45359. SystemJsNgModuleLoader = __decorate([
  45360. Injectable(),
  45361. __param(1, Optional()),
  45362. __metadata("design:paramtypes", [Compiler, SystemJsNgModuleLoaderConfig])
  45363. ], SystemJsNgModuleLoader);
  45364. return SystemJsNgModuleLoader;
  45365. }());
  45366. function checkNotEmpty(value, modulePath, exportName) {
  45367. if (!value) {
  45368. throw new Error("Cannot find '" + exportName + "' in '" + modulePath + "'");
  45369. }
  45370. return value;
  45371. }
  45372. /**
  45373. * @license
  45374. * Copyright Google Inc. All Rights Reserved.
  45375. *
  45376. * Use of this source code is governed by an MIT-style license that can be
  45377. * found in the LICENSE file at https://angular.io/license
  45378. */
  45379. /**
  45380. * Represents an Angular [view](guide/glossary#view),
  45381. * specifically the [host view](guide/glossary#view-tree) that is defined by a component.
  45382. * Also serves as the base class
  45383. * that adds destroy methods for [embedded views](guide/glossary#view-tree).
  45384. *
  45385. * @see `EmbeddedViewRef`
  45386. *
  45387. * @publicApi
  45388. */
  45389. var ViewRef$1 = /** @class */ (function (_super) {
  45390. __extends(ViewRef, _super);
  45391. function ViewRef() {
  45392. return _super !== null && _super.apply(this, arguments) || this;
  45393. }
  45394. return ViewRef;
  45395. }(ChangeDetectorRef));
  45396. /**
  45397. * Represents an Angular [view](guide/glossary#view) in a view container.
  45398. * An [embedded view](guide/glossary#view-tree) can be referenced from a component
  45399. * other than the hosting component whose template defines it, or it can be defined
  45400. * independently by a `TemplateRef`.
  45401. *
  45402. * Properties of elements in a view can change, but the structure (number and order) of elements in
  45403. * a view cannot. Change the structure of elements by inserting, moving, or
  45404. * removing nested views in a view container.
  45405. *
  45406. * @see `ViewContainerRef`
  45407. *
  45408. * @usageNotes
  45409. *
  45410. * The following template breaks down into two separate `TemplateRef` instances,
  45411. * an outer one and an inner one.
  45412. *
  45413. * ```
  45414. * Count: {{items.length}}
  45415. * <ul>
  45416. * <li *ngFor="let item of items">{{item}}</li>
  45417. * </ul>
  45418. * ```
  45419. *
  45420. * This is the outer `TemplateRef`:
  45421. *
  45422. * ```
  45423. * Count: {{items.length}}
  45424. * <ul>
  45425. * <ng-template ngFor let-item [ngForOf]="items"></ng-template>
  45426. * </ul>
  45427. * ```
  45428. *
  45429. * This is the inner `TemplateRef`:
  45430. *
  45431. * ```
  45432. * <li>{{item}}</li>
  45433. * ```
  45434. *
  45435. * The outer and inner `TemplateRef` instances are assembled into views as follows:
  45436. *
  45437. * ```
  45438. * <!-- ViewRef: outer-0 -->
  45439. * Count: 2
  45440. * <ul>
  45441. * <ng-template view-container-ref></ng-template>
  45442. * <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
  45443. * <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
  45444. * </ul>
  45445. * <!-- /ViewRef: outer-0 -->
  45446. * ```
  45447. * @publicApi
  45448. */
  45449. var EmbeddedViewRef = /** @class */ (function (_super) {
  45450. __extends(EmbeddedViewRef, _super);
  45451. function EmbeddedViewRef() {
  45452. return _super !== null && _super.apply(this, arguments) || this;
  45453. }
  45454. return EmbeddedViewRef;
  45455. }(ViewRef$1));
  45456. /**
  45457. * @license
  45458. * Copyright Google Inc. All Rights Reserved.
  45459. *
  45460. * Use of this source code is governed by an MIT-style license that can be
  45461. * found in the LICENSE file at https://angular.io/license
  45462. */
  45463. /**
  45464. * @license
  45465. * Copyright Google Inc. All Rights Reserved.
  45466. *
  45467. * Use of this source code is governed by an MIT-style license that can be
  45468. * found in the LICENSE file at https://angular.io/license
  45469. */
  45470. /**
  45471. * @publicApi
  45472. */
  45473. var DebugEventListener = /** @class */ (function () {
  45474. function DebugEventListener(name, callback) {
  45475. this.name = name;
  45476. this.callback = callback;
  45477. }
  45478. return DebugEventListener;
  45479. }());
  45480. var DebugNode__PRE_R3__ = /** @class */ (function () {
  45481. function DebugNode__PRE_R3__(nativeNode, parent, _debugContext) {
  45482. this.listeners = [];
  45483. this.parent = null;
  45484. this._debugContext = _debugContext;
  45485. this.nativeNode = nativeNode;
  45486. if (parent && parent instanceof DebugElement__PRE_R3__) {
  45487. parent.addChild(this);
  45488. }
  45489. }
  45490. Object.defineProperty(DebugNode__PRE_R3__.prototype, "injector", {
  45491. get: function () { return this._debugContext.injector; },
  45492. enumerable: true,
  45493. configurable: true
  45494. });
  45495. Object.defineProperty(DebugNode__PRE_R3__.prototype, "componentInstance", {
  45496. get: function () { return this._debugContext.component; },
  45497. enumerable: true,
  45498. configurable: true
  45499. });
  45500. Object.defineProperty(DebugNode__PRE_R3__.prototype, "context", {
  45501. get: function () { return this._debugContext.context; },
  45502. enumerable: true,
  45503. configurable: true
  45504. });
  45505. Object.defineProperty(DebugNode__PRE_R3__.prototype, "references", {
  45506. get: function () { return this._debugContext.references; },
  45507. enumerable: true,
  45508. configurable: true
  45509. });
  45510. Object.defineProperty(DebugNode__PRE_R3__.prototype, "providerTokens", {
  45511. get: function () { return this._debugContext.providerTokens; },
  45512. enumerable: true,
  45513. configurable: true
  45514. });
  45515. return DebugNode__PRE_R3__;
  45516. }());
  45517. var DebugElement__PRE_R3__ = /** @class */ (function (_super) {
  45518. __extends(DebugElement__PRE_R3__, _super);
  45519. function DebugElement__PRE_R3__(nativeNode, parent, _debugContext) {
  45520. var _this = _super.call(this, nativeNode, parent, _debugContext) || this;
  45521. _this.properties = {};
  45522. _this.attributes = {};
  45523. _this.classes = {};
  45524. _this.styles = {};
  45525. _this.childNodes = [];
  45526. _this.nativeElement = nativeNode;
  45527. return _this;
  45528. }
  45529. DebugElement__PRE_R3__.prototype.addChild = function (child) {
  45530. if (child) {
  45531. this.childNodes.push(child);
  45532. child.parent = this;
  45533. }
  45534. };
  45535. DebugElement__PRE_R3__.prototype.removeChild = function (child) {
  45536. var childIndex = this.childNodes.indexOf(child);
  45537. if (childIndex !== -1) {
  45538. child.parent = null;
  45539. this.childNodes.splice(childIndex, 1);
  45540. }
  45541. };
  45542. DebugElement__PRE_R3__.prototype.insertChildrenAfter = function (child, newChildren) {
  45543. var _this = this;
  45544. var _a;
  45545. var siblingIndex = this.childNodes.indexOf(child);
  45546. if (siblingIndex !== -1) {
  45547. (_a = this.childNodes).splice.apply(_a, __spread([siblingIndex + 1, 0], newChildren));
  45548. newChildren.forEach(function (c) {
  45549. if (c.parent) {
  45550. c.parent.removeChild(c);
  45551. }
  45552. child.parent = _this;
  45553. });
  45554. }
  45555. };
  45556. DebugElement__PRE_R3__.prototype.insertBefore = function (refChild, newChild) {
  45557. var refIndex = this.childNodes.indexOf(refChild);
  45558. if (refIndex === -1) {
  45559. this.addChild(newChild);
  45560. }
  45561. else {
  45562. if (newChild.parent) {
  45563. newChild.parent.removeChild(newChild);
  45564. }
  45565. newChild.parent = this;
  45566. this.childNodes.splice(refIndex, 0, newChild);
  45567. }
  45568. };
  45569. DebugElement__PRE_R3__.prototype.query = function (predicate) {
  45570. var results = this.queryAll(predicate);
  45571. return results[0] || null;
  45572. };
  45573. DebugElement__PRE_R3__.prototype.queryAll = function (predicate) {
  45574. var matches = [];
  45575. _queryElementChildren(this, predicate, matches);
  45576. return matches;
  45577. };
  45578. DebugElement__PRE_R3__.prototype.queryAllNodes = function (predicate) {
  45579. var matches = [];
  45580. _queryNodeChildren(this, predicate, matches);
  45581. return matches;
  45582. };
  45583. Object.defineProperty(DebugElement__PRE_R3__.prototype, "children", {
  45584. get: function () {
  45585. return this
  45586. .childNodes //
  45587. .filter(function (node) { return node instanceof DebugElement__PRE_R3__; });
  45588. },
  45589. enumerable: true,
  45590. configurable: true
  45591. });
  45592. DebugElement__PRE_R3__.prototype.triggerEventHandler = function (eventName, eventObj) {
  45593. this.listeners.forEach(function (listener) {
  45594. if (listener.name == eventName) {
  45595. listener.callback(eventObj);
  45596. }
  45597. });
  45598. };
  45599. return DebugElement__PRE_R3__;
  45600. }(DebugNode__PRE_R3__));
  45601. function _queryElementChildren(element, predicate, matches) {
  45602. element.childNodes.forEach(function (node) {
  45603. if (node instanceof DebugElement__PRE_R3__) {
  45604. if (predicate(node)) {
  45605. matches.push(node);
  45606. }
  45607. _queryElementChildren(node, predicate, matches);
  45608. }
  45609. });
  45610. }
  45611. function _queryNodeChildren(parentNode, predicate, matches) {
  45612. if (parentNode instanceof DebugElement__PRE_R3__) {
  45613. parentNode.childNodes.forEach(function (node) {
  45614. if (predicate(node)) {
  45615. matches.push(node);
  45616. }
  45617. if (node instanceof DebugElement__PRE_R3__) {
  45618. _queryNodeChildren(node, predicate, matches);
  45619. }
  45620. });
  45621. }
  45622. }
  45623. var DebugNode__POST_R3__ = /** @class */ (function () {
  45624. function DebugNode__POST_R3__(nativeNode) {
  45625. this.nativeNode = nativeNode;
  45626. }
  45627. Object.defineProperty(DebugNode__POST_R3__.prototype, "parent", {
  45628. get: function () {
  45629. var parent = this.nativeNode.parentNode;
  45630. return parent ? new DebugElement__POST_R3__(parent) : null;
  45631. },
  45632. enumerable: true,
  45633. configurable: true
  45634. });
  45635. Object.defineProperty(DebugNode__POST_R3__.prototype, "injector", {
  45636. get: function () { return getInjector(this.nativeNode); },
  45637. enumerable: true,
  45638. configurable: true
  45639. });
  45640. Object.defineProperty(DebugNode__POST_R3__.prototype, "componentInstance", {
  45641. get: function () {
  45642. var nativeElement = this.nativeNode;
  45643. return nativeElement &&
  45644. (getComponent(nativeElement) || getViewComponent(nativeElement));
  45645. },
  45646. enumerable: true,
  45647. configurable: true
  45648. });
  45649. Object.defineProperty(DebugNode__POST_R3__.prototype, "context", {
  45650. get: function () { return getContext(this.nativeNode); },
  45651. enumerable: true,
  45652. configurable: true
  45653. });
  45654. Object.defineProperty(DebugNode__POST_R3__.prototype, "listeners", {
  45655. get: function () {
  45656. return getListeners(this.nativeNode).filter(isBrowserEvents);
  45657. },
  45658. enumerable: true,
  45659. configurable: true
  45660. });
  45661. Object.defineProperty(DebugNode__POST_R3__.prototype, "references", {
  45662. get: function () { return getLocalRefs(this.nativeNode); },
  45663. enumerable: true,
  45664. configurable: true
  45665. });
  45666. Object.defineProperty(DebugNode__POST_R3__.prototype, "providerTokens", {
  45667. get: function () { return getInjectionTokens(this.nativeNode); },
  45668. enumerable: true,
  45669. configurable: true
  45670. });
  45671. return DebugNode__POST_R3__;
  45672. }());
  45673. var DebugElement__POST_R3__ = /** @class */ (function (_super) {
  45674. __extends(DebugElement__POST_R3__, _super);
  45675. function DebugElement__POST_R3__(nativeNode) {
  45676. var _this = this;
  45677. ngDevMode && assertDomNode(nativeNode);
  45678. _this = _super.call(this, nativeNode) || this;
  45679. return _this;
  45680. }
  45681. Object.defineProperty(DebugElement__POST_R3__.prototype, "nativeElement", {
  45682. get: function () {
  45683. return this.nativeNode.nodeType == Node.ELEMENT_NODE ? this.nativeNode : null;
  45684. },
  45685. enumerable: true,
  45686. configurable: true
  45687. });
  45688. Object.defineProperty(DebugElement__POST_R3__.prototype, "name", {
  45689. get: function () { return this.nativeElement.nodeName; },
  45690. enumerable: true,
  45691. configurable: true
  45692. });
  45693. Object.defineProperty(DebugElement__POST_R3__.prototype, "properties", {
  45694. /**
  45695. * Gets a map of property names to property values for an element.
  45696. *
  45697. * This map includes:
  45698. * - Regular property bindings (e.g. `[id]="id"`)
  45699. * - Host property bindings (e.g. `host: { '[id]': "id" }`)
  45700. * - Interpolated property bindings (e.g. `id="{{ value }}")
  45701. *
  45702. * It does not include:
  45703. * - input property bindings (e.g. `[myCustomInput]="value"`)
  45704. * - attribute bindings (e.g. `[attr.role]="menu"`)
  45705. */
  45706. get: function () {
  45707. var context = loadLContext(this.nativeNode);
  45708. var lView = context.lView;
  45709. var tData = lView[TVIEW].data;
  45710. var tNode = tData[context.nodeIndex];
  45711. var properties = collectPropertyBindings(tNode, lView, tData);
  45712. var hostProperties = collectHostPropertyBindings(tNode, lView, tData);
  45713. var className = collectClassNames(this);
  45714. var output = __assign({}, properties, hostProperties);
  45715. if (className) {
  45716. output['className'] = output['className'] ? output['className'] + (" " + className) : className;
  45717. }
  45718. return output;
  45719. },
  45720. enumerable: true,
  45721. configurable: true
  45722. });
  45723. Object.defineProperty(DebugElement__POST_R3__.prototype, "attributes", {
  45724. get: function () {
  45725. var attributes = {};
  45726. var element = this.nativeElement;
  45727. if (!element) {
  45728. return attributes;
  45729. }
  45730. var context = loadLContext(element);
  45731. var lView = context.lView;
  45732. var tNodeAttrs = lView[TVIEW].data[context.nodeIndex].attrs;
  45733. var lowercaseTNodeAttrs = [];
  45734. // For debug nodes we take the element's attribute directly from the DOM since it allows us
  45735. // to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
  45736. // that are set through `Renderer2`). The problem is that the browser will lowercase all names,
  45737. // however since we have the attributes already on the TNode, we can preserve the case by going
  45738. // through them once, adding them to the `attributes` map and putting their lower-cased name
  45739. // into an array. Afterwards when we're going through the native DOM attributes, we can check
  45740. // whether we haven't run into an attribute already through the TNode.
  45741. if (tNodeAttrs) {
  45742. var i = 0;
  45743. while (i < tNodeAttrs.length) {
  45744. var attrName = tNodeAttrs[i];
  45745. // Stop as soon as we hit a marker. We only care about the regular attributes. Everything
  45746. // else will be handled below when we read the final attributes off the DOM.
  45747. if (typeof attrName !== 'string')
  45748. break;
  45749. var attrValue = tNodeAttrs[i + 1];
  45750. attributes[attrName] = attrValue;
  45751. lowercaseTNodeAttrs.push(attrName.toLowerCase());
  45752. i += 2;
  45753. }
  45754. }
  45755. var eAttrs = element.attributes;
  45756. for (var i = 0; i < eAttrs.length; i++) {
  45757. var attr = eAttrs[i];
  45758. // Make sure that we don't assign the same attribute both in its
  45759. // case-sensitive form and the lower-cased one from the browser.
  45760. if (lowercaseTNodeAttrs.indexOf(attr.name) === -1) {
  45761. attributes[attr.name] = attr.value;
  45762. }
  45763. }
  45764. return attributes;
  45765. },
  45766. enumerable: true,
  45767. configurable: true
  45768. });
  45769. Object.defineProperty(DebugElement__POST_R3__.prototype, "classes", {
  45770. get: function () {
  45771. var classes = {};
  45772. var element = this.nativeElement;
  45773. if (element) {
  45774. var lContext = loadLContextFromNode(element);
  45775. var stylingContext = getStylingContextFromLView(lContext.nodeIndex, lContext.lView);
  45776. if (stylingContext) {
  45777. for (var i = 10 /* SingleStylesStartPosition */; i < stylingContext.length; i += 4 /* Size */) {
  45778. if (isClassBasedValue(stylingContext, i)) {
  45779. var className = getProp(stylingContext, i);
  45780. var value = getValue(stylingContext, i);
  45781. if (typeof value == 'boolean') {
  45782. // we want to ignore `null` since those don't overwrite the values.
  45783. classes[className] = value;
  45784. }
  45785. }
  45786. }
  45787. }
  45788. else {
  45789. // Fallback, just read DOM.
  45790. var eClasses = element.classList;
  45791. for (var i = 0; i < eClasses.length; i++) {
  45792. classes[eClasses[i]] = true;
  45793. }
  45794. }
  45795. }
  45796. return classes;
  45797. },
  45798. enumerable: true,
  45799. configurable: true
  45800. });
  45801. Object.defineProperty(DebugElement__POST_R3__.prototype, "styles", {
  45802. get: function () {
  45803. var styles = {};
  45804. var element = this.nativeElement;
  45805. if (element) {
  45806. var lContext = loadLContextFromNode(element);
  45807. var stylingContext = getStylingContextFromLView(lContext.nodeIndex, lContext.lView);
  45808. if (stylingContext) {
  45809. for (var i = 10 /* SingleStylesStartPosition */; i < stylingContext.length; i += 4 /* Size */) {
  45810. if (!isClassBasedValue(stylingContext, i)) {
  45811. var styleName = getProp(stylingContext, i);
  45812. var value = getValue(stylingContext, i);
  45813. if (value !== null) {
  45814. // we want to ignore `null` since those don't overwrite the values.
  45815. styles[styleName] = value;
  45816. }
  45817. }
  45818. }
  45819. }
  45820. else {
  45821. // Fallback, just read DOM.
  45822. var eStyles = element.style;
  45823. for (var i = 0; i < eStyles.length; i++) {
  45824. var name_1 = eStyles.item(i);
  45825. styles[name_1] = eStyles.getPropertyValue(name_1);
  45826. }
  45827. }
  45828. }
  45829. return styles;
  45830. },
  45831. enumerable: true,
  45832. configurable: true
  45833. });
  45834. Object.defineProperty(DebugElement__POST_R3__.prototype, "childNodes", {
  45835. get: function () {
  45836. var childNodes = this.nativeNode.childNodes;
  45837. var children = [];
  45838. for (var i = 0; i < childNodes.length; i++) {
  45839. var element = childNodes[i];
  45840. children.push(getDebugNode__POST_R3__(element));
  45841. }
  45842. return children;
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. Object.defineProperty(DebugElement__POST_R3__.prototype, "children", {
  45848. get: function () {
  45849. var nativeElement = this.nativeElement;
  45850. if (!nativeElement)
  45851. return [];
  45852. var childNodes = nativeElement.children;
  45853. var children = [];
  45854. for (var i = 0; i < childNodes.length; i++) {
  45855. var element = childNodes[i];
  45856. children.push(getDebugNode__POST_R3__(element));
  45857. }
  45858. return children;
  45859. },
  45860. enumerable: true,
  45861. configurable: true
  45862. });
  45863. DebugElement__POST_R3__.prototype.query = function (predicate) {
  45864. var results = this.queryAll(predicate);
  45865. return results[0] || null;
  45866. };
  45867. DebugElement__POST_R3__.prototype.queryAll = function (predicate) {
  45868. var matches = [];
  45869. _queryAllR3(this, predicate, matches, true);
  45870. return matches;
  45871. };
  45872. DebugElement__POST_R3__.prototype.queryAllNodes = function (predicate) {
  45873. var matches = [];
  45874. _queryAllR3(this, predicate, matches, false);
  45875. return matches;
  45876. };
  45877. DebugElement__POST_R3__.prototype.triggerEventHandler = function (eventName, eventObj) {
  45878. this.listeners.forEach(function (listener) {
  45879. if (listener.name === eventName) {
  45880. listener.callback(eventObj);
  45881. }
  45882. });
  45883. };
  45884. return DebugElement__POST_R3__;
  45885. }(DebugNode__POST_R3__));
  45886. /**
  45887. * Walk the TNode tree to find matches for the predicate.
  45888. *
  45889. * @param parentElement the element from which the walk is started
  45890. * @param predicate the predicate to match
  45891. * @param matches the list of positive matches
  45892. * @param elementsOnly whether only elements should be searched
  45893. */
  45894. function _queryAllR3(parentElement, predicate, matches, elementsOnly) {
  45895. var context = loadLContext(parentElement.nativeNode);
  45896. var parentTNode = context.lView[TVIEW].data[context.nodeIndex];
  45897. _queryNodeChildrenR3(parentTNode, context.lView, predicate, matches, elementsOnly, parentElement.nativeNode);
  45898. }
  45899. /**
  45900. * Recursively match the current TNode against the predicate, and goes on with the next ones.
  45901. *
  45902. * @param tNode the current TNode
  45903. * @param lView the LView of this TNode
  45904. * @param predicate the predicate to match
  45905. * @param matches the list of positive matches
  45906. * @param elementsOnly whether only elements should be searched
  45907. * @param rootNativeNode the root native node on which prediccate shouold not be matched
  45908. */
  45909. function _queryNodeChildrenR3(tNode, lView, predicate, matches, elementsOnly, rootNativeNode) {
  45910. var e_1, _a;
  45911. var nativeNode = getNativeByTNode(tNode, lView);
  45912. // For each type of TNode, specific logic is executed.
  45913. if (tNode.type === 3 /* Element */ || tNode.type === 4 /* ElementContainer */) {
  45914. // Case 1: the TNode is an element
  45915. // The native node has to be checked.
  45916. _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
  45917. if (isComponent(tNode)) {
  45918. // If the element is the host of a component, then all nodes in its view have to be processed.
  45919. // Note: the component's content (tNode.child) will be processed from the insertion points.
  45920. var componentView = getComponentViewByIndex(tNode.index, lView);
  45921. if (componentView && componentView[TVIEW].firstChild) {
  45922. _queryNodeChildrenR3(componentView[TVIEW].firstChild, componentView, predicate, matches, elementsOnly, rootNativeNode);
  45923. }
  45924. }
  45925. else if (tNode.child) {
  45926. // Otherwise, its children have to be processed.
  45927. _queryNodeChildrenR3(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  45928. }
  45929. // In all cases, if a dynamic container exists for this node, each view inside it has to be
  45930. // processed.
  45931. var nodeOrContainer = lView[tNode.index];
  45932. if (isLContainer(nodeOrContainer)) {
  45933. _queryNodeChildrenInContainerR3(nodeOrContainer, predicate, matches, elementsOnly, rootNativeNode);
  45934. }
  45935. }
  45936. else if (tNode.type === 0 /* Container */) {
  45937. // Case 2: the TNode is a container
  45938. // The native node has to be checked.
  45939. var lContainer = lView[tNode.index];
  45940. _addQueryMatchR3(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
  45941. // Each view inside the container has to be processed.
  45942. _queryNodeChildrenInContainerR3(lContainer, predicate, matches, elementsOnly, rootNativeNode);
  45943. }
  45944. else if (tNode.type === 1 /* Projection */) {
  45945. // Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
  45946. // The nodes projected at this location all need to be processed.
  45947. var componentView = findComponentView(lView);
  45948. var componentHost = componentView[T_HOST];
  45949. var head = componentHost.projection[tNode.projection];
  45950. if (Array.isArray(head)) {
  45951. try {
  45952. for (var head_1 = __values(head), head_1_1 = head_1.next(); !head_1_1.done; head_1_1 = head_1.next()) {
  45953. var nativeNode_1 = head_1_1.value;
  45954. _addQueryMatchR3(nativeNode_1, predicate, matches, elementsOnly, rootNativeNode);
  45955. }
  45956. }
  45957. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  45958. finally {
  45959. try {
  45960. if (head_1_1 && !head_1_1.done && (_a = head_1.return)) _a.call(head_1);
  45961. }
  45962. finally { if (e_1) throw e_1.error; }
  45963. }
  45964. }
  45965. else if (head) {
  45966. var nextLView = componentView[PARENT];
  45967. var nextTNode = nextLView[TVIEW].data[head.index];
  45968. _queryNodeChildrenR3(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
  45969. }
  45970. }
  45971. else if (tNode.child) {
  45972. // Case 4: the TNode is a view.
  45973. _queryNodeChildrenR3(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  45974. }
  45975. // We don't want to go to the next sibling of the root node.
  45976. if (rootNativeNode !== nativeNode) {
  45977. // To determine the next node to be processed, we need to use the next or the projectionNext
  45978. // link, depending on whether the current node has been projected.
  45979. var nextTNode = (tNode.flags & 2 /* isProjected */) ? tNode.projectionNext : tNode.next;
  45980. if (nextTNode) {
  45981. _queryNodeChildrenR3(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
  45982. }
  45983. }
  45984. }
  45985. /**
  45986. * Process all TNodes in a given container.
  45987. *
  45988. * @param lContainer the container to be processed
  45989. * @param predicate the predicate to match
  45990. * @param matches the list of positive matches
  45991. * @param elementsOnly whether only elements should be searched
  45992. * @param rootNativeNode the root native node on which prediccate shouold not be matched
  45993. */
  45994. function _queryNodeChildrenInContainerR3(lContainer, predicate, matches, elementsOnly, rootNativeNode) {
  45995. for (var i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  45996. var childView = lContainer[i];
  45997. _queryNodeChildrenR3(childView[TVIEW].node, childView, predicate, matches, elementsOnly, rootNativeNode);
  45998. }
  45999. }
  46000. /**
  46001. * Match the current native node against the predicate.
  46002. *
  46003. * @param nativeNode the current native node
  46004. * @param predicate the predicate to match
  46005. * @param matches the list of positive matches
  46006. * @param elementsOnly whether only elements should be searched
  46007. * @param rootNativeNode the root native node on which prediccate shouold not be matched
  46008. */
  46009. function _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode) {
  46010. if (rootNativeNode !== nativeNode) {
  46011. var debugNode = getDebugNode(nativeNode);
  46012. if (debugNode && (elementsOnly ? debugNode instanceof DebugElement__POST_R3__ : true) &&
  46013. predicate(debugNode)) {
  46014. matches.push(debugNode);
  46015. }
  46016. }
  46017. }
  46018. /**
  46019. * Iterates through the property bindings for a given node and generates
  46020. * a map of property names to values. This map only contains property bindings
  46021. * defined in templates, not in host bindings.
  46022. */
  46023. function collectPropertyBindings(tNode, lView, tData) {
  46024. var properties = {};
  46025. var bindingIndex = getFirstBindingIndex(tNode.propertyMetadataStartIndex, tData);
  46026. while (bindingIndex < tNode.propertyMetadataEndIndex) {
  46027. var value = void 0;
  46028. var propMetadata = tData[bindingIndex];
  46029. while (!isPropMetadataString(propMetadata)) {
  46030. // This is the first value for an interpolation. We need to build up
  46031. // the full interpolation by combining runtime values in LView with
  46032. // the static interstitial values stored in TData.
  46033. value = (value || '') + renderStringify(lView[bindingIndex]) + tData[bindingIndex];
  46034. propMetadata = tData[++bindingIndex];
  46035. }
  46036. value = value === undefined ? lView[bindingIndex] : value += lView[bindingIndex];
  46037. // Property metadata string has 3 parts: property name, prefix, and suffix
  46038. var metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
  46039. var propertyName = metadataParts[0];
  46040. // Attr bindings don't have property names and should be skipped
  46041. if (propertyName) {
  46042. // Wrap value with prefix and suffix (will be '' for normal bindings), if they're defined.
  46043. // Avoid wrapping for normal bindings so that the value doesn't get cast to a string.
  46044. properties[propertyName] = (metadataParts[1] && metadataParts[2]) ?
  46045. metadataParts[1] + value + metadataParts[2] :
  46046. value;
  46047. }
  46048. bindingIndex++;
  46049. }
  46050. return properties;
  46051. }
  46052. /**
  46053. * Retrieves the first binding index that holds values for this property
  46054. * binding.
  46055. *
  46056. * For normal bindings (e.g. `[id]="id"`), the binding index is the
  46057. * same as the metadata index. For interpolations (e.g. `id="{{id}}-{{name}}"`),
  46058. * there can be multiple binding values, so we might have to loop backwards
  46059. * from the metadata index until we find the first one.
  46060. *
  46061. * @param metadataIndex The index of the first property metadata string for
  46062. * this node.
  46063. * @param tData The data array for the current TView
  46064. * @returns The first binding index for this binding
  46065. */
  46066. function getFirstBindingIndex(metadataIndex, tData) {
  46067. var currentBindingIndex = metadataIndex - 1;
  46068. // If the slot before the metadata holds a string, we know that this
  46069. // metadata applies to an interpolation with at least 2 bindings, and
  46070. // we need to search further to access the first binding value.
  46071. var currentValue = tData[currentBindingIndex];
  46072. // We need to iterate until we hit either a:
  46073. // - TNode (it is an element slot marking the end of `consts` section), OR a
  46074. // - metadata string (slot is attribute metadata or a previous node's property metadata)
  46075. while (typeof currentValue === 'string' && !isPropMetadataString(currentValue)) {
  46076. currentValue = tData[--currentBindingIndex];
  46077. }
  46078. return currentBindingIndex + 1;
  46079. }
  46080. function collectHostPropertyBindings(tNode, lView, tData) {
  46081. var properties = {};
  46082. // Host binding values for a node are stored after directives on that node
  46083. var hostPropIndex = tNode.directiveEnd;
  46084. var propMetadata = tData[hostPropIndex];
  46085. // When we reach a value in TView.data that is not a string, we know we've
  46086. // hit the next node's providers and directives and should stop copying data.
  46087. while (typeof propMetadata === 'string') {
  46088. var propertyName = propMetadata.split(INTERPOLATION_DELIMITER)[0];
  46089. properties[propertyName] = lView[hostPropIndex];
  46090. propMetadata = tData[++hostPropIndex];
  46091. }
  46092. return properties;
  46093. }
  46094. function collectClassNames(debugElement) {
  46095. var e_2, _a;
  46096. var classes = debugElement.classes;
  46097. var output = '';
  46098. try {
  46099. for (var _b = __values(Object.keys(classes)), _c = _b.next(); !_c.done; _c = _b.next()) {
  46100. var className = _c.value;
  46101. if (classes[className]) {
  46102. output = output ? output + (" " + className) : className;
  46103. }
  46104. }
  46105. }
  46106. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  46107. finally {
  46108. try {
  46109. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  46110. }
  46111. finally { if (e_2) throw e_2.error; }
  46112. }
  46113. return output;
  46114. }
  46115. // Need to keep the nodes in a global Map so that multiple angular apps are supported.
  46116. var _nativeNodeToDebugNode = new Map();
  46117. function getDebugNode__PRE_R3__(nativeNode) {
  46118. return _nativeNodeToDebugNode.get(nativeNode) || null;
  46119. }
  46120. var NG_DEBUG_PROPERTY = '__ng_debug__';
  46121. function getDebugNode__POST_R3__(nativeNode) {
  46122. if (nativeNode instanceof Node) {
  46123. if (!(nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY))) {
  46124. nativeNode[NG_DEBUG_PROPERTY] = nativeNode.nodeType == Node.ELEMENT_NODE ?
  46125. new DebugElement__POST_R3__(nativeNode) :
  46126. new DebugNode__POST_R3__(nativeNode);
  46127. }
  46128. return nativeNode[NG_DEBUG_PROPERTY];
  46129. }
  46130. return null;
  46131. }
  46132. /**
  46133. * @publicApi
  46134. */
  46135. var getDebugNode = getDebugNode__PRE_R3__;
  46136. function indexDebugNode(node) {
  46137. _nativeNodeToDebugNode.set(node.nativeNode, node);
  46138. }
  46139. function removeDebugNodeFromIndex(node) {
  46140. _nativeNodeToDebugNode.delete(node.nativeNode);
  46141. }
  46142. /**
  46143. * @license
  46144. * Copyright Google Inc. All Rights Reserved.
  46145. *
  46146. * Use of this source code is governed by an MIT-style license that can be
  46147. * found in the LICENSE file at https://angular.io/license
  46148. */
  46149. /**
  46150. * @license
  46151. * Copyright Google Inc. All Rights Reserved.
  46152. *
  46153. * Use of this source code is governed by an MIT-style license that can be
  46154. * found in the LICENSE file at https://angular.io/license
  46155. */
  46156. var _CORE_PLATFORM_PROVIDERS = [
  46157. // Set a default platform name for platforms that don't set it explicitly.
  46158. { provide: PLATFORM_ID, useValue: 'unknown' },
  46159. { provide: PlatformRef, deps: [Injector] },
  46160. { provide: TestabilityRegistry, deps: [] },
  46161. { provide: Console, deps: [] },
  46162. ];
  46163. /**
  46164. * This platform has to be included in any other platform
  46165. *
  46166. * @publicApi
  46167. */
  46168. var platformCore = createPlatformFactory(null, 'core', _CORE_PLATFORM_PROVIDERS);
  46169. /**
  46170. * @license
  46171. * Copyright Google Inc. All Rights Reserved.
  46172. *
  46173. * Use of this source code is governed by an MIT-style license that can be
  46174. * found in the LICENSE file at https://angular.io/license
  46175. */
  46176. function _iterableDiffersFactory() {
  46177. return defaultIterableDiffers;
  46178. }
  46179. function _keyValueDiffersFactory() {
  46180. return defaultKeyValueDiffers;
  46181. }
  46182. function _localeFactory(locale) {
  46183. return locale || 'en-US';
  46184. }
  46185. /**
  46186. * A built-in [dependency injection token](guide/glossary#di-token)
  46187. * that is used to configure the root injector for bootstrapping.
  46188. */
  46189. var APPLICATION_MODULE_PROVIDERS = [
  46190. {
  46191. provide: ApplicationRef,
  46192. useClass: ApplicationRef,
  46193. deps: [NgZone, Console, Injector, ErrorHandler, ComponentFactoryResolver, ApplicationInitStatus]
  46194. },
  46195. { provide: SCHEDULER, deps: [NgZone], useFactory: zoneSchedulerFactory },
  46196. {
  46197. provide: ApplicationInitStatus,
  46198. useClass: ApplicationInitStatus,
  46199. deps: [[new Optional(), APP_INITIALIZER]]
  46200. },
  46201. { provide: Compiler, useClass: Compiler, deps: [] },
  46202. APP_ID_RANDOM_PROVIDER,
  46203. { provide: IterableDiffers, useFactory: _iterableDiffersFactory, deps: [] },
  46204. { provide: KeyValueDiffers, useFactory: _keyValueDiffersFactory, deps: [] },
  46205. {
  46206. provide: LOCALE_ID$1,
  46207. useFactory: _localeFactory,
  46208. deps: [[new Inject(LOCALE_ID$1), new Optional(), new SkipSelf()]]
  46209. },
  46210. ];
  46211. /**
  46212. * Schedule work at next available slot.
  46213. *
  46214. * In Ivy this is just `requestAnimationFrame`. For compatibility reasons when bootstrapped
  46215. * using `platformRef.bootstrap` we need to use `NgZone.onStable` as the scheduling mechanism.
  46216. * This overrides the scheduling mechanism in Ivy to `NgZone.onStable`.
  46217. *
  46218. * @param ngZone NgZone to use for scheduling.
  46219. */
  46220. function zoneSchedulerFactory(ngZone) {
  46221. var queue = [];
  46222. ngZone.onStable.subscribe(function () {
  46223. while (queue.length) {
  46224. queue.pop()();
  46225. }
  46226. });
  46227. return function (fn) { queue.push(fn); };
  46228. }
  46229. /**
  46230. * Configures the root injector for an app with
  46231. * providers of `@angular/core` dependencies that `ApplicationRef` needs
  46232. * to bootstrap components.
  46233. *
  46234. * Re-exported by `BrowserModule`, which is included automatically in the root
  46235. * `AppModule` when you create a new app with the CLI `new` command.
  46236. *
  46237. * @publicApi
  46238. */
  46239. var ApplicationModule = /** @class */ (function () {
  46240. // Inject ApplicationRef to make it eager...
  46241. function ApplicationModule(appRef) {
  46242. }
  46243. ApplicationModule = __decorate([
  46244. NgModule({ providers: APPLICATION_MODULE_PROVIDERS }),
  46245. __metadata("design:paramtypes", [ApplicationRef])
  46246. ], ApplicationModule);
  46247. return ApplicationModule;
  46248. }());
  46249. /**
  46250. * @license
  46251. * Copyright Google Inc. All Rights Reserved.
  46252. *
  46253. * Use of this source code is governed by an MIT-style license that can be
  46254. * found in the LICENSE file at https://angular.io/license
  46255. */
  46256. function createElement(view, renderHost, def) {
  46257. var elDef = def.element;
  46258. var rootSelectorOrNode = view.root.selectorOrNode;
  46259. var renderer = view.renderer;
  46260. var el;
  46261. if (view.parent || !rootSelectorOrNode) {
  46262. if (elDef.name) {
  46263. el = renderer.createElement(elDef.name, elDef.ns);
  46264. }
  46265. else {
  46266. el = renderer.createComment('');
  46267. }
  46268. var parentEl = getParentRenderElement(view, renderHost, def);
  46269. if (parentEl) {
  46270. renderer.appendChild(parentEl, el);
  46271. }
  46272. }
  46273. else {
  46274. // when using native Shadow DOM, do not clear the root element contents to allow slot projection
  46275. var preserveContent = (!!elDef.componentRendererType &&
  46276. elDef.componentRendererType.encapsulation === ViewEncapsulation$1.ShadowDom);
  46277. el = renderer.selectRootElement(rootSelectorOrNode, preserveContent);
  46278. }
  46279. if (elDef.attrs) {
  46280. for (var i = 0; i < elDef.attrs.length; i++) {
  46281. var _a = __read(elDef.attrs[i], 3), ns = _a[0], name_2 = _a[1], value = _a[2];
  46282. renderer.setAttribute(el, name_2, value, ns);
  46283. }
  46284. }
  46285. return el;
  46286. }
  46287. function listenToElementOutputs(view, compView, def, el) {
  46288. for (var i = 0; i < def.outputs.length; i++) {
  46289. var output = def.outputs[i];
  46290. var handleEventClosure = renderEventHandlerClosure(view, def.nodeIndex, elementEventFullName(output.target, output.eventName));
  46291. var listenTarget = output.target;
  46292. var listenerView = view;
  46293. if (output.target === 'component') {
  46294. listenTarget = null;
  46295. listenerView = compView;
  46296. }
  46297. var disposable = listenerView.renderer.listen(listenTarget || el, output.eventName, handleEventClosure);
  46298. view.disposables[def.outputIndex + i] = disposable;
  46299. }
  46300. }
  46301. function renderEventHandlerClosure(view, index, eventName) {
  46302. return function (event) { return dispatchEvent(view, index, eventName, event); };
  46303. }
  46304. function checkAndUpdateElementInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  46305. var bindLen = def.bindings.length;
  46306. var changed = false;
  46307. if (bindLen > 0 && checkAndUpdateElementValue(view, def, 0, v0))
  46308. changed = true;
  46309. if (bindLen > 1 && checkAndUpdateElementValue(view, def, 1, v1))
  46310. changed = true;
  46311. if (bindLen > 2 && checkAndUpdateElementValue(view, def, 2, v2))
  46312. changed = true;
  46313. if (bindLen > 3 && checkAndUpdateElementValue(view, def, 3, v3))
  46314. changed = true;
  46315. if (bindLen > 4 && checkAndUpdateElementValue(view, def, 4, v4))
  46316. changed = true;
  46317. if (bindLen > 5 && checkAndUpdateElementValue(view, def, 5, v5))
  46318. changed = true;
  46319. if (bindLen > 6 && checkAndUpdateElementValue(view, def, 6, v6))
  46320. changed = true;
  46321. if (bindLen > 7 && checkAndUpdateElementValue(view, def, 7, v7))
  46322. changed = true;
  46323. if (bindLen > 8 && checkAndUpdateElementValue(view, def, 8, v8))
  46324. changed = true;
  46325. if (bindLen > 9 && checkAndUpdateElementValue(view, def, 9, v9))
  46326. changed = true;
  46327. return changed;
  46328. }
  46329. function checkAndUpdateElementDynamic(view, def, values) {
  46330. var changed = false;
  46331. for (var i = 0; i < values.length; i++) {
  46332. if (checkAndUpdateElementValue(view, def, i, values[i]))
  46333. changed = true;
  46334. }
  46335. return changed;
  46336. }
  46337. function checkAndUpdateElementValue(view, def, bindingIdx, value) {
  46338. if (!checkAndUpdateBinding(view, def, bindingIdx, value)) {
  46339. return false;
  46340. }
  46341. var binding = def.bindings[bindingIdx];
  46342. var elData = asElementData(view, def.nodeIndex);
  46343. var renderNode = elData.renderElement;
  46344. var name = binding.name;
  46345. switch (binding.flags & 15 /* Types */) {
  46346. case 1 /* TypeElementAttribute */:
  46347. setElementAttribute(view, binding, renderNode, binding.ns, name, value);
  46348. break;
  46349. case 2 /* TypeElementClass */:
  46350. setElementClass(view, renderNode, name, value);
  46351. break;
  46352. case 4 /* TypeElementStyle */:
  46353. setElementStyle(view, binding, renderNode, name, value);
  46354. break;
  46355. case 8 /* TypeProperty */:
  46356. var bindView = (def.flags & 33554432 /* ComponentView */ &&
  46357. binding.flags & 32 /* SyntheticHostProperty */) ?
  46358. elData.componentView :
  46359. view;
  46360. setElementProperty(bindView, binding, renderNode, name, value);
  46361. break;
  46362. }
  46363. return true;
  46364. }
  46365. function setElementAttribute(view, binding, renderNode, ns, name, value) {
  46366. var securityContext = binding.securityContext;
  46367. var renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
  46368. renderValue = renderValue != null ? renderValue.toString() : null;
  46369. var renderer = view.renderer;
  46370. if (value != null) {
  46371. renderer.setAttribute(renderNode, name, renderValue, ns);
  46372. }
  46373. else {
  46374. renderer.removeAttribute(renderNode, name, ns);
  46375. }
  46376. }
  46377. function setElementClass(view, renderNode, name, value) {
  46378. var renderer = view.renderer;
  46379. if (value) {
  46380. renderer.addClass(renderNode, name);
  46381. }
  46382. else {
  46383. renderer.removeClass(renderNode, name);
  46384. }
  46385. }
  46386. function setElementStyle(view, binding, renderNode, name, value) {
  46387. var renderValue = view.root.sanitizer.sanitize(SecurityContext$1.STYLE, value);
  46388. if (renderValue != null) {
  46389. renderValue = renderValue.toString();
  46390. var unit = binding.suffix;
  46391. if (unit != null) {
  46392. renderValue = renderValue + unit;
  46393. }
  46394. }
  46395. else {
  46396. renderValue = null;
  46397. }
  46398. var renderer = view.renderer;
  46399. if (renderValue != null) {
  46400. renderer.setStyle(renderNode, name, renderValue);
  46401. }
  46402. else {
  46403. renderer.removeStyle(renderNode, name);
  46404. }
  46405. }
  46406. function setElementProperty(view, binding, renderNode, name, value) {
  46407. var securityContext = binding.securityContext;
  46408. var renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
  46409. view.renderer.setProperty(renderNode, name, renderValue);
  46410. }
  46411. /**
  46412. * @license
  46413. * Copyright Google Inc. All Rights Reserved.
  46414. *
  46415. * Use of this source code is governed by an MIT-style license that can be
  46416. * found in the LICENSE file at https://angular.io/license
  46417. */
  46418. function createQuery() {
  46419. return new QueryList();
  46420. }
  46421. function dirtyParentQueries(view) {
  46422. var queryIds = view.def.nodeMatchedQueries;
  46423. while (view.parent && isEmbeddedView(view)) {
  46424. var tplDef = view.parentNodeDef;
  46425. view = view.parent;
  46426. // content queries
  46427. var end = tplDef.nodeIndex + tplDef.childCount;
  46428. for (var i = 0; i <= end; i++) {
  46429. var nodeDef = view.def.nodes[i];
  46430. if ((nodeDef.flags & 67108864 /* TypeContentQuery */) &&
  46431. (nodeDef.flags & 536870912 /* DynamicQuery */) &&
  46432. (nodeDef.query.filterId & queryIds) === nodeDef.query.filterId) {
  46433. asQueryList(view, i).setDirty();
  46434. }
  46435. if ((nodeDef.flags & 1 /* TypeElement */ && i + nodeDef.childCount < tplDef.nodeIndex) ||
  46436. !(nodeDef.childFlags & 67108864 /* TypeContentQuery */) ||
  46437. !(nodeDef.childFlags & 536870912 /* DynamicQuery */)) {
  46438. // skip elements that don't contain the template element or no query.
  46439. i += nodeDef.childCount;
  46440. }
  46441. }
  46442. }
  46443. // view queries
  46444. if (view.def.nodeFlags & 134217728 /* TypeViewQuery */) {
  46445. for (var i = 0; i < view.def.nodes.length; i++) {
  46446. var nodeDef = view.def.nodes[i];
  46447. if ((nodeDef.flags & 134217728 /* TypeViewQuery */) && (nodeDef.flags & 536870912 /* DynamicQuery */)) {
  46448. asQueryList(view, i).setDirty();
  46449. }
  46450. // only visit the root nodes
  46451. i += nodeDef.childCount;
  46452. }
  46453. }
  46454. }
  46455. function checkAndUpdateQuery(view, nodeDef) {
  46456. var queryList = asQueryList(view, nodeDef.nodeIndex);
  46457. if (!queryList.dirty) {
  46458. return;
  46459. }
  46460. var directiveInstance;
  46461. var newValues = undefined;
  46462. if (nodeDef.flags & 67108864 /* TypeContentQuery */) {
  46463. var elementDef = nodeDef.parent.parent;
  46464. newValues = calcQueryValues(view, elementDef.nodeIndex, elementDef.nodeIndex + elementDef.childCount, nodeDef.query, []);
  46465. directiveInstance = asProviderData(view, nodeDef.parent.nodeIndex).instance;
  46466. }
  46467. else if (nodeDef.flags & 134217728 /* TypeViewQuery */) {
  46468. newValues = calcQueryValues(view, 0, view.def.nodes.length - 1, nodeDef.query, []);
  46469. directiveInstance = view.component;
  46470. }
  46471. queryList.reset(newValues);
  46472. var bindings = nodeDef.query.bindings;
  46473. var notify = false;
  46474. for (var i = 0; i < bindings.length; i++) {
  46475. var binding = bindings[i];
  46476. var boundValue = void 0;
  46477. switch (binding.bindingType) {
  46478. case 0 /* First */:
  46479. boundValue = queryList.first;
  46480. break;
  46481. case 1 /* All */:
  46482. boundValue = queryList;
  46483. notify = true;
  46484. break;
  46485. }
  46486. directiveInstance[binding.propName] = boundValue;
  46487. }
  46488. if (notify) {
  46489. queryList.notifyOnChanges();
  46490. }
  46491. }
  46492. function calcQueryValues(view, startIndex, endIndex, queryDef, values) {
  46493. for (var i = startIndex; i <= endIndex; i++) {
  46494. var nodeDef = view.def.nodes[i];
  46495. var valueType = nodeDef.matchedQueries[queryDef.id];
  46496. if (valueType != null) {
  46497. values.push(getQueryValue(view, nodeDef, valueType));
  46498. }
  46499. if (nodeDef.flags & 1 /* TypeElement */ && nodeDef.element.template &&
  46500. (nodeDef.element.template.nodeMatchedQueries & queryDef.filterId) ===
  46501. queryDef.filterId) {
  46502. var elementData = asElementData(view, i);
  46503. // check embedded views that were attached at the place of their template,
  46504. // but process child nodes first if some match the query (see issue #16568)
  46505. if ((nodeDef.childMatchedQueries & queryDef.filterId) === queryDef.filterId) {
  46506. calcQueryValues(view, i + 1, i + nodeDef.childCount, queryDef, values);
  46507. i += nodeDef.childCount;
  46508. }
  46509. if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
  46510. var embeddedViews = elementData.viewContainer._embeddedViews;
  46511. for (var k = 0; k < embeddedViews.length; k++) {
  46512. var embeddedView = embeddedViews[k];
  46513. var dvc = declaredViewContainer(embeddedView);
  46514. if (dvc && dvc === elementData) {
  46515. calcQueryValues(embeddedView, 0, embeddedView.def.nodes.length - 1, queryDef, values);
  46516. }
  46517. }
  46518. }
  46519. var projectedViews = elementData.template._projectedViews;
  46520. if (projectedViews) {
  46521. for (var k = 0; k < projectedViews.length; k++) {
  46522. var projectedView = projectedViews[k];
  46523. calcQueryValues(projectedView, 0, projectedView.def.nodes.length - 1, queryDef, values);
  46524. }
  46525. }
  46526. }
  46527. if ((nodeDef.childMatchedQueries & queryDef.filterId) !== queryDef.filterId) {
  46528. // if no child matches the query, skip the children.
  46529. i += nodeDef.childCount;
  46530. }
  46531. }
  46532. return values;
  46533. }
  46534. function getQueryValue(view, nodeDef, queryValueType) {
  46535. if (queryValueType != null) {
  46536. // a match
  46537. switch (queryValueType) {
  46538. case 1 /* RenderElement */:
  46539. return asElementData(view, nodeDef.nodeIndex).renderElement;
  46540. case 0 /* ElementRef */:
  46541. return new ElementRef(asElementData(view, nodeDef.nodeIndex).renderElement);
  46542. case 2 /* TemplateRef */:
  46543. return asElementData(view, nodeDef.nodeIndex).template;
  46544. case 3 /* ViewContainerRef */:
  46545. return asElementData(view, nodeDef.nodeIndex).viewContainer;
  46546. case 4 /* Provider */:
  46547. return asProviderData(view, nodeDef.nodeIndex).instance;
  46548. }
  46549. }
  46550. }
  46551. /**
  46552. * @license
  46553. * Copyright Google Inc. All Rights Reserved.
  46554. *
  46555. * Use of this source code is governed by an MIT-style license that can be
  46556. * found in the LICENSE file at https://angular.io/license
  46557. */
  46558. function appendNgContent(view, renderHost, def) {
  46559. var parentEl = getParentRenderElement(view, renderHost, def);
  46560. if (!parentEl) {
  46561. // Nothing to do if there is no parent element.
  46562. return;
  46563. }
  46564. var ngContentIndex = def.ngContent.index;
  46565. visitProjectedRenderNodes(view, ngContentIndex, 1 /* AppendChild */, parentEl, null, undefined);
  46566. }
  46567. /**
  46568. * @license
  46569. * Copyright Google Inc. All Rights Reserved.
  46570. *
  46571. * Use of this source code is governed by an MIT-style license that can be
  46572. * found in the LICENSE file at https://angular.io/license
  46573. */
  46574. function createPureExpression(view, def) {
  46575. return { value: undefined };
  46576. }
  46577. function checkAndUpdatePureExpressionInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  46578. var bindings = def.bindings;
  46579. var changed = false;
  46580. var bindLen = bindings.length;
  46581. if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
  46582. changed = true;
  46583. if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
  46584. changed = true;
  46585. if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
  46586. changed = true;
  46587. if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
  46588. changed = true;
  46589. if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
  46590. changed = true;
  46591. if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
  46592. changed = true;
  46593. if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
  46594. changed = true;
  46595. if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
  46596. changed = true;
  46597. if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
  46598. changed = true;
  46599. if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
  46600. changed = true;
  46601. if (changed) {
  46602. var data = asPureExpressionData(view, def.nodeIndex);
  46603. var value = void 0;
  46604. switch (def.flags & 201347067 /* Types */) {
  46605. case 32 /* TypePureArray */:
  46606. value = new Array(bindings.length);
  46607. if (bindLen > 0)
  46608. value[0] = v0;
  46609. if (bindLen > 1)
  46610. value[1] = v1;
  46611. if (bindLen > 2)
  46612. value[2] = v2;
  46613. if (bindLen > 3)
  46614. value[3] = v3;
  46615. if (bindLen > 4)
  46616. value[4] = v4;
  46617. if (bindLen > 5)
  46618. value[5] = v5;
  46619. if (bindLen > 6)
  46620. value[6] = v6;
  46621. if (bindLen > 7)
  46622. value[7] = v7;
  46623. if (bindLen > 8)
  46624. value[8] = v8;
  46625. if (bindLen > 9)
  46626. value[9] = v9;
  46627. break;
  46628. case 64 /* TypePureObject */:
  46629. value = {};
  46630. if (bindLen > 0)
  46631. value[bindings[0].name] = v0;
  46632. if (bindLen > 1)
  46633. value[bindings[1].name] = v1;
  46634. if (bindLen > 2)
  46635. value[bindings[2].name] = v2;
  46636. if (bindLen > 3)
  46637. value[bindings[3].name] = v3;
  46638. if (bindLen > 4)
  46639. value[bindings[4].name] = v4;
  46640. if (bindLen > 5)
  46641. value[bindings[5].name] = v5;
  46642. if (bindLen > 6)
  46643. value[bindings[6].name] = v6;
  46644. if (bindLen > 7)
  46645. value[bindings[7].name] = v7;
  46646. if (bindLen > 8)
  46647. value[bindings[8].name] = v8;
  46648. if (bindLen > 9)
  46649. value[bindings[9].name] = v9;
  46650. break;
  46651. case 128 /* TypePurePipe */:
  46652. var pipe = v0;
  46653. switch (bindLen) {
  46654. case 1:
  46655. value = pipe.transform(v0);
  46656. break;
  46657. case 2:
  46658. value = pipe.transform(v1);
  46659. break;
  46660. case 3:
  46661. value = pipe.transform(v1, v2);
  46662. break;
  46663. case 4:
  46664. value = pipe.transform(v1, v2, v3);
  46665. break;
  46666. case 5:
  46667. value = pipe.transform(v1, v2, v3, v4);
  46668. break;
  46669. case 6:
  46670. value = pipe.transform(v1, v2, v3, v4, v5);
  46671. break;
  46672. case 7:
  46673. value = pipe.transform(v1, v2, v3, v4, v5, v6);
  46674. break;
  46675. case 8:
  46676. value = pipe.transform(v1, v2, v3, v4, v5, v6, v7);
  46677. break;
  46678. case 9:
  46679. value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8);
  46680. break;
  46681. case 10:
  46682. value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8, v9);
  46683. break;
  46684. }
  46685. break;
  46686. }
  46687. data.value = value;
  46688. }
  46689. return changed;
  46690. }
  46691. function checkAndUpdatePureExpressionDynamic(view, def, values) {
  46692. var bindings = def.bindings;
  46693. var changed = false;
  46694. for (var i = 0; i < values.length; i++) {
  46695. // Note: We need to loop over all values, so that
  46696. // the old values are updates as well!
  46697. if (checkAndUpdateBinding(view, def, i, values[i])) {
  46698. changed = true;
  46699. }
  46700. }
  46701. if (changed) {
  46702. var data = asPureExpressionData(view, def.nodeIndex);
  46703. var value = void 0;
  46704. switch (def.flags & 201347067 /* Types */) {
  46705. case 32 /* TypePureArray */:
  46706. value = values;
  46707. break;
  46708. case 64 /* TypePureObject */:
  46709. value = {};
  46710. for (var i = 0; i < values.length; i++) {
  46711. value[bindings[i].name] = values[i];
  46712. }
  46713. break;
  46714. case 128 /* TypePurePipe */:
  46715. var pipe = values[0];
  46716. var params = values.slice(1);
  46717. value = pipe.transform.apply(pipe, __spread(params));
  46718. break;
  46719. }
  46720. data.value = value;
  46721. }
  46722. return changed;
  46723. }
  46724. /**
  46725. * @license
  46726. * Copyright Google Inc. All Rights Reserved.
  46727. *
  46728. * Use of this source code is governed by an MIT-style license that can be
  46729. * found in the LICENSE file at https://angular.io/license
  46730. */
  46731. function createText(view, renderHost, def) {
  46732. var renderNode;
  46733. var renderer = view.renderer;
  46734. renderNode = renderer.createText(def.text.prefix);
  46735. var parentEl = getParentRenderElement(view, renderHost, def);
  46736. if (parentEl) {
  46737. renderer.appendChild(parentEl, renderNode);
  46738. }
  46739. return { renderText: renderNode };
  46740. }
  46741. function checkAndUpdateTextInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  46742. var changed = false;
  46743. var bindings = def.bindings;
  46744. var bindLen = bindings.length;
  46745. if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
  46746. changed = true;
  46747. if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
  46748. changed = true;
  46749. if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
  46750. changed = true;
  46751. if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
  46752. changed = true;
  46753. if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
  46754. changed = true;
  46755. if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
  46756. changed = true;
  46757. if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
  46758. changed = true;
  46759. if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
  46760. changed = true;
  46761. if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
  46762. changed = true;
  46763. if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
  46764. changed = true;
  46765. if (changed) {
  46766. var value = def.text.prefix;
  46767. if (bindLen > 0)
  46768. value += _addInterpolationPart(v0, bindings[0]);
  46769. if (bindLen > 1)
  46770. value += _addInterpolationPart(v1, bindings[1]);
  46771. if (bindLen > 2)
  46772. value += _addInterpolationPart(v2, bindings[2]);
  46773. if (bindLen > 3)
  46774. value += _addInterpolationPart(v3, bindings[3]);
  46775. if (bindLen > 4)
  46776. value += _addInterpolationPart(v4, bindings[4]);
  46777. if (bindLen > 5)
  46778. value += _addInterpolationPart(v5, bindings[5]);
  46779. if (bindLen > 6)
  46780. value += _addInterpolationPart(v6, bindings[6]);
  46781. if (bindLen > 7)
  46782. value += _addInterpolationPart(v7, bindings[7]);
  46783. if (bindLen > 8)
  46784. value += _addInterpolationPart(v8, bindings[8]);
  46785. if (bindLen > 9)
  46786. value += _addInterpolationPart(v9, bindings[9]);
  46787. var renderNode = asTextData(view, def.nodeIndex).renderText;
  46788. view.renderer.setValue(renderNode, value);
  46789. }
  46790. return changed;
  46791. }
  46792. function checkAndUpdateTextDynamic(view, def, values) {
  46793. var bindings = def.bindings;
  46794. var changed = false;
  46795. for (var i = 0; i < values.length; i++) {
  46796. // Note: We need to loop over all values, so that
  46797. // the old values are updates as well!
  46798. if (checkAndUpdateBinding(view, def, i, values[i])) {
  46799. changed = true;
  46800. }
  46801. }
  46802. if (changed) {
  46803. var value = '';
  46804. for (var i = 0; i < values.length; i++) {
  46805. value = value + _addInterpolationPart(values[i], bindings[i]);
  46806. }
  46807. value = def.text.prefix + value;
  46808. var renderNode = asTextData(view, def.nodeIndex).renderText;
  46809. view.renderer.setValue(renderNode, value);
  46810. }
  46811. return changed;
  46812. }
  46813. function _addInterpolationPart(value, binding) {
  46814. var valueStr = value != null ? value.toString() : '';
  46815. return valueStr + binding.suffix;
  46816. }
  46817. /**
  46818. * @license
  46819. * Copyright Google Inc. All Rights Reserved.
  46820. *
  46821. * Use of this source code is governed by an MIT-style license that can be
  46822. * found in the LICENSE file at https://angular.io/license
  46823. */
  46824. function createEmbeddedView(parent, anchorDef, viewDef, context) {
  46825. // embedded views are seen as siblings to the anchor, so we need
  46826. // to get the parent of the anchor and use it as parentIndex.
  46827. var view = createView(parent.root, parent.renderer, parent, anchorDef, viewDef);
  46828. initView(view, parent.component, context);
  46829. createViewNodes(view);
  46830. return view;
  46831. }
  46832. function createRootView(root, def, context) {
  46833. var view = createView(root, root.renderer, null, null, def);
  46834. initView(view, context, context);
  46835. createViewNodes(view);
  46836. return view;
  46837. }
  46838. function createComponentView(parentView, nodeDef, viewDef, hostElement) {
  46839. var rendererType = nodeDef.element.componentRendererType;
  46840. var compRenderer;
  46841. if (!rendererType) {
  46842. compRenderer = parentView.root.renderer;
  46843. }
  46844. else {
  46845. compRenderer = parentView.root.rendererFactory.createRenderer(hostElement, rendererType);
  46846. }
  46847. return createView(parentView.root, compRenderer, parentView, nodeDef.element.componentProvider, viewDef);
  46848. }
  46849. function createView(root, renderer, parent, parentNodeDef, def) {
  46850. var nodes = new Array(def.nodes.length);
  46851. var disposables = def.outputCount ? new Array(def.outputCount) : null;
  46852. var view = {
  46853. def: def,
  46854. parent: parent,
  46855. viewContainerParent: null, parentNodeDef: parentNodeDef,
  46856. context: null,
  46857. component: null, nodes: nodes,
  46858. state: 13 /* CatInit */, root: root, renderer: renderer,
  46859. oldValues: new Array(def.bindingCount), disposables: disposables,
  46860. initIndex: -1
  46861. };
  46862. return view;
  46863. }
  46864. function initView(view, component, context) {
  46865. view.component = component;
  46866. view.context = context;
  46867. }
  46868. function createViewNodes(view) {
  46869. var renderHost;
  46870. if (isComponentView(view)) {
  46871. var hostDef = view.parentNodeDef;
  46872. renderHost = asElementData(view.parent, hostDef.parent.nodeIndex).renderElement;
  46873. }
  46874. var def = view.def;
  46875. var nodes = view.nodes;
  46876. for (var i = 0; i < def.nodes.length; i++) {
  46877. var nodeDef = def.nodes[i];
  46878. Services.setCurrentNode(view, i);
  46879. var nodeData = void 0;
  46880. switch (nodeDef.flags & 201347067 /* Types */) {
  46881. case 1 /* TypeElement */:
  46882. var el = createElement(view, renderHost, nodeDef);
  46883. var componentView = undefined;
  46884. if (nodeDef.flags & 33554432 /* ComponentView */) {
  46885. var compViewDef = resolveDefinition(nodeDef.element.componentView);
  46886. componentView = Services.createComponentView(view, nodeDef, compViewDef, el);
  46887. }
  46888. listenToElementOutputs(view, componentView, nodeDef, el);
  46889. nodeData = {
  46890. renderElement: el,
  46891. componentView: componentView,
  46892. viewContainer: null,
  46893. template: nodeDef.element.template ? createTemplateData(view, nodeDef) : undefined
  46894. };
  46895. if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
  46896. nodeData.viewContainer = createViewContainerData(view, nodeDef, nodeData);
  46897. }
  46898. break;
  46899. case 2 /* TypeText */:
  46900. nodeData = createText(view, renderHost, nodeDef);
  46901. break;
  46902. case 512 /* TypeClassProvider */:
  46903. case 1024 /* TypeFactoryProvider */:
  46904. case 2048 /* TypeUseExistingProvider */:
  46905. case 256 /* TypeValueProvider */: {
  46906. nodeData = nodes[i];
  46907. if (!nodeData && !(nodeDef.flags & 4096 /* LazyProvider */)) {
  46908. var instance = createProviderInstance(view, nodeDef);
  46909. nodeData = { instance: instance };
  46910. }
  46911. break;
  46912. }
  46913. case 16 /* TypePipe */: {
  46914. var instance = createPipeInstance(view, nodeDef);
  46915. nodeData = { instance: instance };
  46916. break;
  46917. }
  46918. case 16384 /* TypeDirective */: {
  46919. nodeData = nodes[i];
  46920. if (!nodeData) {
  46921. var instance = createDirectiveInstance(view, nodeDef);
  46922. nodeData = { instance: instance };
  46923. }
  46924. if (nodeDef.flags & 32768 /* Component */) {
  46925. var compView = asElementData(view, nodeDef.parent.nodeIndex).componentView;
  46926. initView(compView, nodeData.instance, nodeData.instance);
  46927. }
  46928. break;
  46929. }
  46930. case 32 /* TypePureArray */:
  46931. case 64 /* TypePureObject */:
  46932. case 128 /* TypePurePipe */:
  46933. nodeData = createPureExpression(view, nodeDef);
  46934. break;
  46935. case 67108864 /* TypeContentQuery */:
  46936. case 134217728 /* TypeViewQuery */:
  46937. nodeData = createQuery();
  46938. break;
  46939. case 8 /* TypeNgContent */:
  46940. appendNgContent(view, renderHost, nodeDef);
  46941. // no runtime data needed for NgContent...
  46942. nodeData = undefined;
  46943. break;
  46944. }
  46945. nodes[i] = nodeData;
  46946. }
  46947. // Create the ViewData.nodes of component views after we created everything else,
  46948. // so that e.g. ng-content works
  46949. execComponentViewsAction(view, ViewAction.CreateViewNodes);
  46950. // fill static content and view queries
  46951. execQueriesAction(view, 67108864 /* TypeContentQuery */ | 134217728 /* TypeViewQuery */, 268435456 /* StaticQuery */, 0 /* CheckAndUpdate */);
  46952. }
  46953. function checkNoChangesView(view) {
  46954. markProjectedViewsForCheck(view);
  46955. Services.updateDirectives(view, 1 /* CheckNoChanges */);
  46956. execEmbeddedViewsAction(view, ViewAction.CheckNoChanges);
  46957. Services.updateRenderer(view, 1 /* CheckNoChanges */);
  46958. execComponentViewsAction(view, ViewAction.CheckNoChanges);
  46959. // Note: We don't check queries for changes as we didn't do this in v2.x.
  46960. // TODO(tbosch): investigate if we can enable the check again in v5.x with a nicer error message.
  46961. view.state &= ~(64 /* CheckProjectedViews */ | 32 /* CheckProjectedView */);
  46962. }
  46963. function checkAndUpdateView(view) {
  46964. if (view.state & 1 /* BeforeFirstCheck */) {
  46965. view.state &= ~1 /* BeforeFirstCheck */;
  46966. view.state |= 2 /* FirstCheck */;
  46967. }
  46968. else {
  46969. view.state &= ~2 /* FirstCheck */;
  46970. }
  46971. shiftInitState(view, 0 /* InitState_BeforeInit */, 256 /* InitState_CallingOnInit */);
  46972. markProjectedViewsForCheck(view);
  46973. Services.updateDirectives(view, 0 /* CheckAndUpdate */);
  46974. execEmbeddedViewsAction(view, ViewAction.CheckAndUpdate);
  46975. execQueriesAction(view, 67108864 /* TypeContentQuery */, 536870912 /* DynamicQuery */, 0 /* CheckAndUpdate */);
  46976. var callInit = shiftInitState(view, 256 /* InitState_CallingOnInit */, 512 /* InitState_CallingAfterContentInit */);
  46977. callLifecycleHooksChildrenFirst(view, 2097152 /* AfterContentChecked */ | (callInit ? 1048576 /* AfterContentInit */ : 0));
  46978. Services.updateRenderer(view, 0 /* CheckAndUpdate */);
  46979. execComponentViewsAction(view, ViewAction.CheckAndUpdate);
  46980. execQueriesAction(view, 134217728 /* TypeViewQuery */, 536870912 /* DynamicQuery */, 0 /* CheckAndUpdate */);
  46981. callInit = shiftInitState(view, 512 /* InitState_CallingAfterContentInit */, 768 /* InitState_CallingAfterViewInit */);
  46982. callLifecycleHooksChildrenFirst(view, 8388608 /* AfterViewChecked */ | (callInit ? 4194304 /* AfterViewInit */ : 0));
  46983. if (view.def.flags & 2 /* OnPush */) {
  46984. view.state &= ~8 /* ChecksEnabled */;
  46985. }
  46986. view.state &= ~(64 /* CheckProjectedViews */ | 32 /* CheckProjectedView */);
  46987. shiftInitState(view, 768 /* InitState_CallingAfterViewInit */, 1024 /* InitState_AfterInit */);
  46988. }
  46989. function checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  46990. if (argStyle === 0 /* Inline */) {
  46991. return checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  46992. }
  46993. else {
  46994. return checkAndUpdateNodeDynamic(view, nodeDef, v0);
  46995. }
  46996. }
  46997. function markProjectedViewsForCheck(view) {
  46998. var def = view.def;
  46999. if (!(def.nodeFlags & 4 /* ProjectedTemplate */)) {
  47000. return;
  47001. }
  47002. for (var i = 0; i < def.nodes.length; i++) {
  47003. var nodeDef = def.nodes[i];
  47004. if (nodeDef.flags & 4 /* ProjectedTemplate */) {
  47005. var projectedViews = asElementData(view, i).template._projectedViews;
  47006. if (projectedViews) {
  47007. for (var i_1 = 0; i_1 < projectedViews.length; i_1++) {
  47008. var projectedView = projectedViews[i_1];
  47009. projectedView.state |= 32 /* CheckProjectedView */;
  47010. markParentViewsForCheckProjectedViews(projectedView, view);
  47011. }
  47012. }
  47013. }
  47014. else if ((nodeDef.childFlags & 4 /* ProjectedTemplate */) === 0) {
  47015. // a parent with leafs
  47016. // no child is a component,
  47017. // then skip the children
  47018. i += nodeDef.childCount;
  47019. }
  47020. }
  47021. }
  47022. function checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  47023. switch (nodeDef.flags & 201347067 /* Types */) {
  47024. case 1 /* TypeElement */:
  47025. return checkAndUpdateElementInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47026. case 2 /* TypeText */:
  47027. return checkAndUpdateTextInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47028. case 16384 /* TypeDirective */:
  47029. return checkAndUpdateDirectiveInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47030. case 32 /* TypePureArray */:
  47031. case 64 /* TypePureObject */:
  47032. case 128 /* TypePurePipe */:
  47033. return checkAndUpdatePureExpressionInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47034. default:
  47035. throw 'unreachable';
  47036. }
  47037. }
  47038. function checkAndUpdateNodeDynamic(view, nodeDef, values) {
  47039. switch (nodeDef.flags & 201347067 /* Types */) {
  47040. case 1 /* TypeElement */:
  47041. return checkAndUpdateElementDynamic(view, nodeDef, values);
  47042. case 2 /* TypeText */:
  47043. return checkAndUpdateTextDynamic(view, nodeDef, values);
  47044. case 16384 /* TypeDirective */:
  47045. return checkAndUpdateDirectiveDynamic(view, nodeDef, values);
  47046. case 32 /* TypePureArray */:
  47047. case 64 /* TypePureObject */:
  47048. case 128 /* TypePurePipe */:
  47049. return checkAndUpdatePureExpressionDynamic(view, nodeDef, values);
  47050. default:
  47051. throw 'unreachable';
  47052. }
  47053. }
  47054. function checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  47055. if (argStyle === 0 /* Inline */) {
  47056. checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47057. }
  47058. else {
  47059. checkNoChangesNodeDynamic(view, nodeDef, v0);
  47060. }
  47061. // Returning false is ok here as we would have thrown in case of a change.
  47062. return false;
  47063. }
  47064. function checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  47065. var bindLen = nodeDef.bindings.length;
  47066. if (bindLen > 0)
  47067. checkBindingNoChanges(view, nodeDef, 0, v0);
  47068. if (bindLen > 1)
  47069. checkBindingNoChanges(view, nodeDef, 1, v1);
  47070. if (bindLen > 2)
  47071. checkBindingNoChanges(view, nodeDef, 2, v2);
  47072. if (bindLen > 3)
  47073. checkBindingNoChanges(view, nodeDef, 3, v3);
  47074. if (bindLen > 4)
  47075. checkBindingNoChanges(view, nodeDef, 4, v4);
  47076. if (bindLen > 5)
  47077. checkBindingNoChanges(view, nodeDef, 5, v5);
  47078. if (bindLen > 6)
  47079. checkBindingNoChanges(view, nodeDef, 6, v6);
  47080. if (bindLen > 7)
  47081. checkBindingNoChanges(view, nodeDef, 7, v7);
  47082. if (bindLen > 8)
  47083. checkBindingNoChanges(view, nodeDef, 8, v8);
  47084. if (bindLen > 9)
  47085. checkBindingNoChanges(view, nodeDef, 9, v9);
  47086. }
  47087. function checkNoChangesNodeDynamic(view, nodeDef, values) {
  47088. for (var i = 0; i < values.length; i++) {
  47089. checkBindingNoChanges(view, nodeDef, i, values[i]);
  47090. }
  47091. }
  47092. /**
  47093. * Workaround https://github.com/angular/tsickle/issues/497
  47094. * @suppress {misplacedTypeAnnotation}
  47095. */
  47096. function checkNoChangesQuery(view, nodeDef) {
  47097. var queryList = asQueryList(view, nodeDef.nodeIndex);
  47098. if (queryList.dirty) {
  47099. throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, nodeDef.nodeIndex), "Query " + nodeDef.query.id + " not dirty", "Query " + nodeDef.query.id + " dirty", (view.state & 1 /* BeforeFirstCheck */) !== 0);
  47100. }
  47101. }
  47102. function destroyView(view) {
  47103. if (view.state & 128 /* Destroyed */) {
  47104. return;
  47105. }
  47106. execEmbeddedViewsAction(view, ViewAction.Destroy);
  47107. execComponentViewsAction(view, ViewAction.Destroy);
  47108. callLifecycleHooksChildrenFirst(view, 131072 /* OnDestroy */);
  47109. if (view.disposables) {
  47110. for (var i = 0; i < view.disposables.length; i++) {
  47111. view.disposables[i]();
  47112. }
  47113. }
  47114. detachProjectedView(view);
  47115. if (view.renderer.destroyNode) {
  47116. destroyViewNodes(view);
  47117. }
  47118. if (isComponentView(view)) {
  47119. view.renderer.destroy();
  47120. }
  47121. view.state |= 128 /* Destroyed */;
  47122. }
  47123. function destroyViewNodes(view) {
  47124. var len = view.def.nodes.length;
  47125. for (var i = 0; i < len; i++) {
  47126. var def = view.def.nodes[i];
  47127. if (def.flags & 1 /* TypeElement */) {
  47128. view.renderer.destroyNode(asElementData(view, i).renderElement);
  47129. }
  47130. else if (def.flags & 2 /* TypeText */) {
  47131. view.renderer.destroyNode(asTextData(view, i).renderText);
  47132. }
  47133. else if (def.flags & 67108864 /* TypeContentQuery */ || def.flags & 134217728 /* TypeViewQuery */) {
  47134. asQueryList(view, i).destroy();
  47135. }
  47136. }
  47137. }
  47138. var ViewAction;
  47139. (function (ViewAction) {
  47140. ViewAction[ViewAction["CreateViewNodes"] = 0] = "CreateViewNodes";
  47141. ViewAction[ViewAction["CheckNoChanges"] = 1] = "CheckNoChanges";
  47142. ViewAction[ViewAction["CheckNoChangesProjectedViews"] = 2] = "CheckNoChangesProjectedViews";
  47143. ViewAction[ViewAction["CheckAndUpdate"] = 3] = "CheckAndUpdate";
  47144. ViewAction[ViewAction["CheckAndUpdateProjectedViews"] = 4] = "CheckAndUpdateProjectedViews";
  47145. ViewAction[ViewAction["Destroy"] = 5] = "Destroy";
  47146. })(ViewAction || (ViewAction = {}));
  47147. function execComponentViewsAction(view, action) {
  47148. var def = view.def;
  47149. if (!(def.nodeFlags & 33554432 /* ComponentView */)) {
  47150. return;
  47151. }
  47152. for (var i = 0; i < def.nodes.length; i++) {
  47153. var nodeDef = def.nodes[i];
  47154. if (nodeDef.flags & 33554432 /* ComponentView */) {
  47155. // a leaf
  47156. callViewAction(asElementData(view, i).componentView, action);
  47157. }
  47158. else if ((nodeDef.childFlags & 33554432 /* ComponentView */) === 0) {
  47159. // a parent with leafs
  47160. // no child is a component,
  47161. // then skip the children
  47162. i += nodeDef.childCount;
  47163. }
  47164. }
  47165. }
  47166. function execEmbeddedViewsAction(view, action) {
  47167. var def = view.def;
  47168. if (!(def.nodeFlags & 16777216 /* EmbeddedViews */)) {
  47169. return;
  47170. }
  47171. for (var i = 0; i < def.nodes.length; i++) {
  47172. var nodeDef = def.nodes[i];
  47173. if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
  47174. // a leaf
  47175. var embeddedViews = asElementData(view, i).viewContainer._embeddedViews;
  47176. for (var k = 0; k < embeddedViews.length; k++) {
  47177. callViewAction(embeddedViews[k], action);
  47178. }
  47179. }
  47180. else if ((nodeDef.childFlags & 16777216 /* EmbeddedViews */) === 0) {
  47181. // a parent with leafs
  47182. // no child is a component,
  47183. // then skip the children
  47184. i += nodeDef.childCount;
  47185. }
  47186. }
  47187. }
  47188. function callViewAction(view, action) {
  47189. var viewState = view.state;
  47190. switch (action) {
  47191. case ViewAction.CheckNoChanges:
  47192. if ((viewState & 128 /* Destroyed */) === 0) {
  47193. if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */) {
  47194. checkNoChangesView(view);
  47195. }
  47196. else if (viewState & 64 /* CheckProjectedViews */) {
  47197. execProjectedViewsAction(view, ViewAction.CheckNoChangesProjectedViews);
  47198. }
  47199. }
  47200. break;
  47201. case ViewAction.CheckNoChangesProjectedViews:
  47202. if ((viewState & 128 /* Destroyed */) === 0) {
  47203. if (viewState & 32 /* CheckProjectedView */) {
  47204. checkNoChangesView(view);
  47205. }
  47206. else if (viewState & 64 /* CheckProjectedViews */) {
  47207. execProjectedViewsAction(view, action);
  47208. }
  47209. }
  47210. break;
  47211. case ViewAction.CheckAndUpdate:
  47212. if ((viewState & 128 /* Destroyed */) === 0) {
  47213. if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */) {
  47214. checkAndUpdateView(view);
  47215. }
  47216. else if (viewState & 64 /* CheckProjectedViews */) {
  47217. execProjectedViewsAction(view, ViewAction.CheckAndUpdateProjectedViews);
  47218. }
  47219. }
  47220. break;
  47221. case ViewAction.CheckAndUpdateProjectedViews:
  47222. if ((viewState & 128 /* Destroyed */) === 0) {
  47223. if (viewState & 32 /* CheckProjectedView */) {
  47224. checkAndUpdateView(view);
  47225. }
  47226. else if (viewState & 64 /* CheckProjectedViews */) {
  47227. execProjectedViewsAction(view, action);
  47228. }
  47229. }
  47230. break;
  47231. case ViewAction.Destroy:
  47232. // Note: destroyView recurses over all views,
  47233. // so we don't need to special case projected views here.
  47234. destroyView(view);
  47235. break;
  47236. case ViewAction.CreateViewNodes:
  47237. createViewNodes(view);
  47238. break;
  47239. }
  47240. }
  47241. function execProjectedViewsAction(view, action) {
  47242. execEmbeddedViewsAction(view, action);
  47243. execComponentViewsAction(view, action);
  47244. }
  47245. function execQueriesAction(view, queryFlags, staticDynamicQueryFlag, checkType) {
  47246. if (!(view.def.nodeFlags & queryFlags) || !(view.def.nodeFlags & staticDynamicQueryFlag)) {
  47247. return;
  47248. }
  47249. var nodeCount = view.def.nodes.length;
  47250. for (var i = 0; i < nodeCount; i++) {
  47251. var nodeDef = view.def.nodes[i];
  47252. if ((nodeDef.flags & queryFlags) && (nodeDef.flags & staticDynamicQueryFlag)) {
  47253. Services.setCurrentNode(view, nodeDef.nodeIndex);
  47254. switch (checkType) {
  47255. case 0 /* CheckAndUpdate */:
  47256. checkAndUpdateQuery(view, nodeDef);
  47257. break;
  47258. case 1 /* CheckNoChanges */:
  47259. checkNoChangesQuery(view, nodeDef);
  47260. break;
  47261. }
  47262. }
  47263. if (!(nodeDef.childFlags & queryFlags) || !(nodeDef.childFlags & staticDynamicQueryFlag)) {
  47264. // no child has a matching query
  47265. // then skip the children
  47266. i += nodeDef.childCount;
  47267. }
  47268. }
  47269. }
  47270. /**
  47271. * @license
  47272. * Copyright Google Inc. All Rights Reserved.
  47273. *
  47274. * Use of this source code is governed by an MIT-style license that can be
  47275. * found in the LICENSE file at https://angular.io/license
  47276. */
  47277. var initialized = false;
  47278. function initServicesIfNeeded() {
  47279. if (initialized) {
  47280. return;
  47281. }
  47282. initialized = true;
  47283. var services = isDevMode() ? createDebugServices() : createProdServices();
  47284. Services.setCurrentNode = services.setCurrentNode;
  47285. Services.createRootView = services.createRootView;
  47286. Services.createEmbeddedView = services.createEmbeddedView;
  47287. Services.createComponentView = services.createComponentView;
  47288. Services.createNgModuleRef = services.createNgModuleRef;
  47289. Services.overrideProvider = services.overrideProvider;
  47290. Services.overrideComponentView = services.overrideComponentView;
  47291. Services.clearOverrides = services.clearOverrides;
  47292. Services.checkAndUpdateView = services.checkAndUpdateView;
  47293. Services.checkNoChangesView = services.checkNoChangesView;
  47294. Services.destroyView = services.destroyView;
  47295. Services.resolveDep = resolveDep;
  47296. Services.createDebugContext = services.createDebugContext;
  47297. Services.handleEvent = services.handleEvent;
  47298. Services.updateDirectives = services.updateDirectives;
  47299. Services.updateRenderer = services.updateRenderer;
  47300. Services.dirtyParentQueries = dirtyParentQueries;
  47301. }
  47302. function createProdServices() {
  47303. return {
  47304. setCurrentNode: function () { },
  47305. createRootView: createProdRootView,
  47306. createEmbeddedView: createEmbeddedView,
  47307. createComponentView: createComponentView,
  47308. createNgModuleRef: createNgModuleRef,
  47309. overrideProvider: NOOP,
  47310. overrideComponentView: NOOP,
  47311. clearOverrides: NOOP,
  47312. checkAndUpdateView: checkAndUpdateView,
  47313. checkNoChangesView: checkNoChangesView,
  47314. destroyView: destroyView,
  47315. createDebugContext: function (view, nodeIndex) { return new DebugContext_(view, nodeIndex); },
  47316. handleEvent: function (view, nodeIndex, eventName, event) {
  47317. return view.def.handleEvent(view, nodeIndex, eventName, event);
  47318. },
  47319. updateDirectives: function (view, checkType) { return view.def.updateDirectives(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode :
  47320. prodCheckNoChangesNode, view); },
  47321. updateRenderer: function (view, checkType) { return view.def.updateRenderer(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode :
  47322. prodCheckNoChangesNode, view); },
  47323. };
  47324. }
  47325. function createDebugServices() {
  47326. return {
  47327. setCurrentNode: debugSetCurrentNode,
  47328. createRootView: debugCreateRootView,
  47329. createEmbeddedView: debugCreateEmbeddedView,
  47330. createComponentView: debugCreateComponentView,
  47331. createNgModuleRef: debugCreateNgModuleRef,
  47332. overrideProvider: debugOverrideProvider,
  47333. overrideComponentView: debugOverrideComponentView,
  47334. clearOverrides: debugClearOverrides,
  47335. checkAndUpdateView: debugCheckAndUpdateView,
  47336. checkNoChangesView: debugCheckNoChangesView,
  47337. destroyView: debugDestroyView,
  47338. createDebugContext: function (view, nodeIndex) { return new DebugContext_(view, nodeIndex); },
  47339. handleEvent: debugHandleEvent,
  47340. updateDirectives: debugUpdateDirectives,
  47341. updateRenderer: debugUpdateRenderer,
  47342. };
  47343. }
  47344. function createProdRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
  47345. var rendererFactory = ngModule.injector.get(RendererFactory2);
  47346. return createRootView(createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode), def, context);
  47347. }
  47348. function debugCreateRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
  47349. var rendererFactory = ngModule.injector.get(RendererFactory2);
  47350. var root = createRootData(elInjector, ngModule, new DebugRendererFactory2(rendererFactory), projectableNodes, rootSelectorOrNode);
  47351. var defWithOverride = applyProviderOverridesToView(def);
  47352. return callWithDebugContext(DebugAction.create, createRootView, null, [root, defWithOverride, context]);
  47353. }
  47354. function createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode) {
  47355. var sanitizer = ngModule.injector.get(Sanitizer);
  47356. var errorHandler = ngModule.injector.get(ErrorHandler);
  47357. var renderer = rendererFactory.createRenderer(null, null);
  47358. return {
  47359. ngModule: ngModule,
  47360. injector: elInjector, projectableNodes: projectableNodes,
  47361. selectorOrNode: rootSelectorOrNode, sanitizer: sanitizer, rendererFactory: rendererFactory, renderer: renderer, errorHandler: errorHandler
  47362. };
  47363. }
  47364. function debugCreateEmbeddedView(parentView, anchorDef, viewDef, context) {
  47365. var defWithOverride = applyProviderOverridesToView(viewDef);
  47366. return callWithDebugContext(DebugAction.create, createEmbeddedView, null, [parentView, anchorDef, defWithOverride, context]);
  47367. }
  47368. function debugCreateComponentView(parentView, nodeDef, viewDef, hostElement) {
  47369. var overrideComponentView = viewDefOverrides.get(nodeDef.element.componentProvider.provider.token);
  47370. if (overrideComponentView) {
  47371. viewDef = overrideComponentView;
  47372. }
  47373. else {
  47374. viewDef = applyProviderOverridesToView(viewDef);
  47375. }
  47376. return callWithDebugContext(DebugAction.create, createComponentView, null, [parentView, nodeDef, viewDef, hostElement]);
  47377. }
  47378. function debugCreateNgModuleRef(moduleType, parentInjector, bootstrapComponents, def) {
  47379. var defWithOverride = applyProviderOverridesToNgModule(def);
  47380. return createNgModuleRef(moduleType, parentInjector, bootstrapComponents, defWithOverride);
  47381. }
  47382. var providerOverrides = new Map();
  47383. var providerOverridesWithScope = new Map();
  47384. var viewDefOverrides = new Map();
  47385. function debugOverrideProvider(override) {
  47386. providerOverrides.set(override.token, override);
  47387. var injectableDef;
  47388. if (typeof override.token === 'function' && (injectableDef = getInjectableDef(override.token)) &&
  47389. typeof injectableDef.providedIn === 'function') {
  47390. providerOverridesWithScope.set(override.token, override);
  47391. }
  47392. }
  47393. function debugOverrideComponentView(comp, compFactory) {
  47394. var hostViewDef = resolveDefinition(getComponentViewDefinitionFactory(compFactory));
  47395. var compViewDef = resolveDefinition(hostViewDef.nodes[0].element.componentView);
  47396. viewDefOverrides.set(comp, compViewDef);
  47397. }
  47398. function debugClearOverrides() {
  47399. providerOverrides.clear();
  47400. providerOverridesWithScope.clear();
  47401. viewDefOverrides.clear();
  47402. }
  47403. // Notes about the algorithm:
  47404. // 1) Locate the providers of an element and check if one of them was overwritten
  47405. // 2) Change the providers of that element
  47406. //
  47407. // We only create new datastructures if we need to, to keep perf impact
  47408. // reasonable.
  47409. function applyProviderOverridesToView(def) {
  47410. if (providerOverrides.size === 0) {
  47411. return def;
  47412. }
  47413. var elementIndicesWithOverwrittenProviders = findElementIndicesWithOverwrittenProviders(def);
  47414. if (elementIndicesWithOverwrittenProviders.length === 0) {
  47415. return def;
  47416. }
  47417. // clone the whole view definition,
  47418. // as it maintains references between the nodes that are hard to update.
  47419. def = def.factory(function () { return NOOP; });
  47420. for (var i = 0; i < elementIndicesWithOverwrittenProviders.length; i++) {
  47421. applyProviderOverridesToElement(def, elementIndicesWithOverwrittenProviders[i]);
  47422. }
  47423. return def;
  47424. function findElementIndicesWithOverwrittenProviders(def) {
  47425. var elIndicesWithOverwrittenProviders = [];
  47426. var lastElementDef = null;
  47427. for (var i = 0; i < def.nodes.length; i++) {
  47428. var nodeDef = def.nodes[i];
  47429. if (nodeDef.flags & 1 /* TypeElement */) {
  47430. lastElementDef = nodeDef;
  47431. }
  47432. if (lastElementDef && nodeDef.flags & 3840 /* CatProviderNoDirective */ &&
  47433. providerOverrides.has(nodeDef.provider.token)) {
  47434. elIndicesWithOverwrittenProviders.push(lastElementDef.nodeIndex);
  47435. lastElementDef = null;
  47436. }
  47437. }
  47438. return elIndicesWithOverwrittenProviders;
  47439. }
  47440. function applyProviderOverridesToElement(viewDef, elIndex) {
  47441. for (var i = elIndex + 1; i < viewDef.nodes.length; i++) {
  47442. var nodeDef = viewDef.nodes[i];
  47443. if (nodeDef.flags & 1 /* TypeElement */) {
  47444. // stop at the next element
  47445. return;
  47446. }
  47447. if (nodeDef.flags & 3840 /* CatProviderNoDirective */) {
  47448. var provider = nodeDef.provider;
  47449. var override = providerOverrides.get(provider.token);
  47450. if (override) {
  47451. nodeDef.flags = (nodeDef.flags & ~3840 /* CatProviderNoDirective */) | override.flags;
  47452. provider.deps = splitDepsDsl(override.deps);
  47453. provider.value = override.value;
  47454. }
  47455. }
  47456. }
  47457. }
  47458. }
  47459. // Notes about the algorithm:
  47460. // We only create new datastructures if we need to, to keep perf impact
  47461. // reasonable.
  47462. function applyProviderOverridesToNgModule(def) {
  47463. var _a = calcHasOverrides(def), hasOverrides = _a.hasOverrides, hasDeprecatedOverrides = _a.hasDeprecatedOverrides;
  47464. if (!hasOverrides) {
  47465. return def;
  47466. }
  47467. // clone the whole view definition,
  47468. // as it maintains references between the nodes that are hard to update.
  47469. def = def.factory(function () { return NOOP; });
  47470. applyProviderOverrides(def);
  47471. return def;
  47472. function calcHasOverrides(def) {
  47473. var hasOverrides = false;
  47474. var hasDeprecatedOverrides = false;
  47475. if (providerOverrides.size === 0) {
  47476. return { hasOverrides: hasOverrides, hasDeprecatedOverrides: hasDeprecatedOverrides };
  47477. }
  47478. def.providers.forEach(function (node) {
  47479. var override = providerOverrides.get(node.token);
  47480. if ((node.flags & 3840 /* CatProviderNoDirective */) && override) {
  47481. hasOverrides = true;
  47482. hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior;
  47483. }
  47484. });
  47485. def.modules.forEach(function (module) {
  47486. providerOverridesWithScope.forEach(function (override, token) {
  47487. if (getInjectableDef(token).providedIn === module) {
  47488. hasOverrides = true;
  47489. hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior;
  47490. }
  47491. });
  47492. });
  47493. return { hasOverrides: hasOverrides, hasDeprecatedOverrides: hasDeprecatedOverrides };
  47494. }
  47495. function applyProviderOverrides(def) {
  47496. for (var i = 0; i < def.providers.length; i++) {
  47497. var provider = def.providers[i];
  47498. if (hasDeprecatedOverrides) {
  47499. // We had a bug where me made
  47500. // all providers lazy. Keep this logic behind a flag
  47501. // for migrating existing users.
  47502. provider.flags |= 4096 /* LazyProvider */;
  47503. }
  47504. var override = providerOverrides.get(provider.token);
  47505. if (override) {
  47506. provider.flags = (provider.flags & ~3840 /* CatProviderNoDirective */) | override.flags;
  47507. provider.deps = splitDepsDsl(override.deps);
  47508. provider.value = override.value;
  47509. }
  47510. }
  47511. if (providerOverridesWithScope.size > 0) {
  47512. var moduleSet_1 = new Set(def.modules);
  47513. providerOverridesWithScope.forEach(function (override, token) {
  47514. if (moduleSet_1.has(getInjectableDef(token).providedIn)) {
  47515. var provider = {
  47516. token: token,
  47517. flags: override.flags | (hasDeprecatedOverrides ? 4096 /* LazyProvider */ : 0 /* None */),
  47518. deps: splitDepsDsl(override.deps),
  47519. value: override.value,
  47520. index: def.providers.length,
  47521. };
  47522. def.providers.push(provider);
  47523. def.providersByKey[tokenKey(token)] = provider;
  47524. }
  47525. });
  47526. }
  47527. }
  47528. }
  47529. function prodCheckAndUpdateNode(view, checkIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  47530. var nodeDef = view.def.nodes[checkIndex];
  47531. checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47532. return (nodeDef.flags & 224 /* CatPureExpression */) ?
  47533. asPureExpressionData(view, checkIndex).value :
  47534. undefined;
  47535. }
  47536. function prodCheckNoChangesNode(view, checkIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
  47537. var nodeDef = view.def.nodes[checkIndex];
  47538. checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
  47539. return (nodeDef.flags & 224 /* CatPureExpression */) ?
  47540. asPureExpressionData(view, checkIndex).value :
  47541. undefined;
  47542. }
  47543. function debugCheckAndUpdateView(view) {
  47544. return callWithDebugContext(DebugAction.detectChanges, checkAndUpdateView, null, [view]);
  47545. }
  47546. function debugCheckNoChangesView(view) {
  47547. return callWithDebugContext(DebugAction.checkNoChanges, checkNoChangesView, null, [view]);
  47548. }
  47549. function debugDestroyView(view) {
  47550. return callWithDebugContext(DebugAction.destroy, destroyView, null, [view]);
  47551. }
  47552. var DebugAction;
  47553. (function (DebugAction) {
  47554. DebugAction[DebugAction["create"] = 0] = "create";
  47555. DebugAction[DebugAction["detectChanges"] = 1] = "detectChanges";
  47556. DebugAction[DebugAction["checkNoChanges"] = 2] = "checkNoChanges";
  47557. DebugAction[DebugAction["destroy"] = 3] = "destroy";
  47558. DebugAction[DebugAction["handleEvent"] = 4] = "handleEvent";
  47559. })(DebugAction || (DebugAction = {}));
  47560. var _currentAction;
  47561. var _currentView;
  47562. var _currentNodeIndex;
  47563. function debugSetCurrentNode(view, nodeIndex) {
  47564. _currentView = view;
  47565. _currentNodeIndex = nodeIndex;
  47566. }
  47567. function debugHandleEvent(view, nodeIndex, eventName, event) {
  47568. debugSetCurrentNode(view, nodeIndex);
  47569. return callWithDebugContext(DebugAction.handleEvent, view.def.handleEvent, null, [view, nodeIndex, eventName, event]);
  47570. }
  47571. function debugUpdateDirectives(view, checkType) {
  47572. if (view.state & 128 /* Destroyed */) {
  47573. throw viewDestroyedError(DebugAction[_currentAction]);
  47574. }
  47575. debugSetCurrentNode(view, nextDirectiveWithBinding(view, 0));
  47576. return view.def.updateDirectives(debugCheckDirectivesFn, view);
  47577. function debugCheckDirectivesFn(view, nodeIndex, argStyle) {
  47578. var values = [];
  47579. for (var _i = 3; _i < arguments.length; _i++) {
  47580. values[_i - 3] = arguments[_i];
  47581. }
  47582. var nodeDef = view.def.nodes[nodeIndex];
  47583. if (checkType === 0 /* CheckAndUpdate */) {
  47584. debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
  47585. }
  47586. else {
  47587. debugCheckNoChangesNode(view, nodeDef, argStyle, values);
  47588. }
  47589. if (nodeDef.flags & 16384 /* TypeDirective */) {
  47590. debugSetCurrentNode(view, nextDirectiveWithBinding(view, nodeIndex));
  47591. }
  47592. return (nodeDef.flags & 224 /* CatPureExpression */) ?
  47593. asPureExpressionData(view, nodeDef.nodeIndex).value :
  47594. undefined;
  47595. }
  47596. }
  47597. function debugUpdateRenderer(view, checkType) {
  47598. if (view.state & 128 /* Destroyed */) {
  47599. throw viewDestroyedError(DebugAction[_currentAction]);
  47600. }
  47601. debugSetCurrentNode(view, nextRenderNodeWithBinding(view, 0));
  47602. return view.def.updateRenderer(debugCheckRenderNodeFn, view);
  47603. function debugCheckRenderNodeFn(view, nodeIndex, argStyle) {
  47604. var values = [];
  47605. for (var _i = 3; _i < arguments.length; _i++) {
  47606. values[_i - 3] = arguments[_i];
  47607. }
  47608. var nodeDef = view.def.nodes[nodeIndex];
  47609. if (checkType === 0 /* CheckAndUpdate */) {
  47610. debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
  47611. }
  47612. else {
  47613. debugCheckNoChangesNode(view, nodeDef, argStyle, values);
  47614. }
  47615. if (nodeDef.flags & 3 /* CatRenderNode */) {
  47616. debugSetCurrentNode(view, nextRenderNodeWithBinding(view, nodeIndex));
  47617. }
  47618. return (nodeDef.flags & 224 /* CatPureExpression */) ?
  47619. asPureExpressionData(view, nodeDef.nodeIndex).value :
  47620. undefined;
  47621. }
  47622. }
  47623. function debugCheckAndUpdateNode(view, nodeDef, argStyle, givenValues) {
  47624. var changed = checkAndUpdateNode.apply(void 0, __spread([view, nodeDef, argStyle], givenValues));
  47625. if (changed) {
  47626. var values = argStyle === 1 /* Dynamic */ ? givenValues[0] : givenValues;
  47627. if (nodeDef.flags & 16384 /* TypeDirective */) {
  47628. var bindingValues = {};
  47629. for (var i = 0; i < nodeDef.bindings.length; i++) {
  47630. var binding = nodeDef.bindings[i];
  47631. var value = values[i];
  47632. if (binding.flags & 8 /* TypeProperty */) {
  47633. bindingValues[normalizeDebugBindingName(binding.nonMinifiedName)] =
  47634. normalizeDebugBindingValue(value);
  47635. }
  47636. }
  47637. var elDef = nodeDef.parent;
  47638. var el = asElementData(view, elDef.nodeIndex).renderElement;
  47639. if (!elDef.element.name) {
  47640. // a comment.
  47641. view.renderer.setValue(el, "bindings=" + JSON.stringify(bindingValues, null, 2));
  47642. }
  47643. else {
  47644. // a regular element.
  47645. for (var attr in bindingValues) {
  47646. var value = bindingValues[attr];
  47647. if (value != null) {
  47648. view.renderer.setAttribute(el, attr, value);
  47649. }
  47650. else {
  47651. view.renderer.removeAttribute(el, attr);
  47652. }
  47653. }
  47654. }
  47655. }
  47656. }
  47657. }
  47658. function debugCheckNoChangesNode(view, nodeDef, argStyle, values) {
  47659. checkNoChangesNode.apply(void 0, __spread([view, nodeDef, argStyle], values));
  47660. }
  47661. function nextDirectiveWithBinding(view, nodeIndex) {
  47662. for (var i = nodeIndex; i < view.def.nodes.length; i++) {
  47663. var nodeDef = view.def.nodes[i];
  47664. if (nodeDef.flags & 16384 /* TypeDirective */ && nodeDef.bindings && nodeDef.bindings.length) {
  47665. return i;
  47666. }
  47667. }
  47668. return null;
  47669. }
  47670. function nextRenderNodeWithBinding(view, nodeIndex) {
  47671. for (var i = nodeIndex; i < view.def.nodes.length; i++) {
  47672. var nodeDef = view.def.nodes[i];
  47673. if ((nodeDef.flags & 3 /* CatRenderNode */) && nodeDef.bindings && nodeDef.bindings.length) {
  47674. return i;
  47675. }
  47676. }
  47677. return null;
  47678. }
  47679. var DebugContext_ = /** @class */ (function () {
  47680. function DebugContext_(view, nodeIndex) {
  47681. this.view = view;
  47682. this.nodeIndex = nodeIndex;
  47683. if (nodeIndex == null) {
  47684. this.nodeIndex = nodeIndex = 0;
  47685. }
  47686. this.nodeDef = view.def.nodes[nodeIndex];
  47687. var elDef = this.nodeDef;
  47688. var elView = view;
  47689. while (elDef && (elDef.flags & 1 /* TypeElement */) === 0) {
  47690. elDef = elDef.parent;
  47691. }
  47692. if (!elDef) {
  47693. while (!elDef && elView) {
  47694. elDef = viewParentEl(elView);
  47695. elView = elView.parent;
  47696. }
  47697. }
  47698. this.elDef = elDef;
  47699. this.elView = elView;
  47700. }
  47701. Object.defineProperty(DebugContext_.prototype, "elOrCompView", {
  47702. get: function () {
  47703. // Has to be done lazily as we use the DebugContext also during creation of elements...
  47704. return asElementData(this.elView, this.elDef.nodeIndex).componentView || this.view;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(DebugContext_.prototype, "injector", {
  47710. get: function () { return createInjector$1(this.elView, this.elDef); },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(DebugContext_.prototype, "component", {
  47715. get: function () { return this.elOrCompView.component; },
  47716. enumerable: true,
  47717. configurable: true
  47718. });
  47719. Object.defineProperty(DebugContext_.prototype, "context", {
  47720. get: function () { return this.elOrCompView.context; },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(DebugContext_.prototype, "providerTokens", {
  47725. get: function () {
  47726. var tokens = [];
  47727. if (this.elDef) {
  47728. for (var i = this.elDef.nodeIndex + 1; i <= this.elDef.nodeIndex + this.elDef.childCount; i++) {
  47729. var childDef = this.elView.def.nodes[i];
  47730. if (childDef.flags & 20224 /* CatProvider */) {
  47731. tokens.push(childDef.provider.token);
  47732. }
  47733. i += childDef.childCount;
  47734. }
  47735. }
  47736. return tokens;
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(DebugContext_.prototype, "references", {
  47742. get: function () {
  47743. var references = {};
  47744. if (this.elDef) {
  47745. collectReferences(this.elView, this.elDef, references);
  47746. for (var i = this.elDef.nodeIndex + 1; i <= this.elDef.nodeIndex + this.elDef.childCount; i++) {
  47747. var childDef = this.elView.def.nodes[i];
  47748. if (childDef.flags & 20224 /* CatProvider */) {
  47749. collectReferences(this.elView, childDef, references);
  47750. }
  47751. i += childDef.childCount;
  47752. }
  47753. }
  47754. return references;
  47755. },
  47756. enumerable: true,
  47757. configurable: true
  47758. });
  47759. Object.defineProperty(DebugContext_.prototype, "componentRenderElement", {
  47760. get: function () {
  47761. var elData = findHostElement(this.elOrCompView);
  47762. return elData ? elData.renderElement : undefined;
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(DebugContext_.prototype, "renderNode", {
  47768. get: function () {
  47769. return this.nodeDef.flags & 2 /* TypeText */ ? renderNode(this.view, this.nodeDef) :
  47770. renderNode(this.elView, this.elDef);
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. DebugContext_.prototype.logError = function (console) {
  47776. var values = [];
  47777. for (var _i = 1; _i < arguments.length; _i++) {
  47778. values[_i - 1] = arguments[_i];
  47779. }
  47780. var logViewDef;
  47781. var logNodeIndex;
  47782. if (this.nodeDef.flags & 2 /* TypeText */) {
  47783. logViewDef = this.view.def;
  47784. logNodeIndex = this.nodeDef.nodeIndex;
  47785. }
  47786. else {
  47787. logViewDef = this.elView.def;
  47788. logNodeIndex = this.elDef.nodeIndex;
  47789. }
  47790. // Note: we only generate a log function for text and element nodes
  47791. // to make the generated code as small as possible.
  47792. var renderNodeIndex = getRenderNodeIndex(logViewDef, logNodeIndex);
  47793. var currRenderNodeIndex = -1;
  47794. var nodeLogger = function () {
  47795. var _a;
  47796. currRenderNodeIndex++;
  47797. if (currRenderNodeIndex === renderNodeIndex) {
  47798. return (_a = console.error).bind.apply(_a, __spread([console], values));
  47799. }
  47800. else {
  47801. return NOOP;
  47802. }
  47803. };
  47804. logViewDef.factory(nodeLogger);
  47805. if (currRenderNodeIndex < renderNodeIndex) {
  47806. console.error('Illegal state: the ViewDefinitionFactory did not call the logger!');
  47807. console.error.apply(console, __spread(values));
  47808. }
  47809. };
  47810. return DebugContext_;
  47811. }());
  47812. function getRenderNodeIndex(viewDef, nodeIndex) {
  47813. var renderNodeIndex = -1;
  47814. for (var i = 0; i <= nodeIndex; i++) {
  47815. var nodeDef = viewDef.nodes[i];
  47816. if (nodeDef.flags & 3 /* CatRenderNode */) {
  47817. renderNodeIndex++;
  47818. }
  47819. }
  47820. return renderNodeIndex;
  47821. }
  47822. function findHostElement(view) {
  47823. while (view && !isComponentView(view)) {
  47824. view = view.parent;
  47825. }
  47826. if (view.parent) {
  47827. return asElementData(view.parent, viewParentEl(view).nodeIndex);
  47828. }
  47829. return null;
  47830. }
  47831. function collectReferences(view, nodeDef, references) {
  47832. for (var refName in nodeDef.references) {
  47833. references[refName] = getQueryValue(view, nodeDef, nodeDef.references[refName]);
  47834. }
  47835. }
  47836. function callWithDebugContext(action, fn, self, args) {
  47837. var oldAction = _currentAction;
  47838. var oldView = _currentView;
  47839. var oldNodeIndex = _currentNodeIndex;
  47840. try {
  47841. _currentAction = action;
  47842. var result = fn.apply(self, args);
  47843. _currentView = oldView;
  47844. _currentNodeIndex = oldNodeIndex;
  47845. _currentAction = oldAction;
  47846. return result;
  47847. }
  47848. catch (e) {
  47849. if (isViewDebugError(e) || !_currentView) {
  47850. throw e;
  47851. }
  47852. throw viewWrappedDebugError(e, getCurrentDebugContext());
  47853. }
  47854. }
  47855. function getCurrentDebugContext() {
  47856. return _currentView ? new DebugContext_(_currentView, _currentNodeIndex) : null;
  47857. }
  47858. var DebugRendererFactory2 = /** @class */ (function () {
  47859. function DebugRendererFactory2(delegate) {
  47860. this.delegate = delegate;
  47861. }
  47862. DebugRendererFactory2.prototype.createRenderer = function (element, renderData) {
  47863. return new DebugRenderer2(this.delegate.createRenderer(element, renderData));
  47864. };
  47865. DebugRendererFactory2.prototype.begin = function () {
  47866. if (this.delegate.begin) {
  47867. this.delegate.begin();
  47868. }
  47869. };
  47870. DebugRendererFactory2.prototype.end = function () {
  47871. if (this.delegate.end) {
  47872. this.delegate.end();
  47873. }
  47874. };
  47875. DebugRendererFactory2.prototype.whenRenderingDone = function () {
  47876. if (this.delegate.whenRenderingDone) {
  47877. return this.delegate.whenRenderingDone();
  47878. }
  47879. return Promise.resolve(null);
  47880. };
  47881. return DebugRendererFactory2;
  47882. }());
  47883. var DebugRenderer2 = /** @class */ (function () {
  47884. function DebugRenderer2(delegate) {
  47885. this.delegate = delegate;
  47886. /**
  47887. * Factory function used to create a `DebugContext` when a node is created.
  47888. *
  47889. * The `DebugContext` allows to retrieve information about the nodes that are useful in tests.
  47890. *
  47891. * The factory is configurable so that the `DebugRenderer2` could instantiate either a View Engine
  47892. * or a Render context.
  47893. */
  47894. this.debugContextFactory = getCurrentDebugContext;
  47895. this.data = this.delegate.data;
  47896. }
  47897. DebugRenderer2.prototype.createDebugContext = function (nativeElement) { return this.debugContextFactory(nativeElement); };
  47898. DebugRenderer2.prototype.destroyNode = function (node) {
  47899. removeDebugNodeFromIndex(getDebugNode(node));
  47900. if (this.delegate.destroyNode) {
  47901. this.delegate.destroyNode(node);
  47902. }
  47903. };
  47904. DebugRenderer2.prototype.destroy = function () { this.delegate.destroy(); };
  47905. DebugRenderer2.prototype.createElement = function (name, namespace) {
  47906. var el = this.delegate.createElement(name, namespace);
  47907. var debugCtx = this.createDebugContext(el);
  47908. if (debugCtx) {
  47909. var debugEl = new DebugElement__PRE_R3__(el, null, debugCtx);
  47910. debugEl.name = name;
  47911. indexDebugNode(debugEl);
  47912. }
  47913. return el;
  47914. };
  47915. DebugRenderer2.prototype.createComment = function (value) {
  47916. var comment = this.delegate.createComment(value);
  47917. var debugCtx = this.createDebugContext(comment);
  47918. if (debugCtx) {
  47919. indexDebugNode(new DebugNode__PRE_R3__(comment, null, debugCtx));
  47920. }
  47921. return comment;
  47922. };
  47923. DebugRenderer2.prototype.createText = function (value) {
  47924. var text = this.delegate.createText(value);
  47925. var debugCtx = this.createDebugContext(text);
  47926. if (debugCtx) {
  47927. indexDebugNode(new DebugNode__PRE_R3__(text, null, debugCtx));
  47928. }
  47929. return text;
  47930. };
  47931. DebugRenderer2.prototype.appendChild = function (parent, newChild) {
  47932. var debugEl = getDebugNode(parent);
  47933. var debugChildEl = getDebugNode(newChild);
  47934. if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
  47935. debugEl.addChild(debugChildEl);
  47936. }
  47937. this.delegate.appendChild(parent, newChild);
  47938. };
  47939. DebugRenderer2.prototype.insertBefore = function (parent, newChild, refChild) {
  47940. var debugEl = getDebugNode(parent);
  47941. var debugChildEl = getDebugNode(newChild);
  47942. var debugRefEl = getDebugNode(refChild);
  47943. if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
  47944. debugEl.insertBefore(debugRefEl, debugChildEl);
  47945. }
  47946. this.delegate.insertBefore(parent, newChild, refChild);
  47947. };
  47948. DebugRenderer2.prototype.removeChild = function (parent, oldChild) {
  47949. var debugEl = getDebugNode(parent);
  47950. var debugChildEl = getDebugNode(oldChild);
  47951. if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
  47952. debugEl.removeChild(debugChildEl);
  47953. }
  47954. this.delegate.removeChild(parent, oldChild);
  47955. };
  47956. DebugRenderer2.prototype.selectRootElement = function (selectorOrNode, preserveContent) {
  47957. var el = this.delegate.selectRootElement(selectorOrNode, preserveContent);
  47958. var debugCtx = getCurrentDebugContext();
  47959. if (debugCtx) {
  47960. indexDebugNode(new DebugElement__PRE_R3__(el, null, debugCtx));
  47961. }
  47962. return el;
  47963. };
  47964. DebugRenderer2.prototype.setAttribute = function (el, name, value, namespace) {
  47965. var debugEl = getDebugNode(el);
  47966. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  47967. var fullName = namespace ? namespace + ':' + name : name;
  47968. debugEl.attributes[fullName] = value;
  47969. }
  47970. this.delegate.setAttribute(el, name, value, namespace);
  47971. };
  47972. DebugRenderer2.prototype.removeAttribute = function (el, name, namespace) {
  47973. var debugEl = getDebugNode(el);
  47974. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  47975. var fullName = namespace ? namespace + ':' + name : name;
  47976. debugEl.attributes[fullName] = null;
  47977. }
  47978. this.delegate.removeAttribute(el, name, namespace);
  47979. };
  47980. DebugRenderer2.prototype.addClass = function (el, name) {
  47981. var debugEl = getDebugNode(el);
  47982. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  47983. debugEl.classes[name] = true;
  47984. }
  47985. this.delegate.addClass(el, name);
  47986. };
  47987. DebugRenderer2.prototype.removeClass = function (el, name) {
  47988. var debugEl = getDebugNode(el);
  47989. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  47990. debugEl.classes[name] = false;
  47991. }
  47992. this.delegate.removeClass(el, name);
  47993. };
  47994. DebugRenderer2.prototype.setStyle = function (el, style, value, flags) {
  47995. var debugEl = getDebugNode(el);
  47996. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  47997. debugEl.styles[style] = value;
  47998. }
  47999. this.delegate.setStyle(el, style, value, flags);
  48000. };
  48001. DebugRenderer2.prototype.removeStyle = function (el, style, flags) {
  48002. var debugEl = getDebugNode(el);
  48003. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  48004. debugEl.styles[style] = null;
  48005. }
  48006. this.delegate.removeStyle(el, style, flags);
  48007. };
  48008. DebugRenderer2.prototype.setProperty = function (el, name, value) {
  48009. var debugEl = getDebugNode(el);
  48010. if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
  48011. debugEl.properties[name] = value;
  48012. }
  48013. this.delegate.setProperty(el, name, value);
  48014. };
  48015. DebugRenderer2.prototype.listen = function (target, eventName, callback) {
  48016. if (typeof target !== 'string') {
  48017. var debugEl = getDebugNode(target);
  48018. if (debugEl) {
  48019. debugEl.listeners.push(new DebugEventListener(eventName, callback));
  48020. }
  48021. }
  48022. return this.delegate.listen(target, eventName, callback);
  48023. };
  48024. DebugRenderer2.prototype.parentNode = function (node) { return this.delegate.parentNode(node); };
  48025. DebugRenderer2.prototype.nextSibling = function (node) { return this.delegate.nextSibling(node); };
  48026. DebugRenderer2.prototype.setValue = function (node, value) { return this.delegate.setValue(node, value); };
  48027. return DebugRenderer2;
  48028. }());
  48029. /**
  48030. * @license
  48031. * Copyright Google Inc. All Rights Reserved.
  48032. *
  48033. * Use of this source code is governed by an MIT-style license that can be
  48034. * found in the LICENSE file at https://angular.io/license
  48035. */
  48036. function cloneNgModuleDefinition(def) {
  48037. var providers = Array.from(def.providers);
  48038. var modules = Array.from(def.modules);
  48039. var providersByKey = {};
  48040. for (var key in def.providersByKey) {
  48041. providersByKey[key] = def.providersByKey[key];
  48042. }
  48043. return {
  48044. factory: def.factory,
  48045. isRoot: def.isRoot, providers: providers, modules: modules, providersByKey: providersByKey,
  48046. };
  48047. }
  48048. var NgModuleFactory_ = /** @class */ (function (_super) {
  48049. __extends(NgModuleFactory_, _super);
  48050. function NgModuleFactory_(moduleType, _bootstrapComponents, _ngModuleDefFactory) {
  48051. var _this =
  48052. // Attention: this ctor is called as top level function.
  48053. // Putting any logic in here will destroy closure tree shaking!
  48054. _super.call(this) || this;
  48055. _this.moduleType = moduleType;
  48056. _this._bootstrapComponents = _bootstrapComponents;
  48057. _this._ngModuleDefFactory = _ngModuleDefFactory;
  48058. return _this;
  48059. }
  48060. NgModuleFactory_.prototype.create = function (parentInjector) {
  48061. initServicesIfNeeded();
  48062. // Clone the NgModuleDefinition so that any tree shakeable provider definition
  48063. // added to this instance of the NgModuleRef doesn't affect the cached copy.
  48064. // See https://github.com/angular/angular/issues/25018.
  48065. var def = cloneNgModuleDefinition(resolveDefinition(this._ngModuleDefFactory));
  48066. return Services.createNgModuleRef(this.moduleType, parentInjector || Injector.NULL, this._bootstrapComponents, def);
  48067. };
  48068. return NgModuleFactory_;
  48069. }(NgModuleFactory));
  48070. /**
  48071. * @license
  48072. * Copyright Google Inc. All Rights Reserved.
  48073. *
  48074. * Use of this source code is governed by an MIT-style license that can be
  48075. * found in the LICENSE file at https://angular.io/license
  48076. */
  48077. /**
  48078. * @license
  48079. * Copyright Google Inc. All Rights Reserved.
  48080. *
  48081. * Use of this source code is governed by an MIT-style license that can be
  48082. * found in the LICENSE file at https://angular.io/license
  48083. */
  48084. /**
  48085. * @license
  48086. * Copyright Google Inc. All Rights Reserved.
  48087. *
  48088. * Use of this source code is governed by an MIT-style license that can be
  48089. * found in the LICENSE file at https://angular.io/license
  48090. */
  48091. // clang-format on
  48092. /**
  48093. * @license
  48094. * Copyright Google Inc. All Rights Reserved.
  48095. *
  48096. * Use of this source code is governed by an MIT-style license that can be
  48097. * found in the LICENSE file at https://angular.io/license
  48098. */
  48099. /**
  48100. * @license
  48101. * Copyright Google Inc. All Rights Reserved.
  48102. *
  48103. * Use of this source code is governed by an MIT-style license that can be
  48104. * found in the LICENSE file at https://angular.io/license
  48105. */
  48106. /**
  48107. * @license
  48108. * Copyright Google Inc. All Rights Reserved.
  48109. *
  48110. * Use of this source code is governed by an MIT-style license that can be
  48111. * found in the LICENSE file at https://angular.io/license
  48112. */
  48113. // This file only reexports content of the `src` folder. Keep it that way.
  48114. /**
  48115. * @license
  48116. * Copyright Google Inc. All Rights Reserved.
  48117. *
  48118. * Use of this source code is governed by an MIT-style license that can be
  48119. * found in the LICENSE file at https://angular.io/license
  48120. */
  48121. /**
  48122. * @license
  48123. * Copyright Google Inc. All Rights Reserved.
  48124. *
  48125. * Use of this source code is governed by an MIT-style license that can be
  48126. * found in the LICENSE file at https://angular.io/license
  48127. */
  48128. var ReflectorModuleModuleResolutionHost = /** @class */ (function () {
  48129. function ReflectorModuleModuleResolutionHost(host, getProgram) {
  48130. var _this = this;
  48131. this.host = host;
  48132. this.getProgram = getProgram;
  48133. // Note: verboseInvalidExpressions is important so that
  48134. // the collector will collect errors instead of throwing
  48135. this.metadataCollector = new MetadataCollector({ verboseInvalidExpression: true });
  48136. if (host.directoryExists)
  48137. this.directoryExists = function (directoryName) { return _this.host.directoryExists(directoryName); };
  48138. }
  48139. ReflectorModuleModuleResolutionHost.prototype.fileExists = function (fileName) { return !!this.host.getScriptSnapshot(fileName); };
  48140. ReflectorModuleModuleResolutionHost.prototype.readFile = function (fileName) {
  48141. var snapshot = this.host.getScriptSnapshot(fileName);
  48142. if (snapshot) {
  48143. return snapshot.getText(0, snapshot.getLength());
  48144. }
  48145. // Typescript readFile() declaration should be `readFile(fileName: string): string | undefined
  48146. return undefined;
  48147. };
  48148. ReflectorModuleModuleResolutionHost.prototype.getSourceFileMetadata = function (fileName) {
  48149. var sf = this.getProgram().getSourceFile(fileName);
  48150. return sf ? this.metadataCollector.getMetadata(sf) : undefined;
  48151. };
  48152. ReflectorModuleModuleResolutionHost.prototype.cacheMetadata = function (fileName) {
  48153. // Don't cache the metadata for .ts files as they might change in the editor!
  48154. return fileName.endsWith('.d.ts');
  48155. };
  48156. return ReflectorModuleModuleResolutionHost;
  48157. }());
  48158. var ReflectorHost = /** @class */ (function () {
  48159. function ReflectorHost(getProgram, serviceHost, options) {
  48160. this.options = options;
  48161. this.metadataReaderCache = createMetadataReaderCache();
  48162. this.hostAdapter = new ReflectorModuleModuleResolutionHost(serviceHost, getProgram);
  48163. }
  48164. ReflectorHost.prototype.getMetadataFor = function (modulePath) {
  48165. return readMetadata(modulePath, this.hostAdapter, this.metadataReaderCache);
  48166. };
  48167. ReflectorHost.prototype.moduleNameToFileName = function (moduleName, containingFile) {
  48168. if (!containingFile) {
  48169. if (moduleName.indexOf('.') === 0) {
  48170. throw new Error('Resolution of relative paths requires a containing file.');
  48171. }
  48172. // Any containing file gives the same result for absolute imports
  48173. containingFile = path.join(this.options.basePath, 'index.ts').replace(/\\/g, '/');
  48174. }
  48175. var resolved = ts.resolveModuleName(moduleName, containingFile, this.options, this.hostAdapter)
  48176. .resolvedModule;
  48177. return resolved ? resolved.resolvedFileName : null;
  48178. };
  48179. ReflectorHost.prototype.getOutputName = function (filePath) { return filePath; };
  48180. return ReflectorHost;
  48181. }());
  48182. /**
  48183. * @license
  48184. * Copyright Google Inc. All Rights Reserved.
  48185. *
  48186. * Use of this source code is governed by an MIT-style license that can be
  48187. * found in the LICENSE file at https://angular.io/license
  48188. */
  48189. /**
  48190. * Create a `LanguageServiceHost`
  48191. */
  48192. function createLanguageServiceFromTypescript(host, service) {
  48193. var ngHost = new TypeScriptServiceHost(host, service);
  48194. var ngServer = createLanguageService(ngHost);
  48195. return ngServer;
  48196. }
  48197. /**
  48198. * The language service never needs the normalized versions of the metadata. To avoid parsing
  48199. * the content and resolving references, return an empty file. This also allows normalizing
  48200. * template that are syntatically incorrect which is required to provide completions in
  48201. * syntactically incorrect templates.
  48202. */
  48203. var DummyHtmlParser = /** @class */ (function (_super) {
  48204. __extends(DummyHtmlParser, _super);
  48205. function DummyHtmlParser() {
  48206. return _super !== null && _super.apply(this, arguments) || this;
  48207. }
  48208. DummyHtmlParser.prototype.parse = function () { return new ParseTreeResult([], []); };
  48209. return DummyHtmlParser;
  48210. }(HtmlParser));
  48211. /**
  48212. * Avoid loading resources in the language servcie by using a dummy loader.
  48213. */
  48214. var DummyResourceLoader = /** @class */ (function (_super) {
  48215. __extends(DummyResourceLoader, _super);
  48216. function DummyResourceLoader() {
  48217. return _super !== null && _super.apply(this, arguments) || this;
  48218. }
  48219. DummyResourceLoader.prototype.get = function (url) { return Promise.resolve(''); };
  48220. return DummyResourceLoader;
  48221. }(ResourceLoader));
  48222. /**
  48223. * An implementation of a `LanguageServiceHost` for a TypeScript project.
  48224. *
  48225. * The `TypeScriptServiceHost` implements the Angular `LanguageServiceHost` using
  48226. * the TypeScript language services.
  48227. *
  48228. * @publicApi
  48229. */
  48230. var TypeScriptServiceHost = /** @class */ (function () {
  48231. function TypeScriptServiceHost(host, tsService) {
  48232. this.host = host;
  48233. this.tsService = tsService;
  48234. this._staticSymbolCache = new StaticSymbolCache();
  48235. this._typeCache = [];
  48236. this.modulesOutOfDate = true;
  48237. this.fileVersions = new Map();
  48238. }
  48239. Object.defineProperty(TypeScriptServiceHost.prototype, "resolver", {
  48240. /**
  48241. * Angular LanguageServiceHost implementation
  48242. */
  48243. get: function () {
  48244. var _this = this;
  48245. this.validate();
  48246. var result = this._resolver;
  48247. if (!result) {
  48248. var moduleResolver = new NgModuleResolver(this.reflector);
  48249. var directiveResolver = new DirectiveResolver(this.reflector);
  48250. var pipeResolver = new PipeResolver(this.reflector);
  48251. var elementSchemaRegistry = new DomElementSchemaRegistry();
  48252. var resourceLoader = new DummyResourceLoader();
  48253. var urlResolver = createOfflineCompileUrlResolver();
  48254. var htmlParser = new DummyHtmlParser();
  48255. // This tracks the CompileConfig in codegen.ts. Currently these options
  48256. // are hard-coded.
  48257. var config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation$1.Emulated, useJit: false });
  48258. var directiveNormalizer = new DirectiveNormalizer(resourceLoader, urlResolver, htmlParser, config);
  48259. result = this._resolver = new CompileMetadataResolver(config, htmlParser, moduleResolver, directiveResolver, pipeResolver, new JitSummaryResolver(), elementSchemaRegistry, directiveNormalizer, new Console(), this._staticSymbolCache, this.reflector, function (error, type) { return _this.collectError(error, type && type.filePath); });
  48260. }
  48261. return result;
  48262. },
  48263. enumerable: true,
  48264. configurable: true
  48265. });
  48266. TypeScriptServiceHost.prototype.getTemplateReferences = function () {
  48267. this.ensureTemplateMap();
  48268. return this.templateReferences || [];
  48269. };
  48270. TypeScriptServiceHost.prototype.getTemplateAt = function (fileName, position) {
  48271. var sourceFile = this.getSourceFile(fileName);
  48272. if (sourceFile) {
  48273. this.context = sourceFile.fileName;
  48274. var node = this.findNode(sourceFile, position);
  48275. if (node) {
  48276. return this.getSourceFromNode(fileName, this.host.getScriptVersion(sourceFile.fileName), node);
  48277. }
  48278. }
  48279. else {
  48280. this.ensureTemplateMap();
  48281. // TODO: Cannocalize the file?
  48282. var componentType = this.fileToComponent.get(fileName);
  48283. if (componentType) {
  48284. return this.getSourceFromType(fileName, this.host.getScriptVersion(fileName), componentType);
  48285. }
  48286. }
  48287. return undefined;
  48288. };
  48289. TypeScriptServiceHost.prototype.getAnalyzedModules = function () {
  48290. this.updateAnalyzedModules();
  48291. return this.ensureAnalyzedModules();
  48292. };
  48293. TypeScriptServiceHost.prototype.ensureAnalyzedModules = function () {
  48294. var analyzedModules = this.analyzedModules;
  48295. if (!analyzedModules) {
  48296. if (this.host.getScriptFileNames().length === 0) {
  48297. analyzedModules = {
  48298. files: [],
  48299. ngModuleByPipeOrDirective: new Map(),
  48300. ngModules: [],
  48301. };
  48302. }
  48303. else {
  48304. var analyzeHost = { isSourceFile: function (filePath) { return true; } };
  48305. var programFiles = this.program.getSourceFiles().map(function (sf) { return sf.fileName; });
  48306. analyzedModules =
  48307. analyzeNgModules(programFiles, analyzeHost, this.staticSymbolResolver, this.resolver);
  48308. }
  48309. this.analyzedModules = analyzedModules;
  48310. }
  48311. return analyzedModules;
  48312. };
  48313. TypeScriptServiceHost.prototype.getTemplates = function (fileName) {
  48314. var _this = this;
  48315. this.ensureTemplateMap();
  48316. var componentType = this.fileToComponent.get(fileName);
  48317. if (componentType) {
  48318. var templateSource = this.getTemplateAt(fileName, 0);
  48319. if (templateSource) {
  48320. return [templateSource];
  48321. }
  48322. }
  48323. else {
  48324. var version_1 = this.host.getScriptVersion(fileName);
  48325. var result_1 = [];
  48326. // Find each template string in the file
  48327. var visit_1 = function (child) {
  48328. var templateSource = _this.getSourceFromNode(fileName, version_1, child);
  48329. if (templateSource) {
  48330. result_1.push(templateSource);
  48331. }
  48332. else {
  48333. ts.forEachChild(child, visit_1);
  48334. }
  48335. };
  48336. var sourceFile = this.getSourceFile(fileName);
  48337. if (sourceFile) {
  48338. this.context = sourceFile.path || sourceFile.fileName;
  48339. ts.forEachChild(sourceFile, visit_1);
  48340. }
  48341. return result_1.length ? result_1 : undefined;
  48342. }
  48343. };
  48344. TypeScriptServiceHost.prototype.getDeclarations = function (fileName) {
  48345. var _this = this;
  48346. var result = [];
  48347. var sourceFile = this.getSourceFile(fileName);
  48348. if (sourceFile) {
  48349. var visit_2 = function (child) {
  48350. var declaration = _this.getDeclarationFromNode(sourceFile, child);
  48351. if (declaration) {
  48352. result.push(declaration);
  48353. }
  48354. else {
  48355. ts.forEachChild(child, visit_2);
  48356. }
  48357. };
  48358. ts.forEachChild(sourceFile, visit_2);
  48359. }
  48360. return result;
  48361. };
  48362. TypeScriptServiceHost.prototype.getSourceFile = function (fileName) {
  48363. return this.tsService.getProgram().getSourceFile(fileName);
  48364. };
  48365. TypeScriptServiceHost.prototype.updateAnalyzedModules = function () {
  48366. this.validate();
  48367. if (this.modulesOutOfDate) {
  48368. this.analyzedModules = null;
  48369. this._reflector = null;
  48370. this.templateReferences = null;
  48371. this.fileToComponent = null;
  48372. this.ensureAnalyzedModules();
  48373. this.modulesOutOfDate = false;
  48374. }
  48375. };
  48376. Object.defineProperty(TypeScriptServiceHost.prototype, "program", {
  48377. get: function () { return this.tsService.getProgram(); },
  48378. enumerable: true,
  48379. configurable: true
  48380. });
  48381. Object.defineProperty(TypeScriptServiceHost.prototype, "checker", {
  48382. get: function () {
  48383. var checker = this._checker;
  48384. if (!checker) {
  48385. checker = this._checker = this.program.getTypeChecker();
  48386. }
  48387. return checker;
  48388. },
  48389. enumerable: true,
  48390. configurable: true
  48391. });
  48392. TypeScriptServiceHost.prototype.validate = function () {
  48393. var _this = this;
  48394. var e_1, _a;
  48395. var program = this.program;
  48396. if (this.lastProgram !== program) {
  48397. // Invalidate file that have changed in the static symbol resolver
  48398. var invalidateFile = function (fileName) {
  48399. return _this._staticSymbolResolver.invalidateFile(fileName);
  48400. };
  48401. this.clearCaches();
  48402. var seen_1 = new Set();
  48403. try {
  48404. for (var _b = __values(this.program.getSourceFiles()), _c = _b.next(); !_c.done; _c = _b.next()) {
  48405. var sourceFile = _c.value;
  48406. var fileName = sourceFile.fileName;
  48407. seen_1.add(fileName);
  48408. var version = this.host.getScriptVersion(fileName);
  48409. var lastVersion = this.fileVersions.get(fileName);
  48410. if (version != lastVersion) {
  48411. this.fileVersions.set(fileName, version);
  48412. if (this._staticSymbolResolver) {
  48413. invalidateFile(fileName);
  48414. }
  48415. }
  48416. }
  48417. }
  48418. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  48419. finally {
  48420. try {
  48421. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  48422. }
  48423. finally { if (e_1) throw e_1.error; }
  48424. }
  48425. // Remove file versions that are no longer in the file and invalidate them.
  48426. var missing = Array.from(this.fileVersions.keys()).filter(function (f) { return !seen_1.has(f); });
  48427. missing.forEach(function (f) { return _this.fileVersions.delete(f); });
  48428. if (this._staticSymbolResolver) {
  48429. missing.forEach(invalidateFile);
  48430. }
  48431. this.lastProgram = program;
  48432. }
  48433. };
  48434. TypeScriptServiceHost.prototype.clearCaches = function () {
  48435. this._checker = null;
  48436. this._typeCache = [];
  48437. this._resolver = null;
  48438. this.collectedErrors = null;
  48439. this.modulesOutOfDate = true;
  48440. };
  48441. TypeScriptServiceHost.prototype.ensureTemplateMap = function () {
  48442. var e_2, _a, e_3, _b;
  48443. if (!this.fileToComponent || !this.templateReferences) {
  48444. var fileToComponent = new Map();
  48445. var templateReference = [];
  48446. var ngModuleSummary = this.getAnalyzedModules();
  48447. var urlResolver = createOfflineCompileUrlResolver();
  48448. try {
  48449. for (var _c = __values(ngModuleSummary.ngModules), _d = _c.next(); !_d.done; _d = _c.next()) {
  48450. var module_1 = _d.value;
  48451. try {
  48452. for (var _e = __values(module_1.declaredDirectives), _f = _e.next(); !_f.done; _f = _e.next()) {
  48453. var directive = _f.value;
  48454. var metadata = this.resolver.getNonNormalizedDirectiveMetadata(directive.reference).metadata;
  48455. if (metadata.isComponent && metadata.template && metadata.template.templateUrl) {
  48456. var templateName = urlResolver.resolve(this.reflector.componentModuleUrl(directive.reference), metadata.template.templateUrl);
  48457. fileToComponent.set(templateName, directive.reference);
  48458. templateReference.push(templateName);
  48459. }
  48460. }
  48461. }
  48462. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  48463. finally {
  48464. try {
  48465. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  48466. }
  48467. finally { if (e_3) throw e_3.error; }
  48468. }
  48469. }
  48470. }
  48471. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  48472. finally {
  48473. try {
  48474. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  48475. }
  48476. finally { if (e_2) throw e_2.error; }
  48477. }
  48478. this.fileToComponent = fileToComponent;
  48479. this.templateReferences = templateReference;
  48480. }
  48481. };
  48482. TypeScriptServiceHost.prototype.getSourceFromDeclaration = function (fileName, version, source, span, type, declaration, node, sourceFile) {
  48483. var queryCache = undefined;
  48484. var t = this;
  48485. if (declaration) {
  48486. return {
  48487. version: version,
  48488. source: source,
  48489. span: span,
  48490. type: type,
  48491. get members() {
  48492. return getClassMembersFromDeclaration(t.program, t.checker, sourceFile, declaration);
  48493. },
  48494. get query() {
  48495. if (!queryCache) {
  48496. var pipes_1 = [];
  48497. var templateInfo = t.getTemplateAstAtPosition(fileName, node.getStart());
  48498. if (templateInfo) {
  48499. pipes_1 = templateInfo.pipes;
  48500. }
  48501. queryCache = getSymbolQuery(t.program, t.checker, sourceFile, function () { return getPipesTable(sourceFile, t.program, t.checker, pipes_1); });
  48502. }
  48503. return queryCache;
  48504. }
  48505. };
  48506. }
  48507. };
  48508. TypeScriptServiceHost.prototype.getSourceFromNode = function (fileName, version, node) {
  48509. var result = undefined;
  48510. switch (node.kind) {
  48511. case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
  48512. case ts.SyntaxKind.StringLiteral:
  48513. var _a = __read(this.getTemplateClassDeclFromNode(node), 2), declaration = _a[0], decorator = _a[1];
  48514. if (declaration && declaration.name) {
  48515. var sourceFile = this.getSourceFile(fileName);
  48516. if (sourceFile) {
  48517. return this.getSourceFromDeclaration(fileName, version, this.stringOf(node) || '', shrink(spanOf$3(node)), this.reflector.getStaticSymbol(sourceFile.fileName, declaration.name.text), declaration, node, sourceFile);
  48518. }
  48519. }
  48520. break;
  48521. }
  48522. return result;
  48523. };
  48524. TypeScriptServiceHost.prototype.getSourceFromType = function (fileName, version, type) {
  48525. var result = undefined;
  48526. var declaration = this.getTemplateClassFromStaticSymbol(type);
  48527. if (declaration) {
  48528. var snapshot = this.host.getScriptSnapshot(fileName);
  48529. if (snapshot) {
  48530. var source = snapshot.getText(0, snapshot.getLength());
  48531. result = this.getSourceFromDeclaration(fileName, version, source, { start: 0, end: source.length }, type, declaration, declaration, declaration.getSourceFile());
  48532. }
  48533. }
  48534. return result;
  48535. };
  48536. Object.defineProperty(TypeScriptServiceHost.prototype, "reflectorHost", {
  48537. get: function () {
  48538. var _this = this;
  48539. var result = this._reflectorHost;
  48540. if (!result) {
  48541. if (!this.context) {
  48542. // Make up a context by finding the first script and using that as the base dir.
  48543. var scriptFileNames = this.host.getScriptFileNames();
  48544. if (0 === scriptFileNames.length) {
  48545. throw new Error('Internal error: no script file names found');
  48546. }
  48547. this.context = scriptFileNames[0];
  48548. }
  48549. // Use the file context's directory as the base directory.
  48550. // The host's getCurrentDirectory() is not reliable as it is always "" in
  48551. // tsserver. We don't need the exact base directory, just one that contains
  48552. // a source file.
  48553. var source = this.tsService.getProgram().getSourceFile(this.context);
  48554. if (!source) {
  48555. throw new Error('Internal error: no context could be determined');
  48556. }
  48557. var tsConfigPath = findTsConfig(source.fileName);
  48558. var basePath = path.dirname(tsConfigPath || this.context);
  48559. var options = { basePath: basePath, genDir: basePath };
  48560. var compilerOptions = this.host.getCompilationSettings();
  48561. if (compilerOptions && compilerOptions.baseUrl) {
  48562. options.baseUrl = compilerOptions.baseUrl;
  48563. }
  48564. if (compilerOptions && compilerOptions.paths) {
  48565. options.paths = compilerOptions.paths;
  48566. }
  48567. result = this._reflectorHost =
  48568. new ReflectorHost(function () { return _this.tsService.getProgram(); }, this.host, options);
  48569. }
  48570. return result;
  48571. },
  48572. enumerable: true,
  48573. configurable: true
  48574. });
  48575. TypeScriptServiceHost.prototype.collectError = function (error, filePath) {
  48576. if (filePath) {
  48577. var errorMap = this.collectedErrors;
  48578. if (!errorMap || !this.collectedErrors) {
  48579. errorMap = this.collectedErrors = new Map();
  48580. }
  48581. var errors = errorMap.get(filePath);
  48582. if (!errors) {
  48583. errors = [];
  48584. this.collectedErrors.set(filePath, errors);
  48585. }
  48586. errors.push(error);
  48587. }
  48588. };
  48589. Object.defineProperty(TypeScriptServiceHost.prototype, "staticSymbolResolver", {
  48590. get: function () {
  48591. var _this = this;
  48592. var result = this._staticSymbolResolver;
  48593. if (!result) {
  48594. this._summaryResolver = new AotSummaryResolver({
  48595. loadSummary: function (filePath) { return null; },
  48596. isSourceFile: function (sourceFilePath) { return true; },
  48597. toSummaryFileName: function (sourceFilePath) { return sourceFilePath; },
  48598. fromSummaryFileName: function (filePath) { return filePath; },
  48599. }, this._staticSymbolCache);
  48600. result = this._staticSymbolResolver = new StaticSymbolResolver(this.reflectorHost, this._staticSymbolCache, this._summaryResolver, function (e, filePath) { return _this.collectError(e, filePath); });
  48601. }
  48602. return result;
  48603. },
  48604. enumerable: true,
  48605. configurable: true
  48606. });
  48607. Object.defineProperty(TypeScriptServiceHost.prototype, "reflector", {
  48608. get: function () {
  48609. var _this = this;
  48610. var result = this._reflector;
  48611. if (!result) {
  48612. var ssr = this.staticSymbolResolver;
  48613. result = this._reflector = new StaticReflector(this._summaryResolver, ssr, [], [], function (e, filePath) { return _this.collectError(e, filePath); });
  48614. }
  48615. return result;
  48616. },
  48617. enumerable: true,
  48618. configurable: true
  48619. });
  48620. TypeScriptServiceHost.prototype.getTemplateClassFromStaticSymbol = function (type) {
  48621. var source = this.getSourceFile(type.filePath);
  48622. if (source) {
  48623. var declarationNode = ts.forEachChild(source, function (child) {
  48624. if (child.kind === ts.SyntaxKind.ClassDeclaration) {
  48625. var classDeclaration = child;
  48626. if (classDeclaration.name != null && classDeclaration.name.text === type.name) {
  48627. return classDeclaration;
  48628. }
  48629. }
  48630. });
  48631. return declarationNode;
  48632. }
  48633. return undefined;
  48634. };
  48635. /**
  48636. * Given a template string node, see if it is an Angular template string, and if so return the
  48637. * containing class.
  48638. */
  48639. TypeScriptServiceHost.prototype.getTemplateClassDeclFromNode = function (currentToken) {
  48640. // Verify we are in a 'template' property assignment, in an object literal, which is an call
  48641. // arg, in a decorator
  48642. var parentNode = currentToken.parent; // PropertyAssignment
  48643. if (!parentNode) {
  48644. return TypeScriptServiceHost.missingTemplate;
  48645. }
  48646. if (parentNode.kind !== ts.SyntaxKind.PropertyAssignment) {
  48647. return TypeScriptServiceHost.missingTemplate;
  48648. }
  48649. else {
  48650. // TODO: Is this different for a literal, i.e. a quoted property name like "template"?
  48651. if (parentNode.name.text !== 'template') {
  48652. return TypeScriptServiceHost.missingTemplate;
  48653. }
  48654. }
  48655. parentNode = parentNode.parent; // ObjectLiteralExpression
  48656. if (!parentNode || parentNode.kind !== ts.SyntaxKind.ObjectLiteralExpression) {
  48657. return TypeScriptServiceHost.missingTemplate;
  48658. }
  48659. parentNode = parentNode.parent; // CallExpression
  48660. if (!parentNode || parentNode.kind !== ts.SyntaxKind.CallExpression) {
  48661. return TypeScriptServiceHost.missingTemplate;
  48662. }
  48663. var callTarget = parentNode.expression;
  48664. var decorator = parentNode.parent; // Decorator
  48665. if (!decorator || decorator.kind !== ts.SyntaxKind.Decorator) {
  48666. return TypeScriptServiceHost.missingTemplate;
  48667. }
  48668. var declaration = decorator.parent; // ClassDeclaration
  48669. if (!declaration || declaration.kind !== ts.SyntaxKind.ClassDeclaration) {
  48670. return TypeScriptServiceHost.missingTemplate;
  48671. }
  48672. return [declaration, callTarget];
  48673. };
  48674. TypeScriptServiceHost.prototype.getCollectedErrors = function (defaultSpan, sourceFile) {
  48675. var errors = (this.collectedErrors && this.collectedErrors.get(sourceFile.fileName));
  48676. return (errors && errors.map(function (e) {
  48677. var line = e.line || (e.position && e.position.line);
  48678. var column = e.column || (e.position && e.position.column);
  48679. var span = spanAt$1(sourceFile, line, column) || defaultSpan;
  48680. if (isFormattedError(e)) {
  48681. return errorToDiagnosticWithChain(e, span);
  48682. }
  48683. return { message: e.message, span: span };
  48684. })) ||
  48685. [];
  48686. };
  48687. TypeScriptServiceHost.prototype.getDeclarationFromNode = function (sourceFile, node) {
  48688. var e_4, _a;
  48689. if (node.kind == ts.SyntaxKind.ClassDeclaration && node.decorators &&
  48690. node.name) {
  48691. try {
  48692. for (var _b = __values(node.decorators), _c = _b.next(); !_c.done; _c = _b.next()) {
  48693. var decorator = _c.value;
  48694. if (decorator.expression && decorator.expression.kind == ts.SyntaxKind.CallExpression) {
  48695. var classDeclaration = node;
  48696. if (classDeclaration.name) {
  48697. var call = decorator.expression;
  48698. var target = call.expression;
  48699. var type = this.checker.getTypeAtLocation(target);
  48700. if (type) {
  48701. var staticSymbol = this.reflector.getStaticSymbol(sourceFile.fileName, classDeclaration.name.text);
  48702. try {
  48703. if (this.resolver.isDirective(staticSymbol)) {
  48704. var metadata = this.resolver.getNonNormalizedDirectiveMetadata(staticSymbol).metadata;
  48705. var declarationSpan = spanOf$3(target);
  48706. return {
  48707. type: staticSymbol,
  48708. declarationSpan: declarationSpan,
  48709. metadata: metadata,
  48710. errors: this.getCollectedErrors(declarationSpan, sourceFile)
  48711. };
  48712. }
  48713. }
  48714. catch (e) {
  48715. if (e.message) {
  48716. this.collectError(e, sourceFile.fileName);
  48717. var declarationSpan = spanOf$3(target);
  48718. return {
  48719. type: staticSymbol,
  48720. declarationSpan: declarationSpan,
  48721. errors: this.getCollectedErrors(declarationSpan, sourceFile)
  48722. };
  48723. }
  48724. }
  48725. }
  48726. }
  48727. }
  48728. }
  48729. }
  48730. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  48731. finally {
  48732. try {
  48733. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  48734. }
  48735. finally { if (e_4) throw e_4.error; }
  48736. }
  48737. }
  48738. };
  48739. TypeScriptServiceHost.prototype.stringOf = function (node) {
  48740. switch (node.kind) {
  48741. case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
  48742. return node.text;
  48743. case ts.SyntaxKind.StringLiteral:
  48744. return node.text;
  48745. }
  48746. };
  48747. TypeScriptServiceHost.prototype.findNode = function (sourceFile, position) {
  48748. function find(node) {
  48749. if (position >= node.getStart() && position < node.getEnd()) {
  48750. return ts.forEachChild(node, find) || node;
  48751. }
  48752. }
  48753. return find(sourceFile);
  48754. };
  48755. TypeScriptServiceHost.prototype.getTemplateAstAtPosition = function (fileName, position) {
  48756. var template = this.getTemplateAt(fileName, position);
  48757. if (template) {
  48758. var astResult = this.getTemplateAst(template, fileName);
  48759. if (astResult && astResult.htmlAst && astResult.templateAst && astResult.directive &&
  48760. astResult.directives && astResult.pipes && astResult.expressionParser)
  48761. return {
  48762. position: position,
  48763. fileName: fileName,
  48764. template: template,
  48765. htmlAst: astResult.htmlAst,
  48766. directive: astResult.directive,
  48767. directives: astResult.directives,
  48768. pipes: astResult.pipes,
  48769. templateAst: astResult.templateAst,
  48770. expressionParser: astResult.expressionParser
  48771. };
  48772. }
  48773. return undefined;
  48774. };
  48775. TypeScriptServiceHost.prototype.getTemplateAst = function (template, contextFile) {
  48776. var _this = this;
  48777. var result = undefined;
  48778. try {
  48779. var resolvedMetadata = this.resolver.getNonNormalizedDirectiveMetadata(template.type);
  48780. var metadata = resolvedMetadata && resolvedMetadata.metadata;
  48781. if (metadata) {
  48782. var rawHtmlParser = new HtmlParser();
  48783. var htmlParser = new I18NHtmlParser(rawHtmlParser);
  48784. var expressionParser = new Parser$1(new Lexer());
  48785. var config = new CompilerConfig();
  48786. var parser = new TemplateParser(config, this.resolver.getReflector(), expressionParser, new DomElementSchemaRegistry(), htmlParser, null, []);
  48787. var htmlResult = htmlParser.parse(template.source, '', { tokenizeExpansionForms: true });
  48788. var analyzedModules = this.getAnalyzedModules();
  48789. var errors = undefined;
  48790. var ngModule = analyzedModules.ngModuleByPipeOrDirective.get(template.type);
  48791. if (!ngModule) {
  48792. // Reported by the the declaration diagnostics.
  48793. ngModule = findSuitableDefaultModule(analyzedModules);
  48794. }
  48795. if (ngModule) {
  48796. var directives = ngModule.transitiveModule.directives
  48797. .map(function (d) { return _this.resolver.getNonNormalizedDirectiveMetadata(d.reference); })
  48798. .filter(function (d) { return d; })
  48799. .map(function (d) { return d.metadata.toSummary(); });
  48800. var pipes = ngModule.transitiveModule.pipes.map(function (p) { return _this.resolver.getOrLoadPipeMetadata(p.reference).toSummary(); });
  48801. var schemas = ngModule.schemas;
  48802. var parseResult = parser.tryParseHtml(htmlResult, metadata, directives, pipes, schemas);
  48803. result = {
  48804. htmlAst: htmlResult.rootNodes,
  48805. templateAst: parseResult.templateAst,
  48806. directive: metadata, directives: directives, pipes: pipes,
  48807. parseErrors: parseResult.errors, expressionParser: expressionParser, errors: errors
  48808. };
  48809. }
  48810. }
  48811. }
  48812. catch (e) {
  48813. var span = template.span;
  48814. if (e.fileName == contextFile) {
  48815. span = template.query.getSpanAt(e.line, e.column) || span;
  48816. }
  48817. result = { errors: [{ kind: DiagnosticKind$1.Error, message: e.message, span: span }] };
  48818. }
  48819. return result || {};
  48820. };
  48821. TypeScriptServiceHost.missingTemplate = [undefined, undefined];
  48822. return TypeScriptServiceHost;
  48823. }());
  48824. function findSuitableDefaultModule(modules) {
  48825. var e_5, _a;
  48826. var result = undefined;
  48827. var resultSize = 0;
  48828. try {
  48829. for (var _b = __values(modules.ngModules), _c = _b.next(); !_c.done; _c = _b.next()) {
  48830. var module_2 = _c.value;
  48831. var moduleSize = module_2.transitiveModule.directives.length;
  48832. if (moduleSize > resultSize) {
  48833. result = module_2;
  48834. resultSize = moduleSize;
  48835. }
  48836. }
  48837. }
  48838. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  48839. finally {
  48840. try {
  48841. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  48842. }
  48843. finally { if (e_5) throw e_5.error; }
  48844. }
  48845. return result;
  48846. }
  48847. function findTsConfig(fileName) {
  48848. var dir = path.dirname(fileName);
  48849. while (fs.existsSync(dir)) {
  48850. var candidate = path.join(dir, 'tsconfig.json');
  48851. if (fs.existsSync(candidate))
  48852. return candidate;
  48853. var parentDir = path.dirname(dir);
  48854. if (parentDir === dir)
  48855. break;
  48856. dir = parentDir;
  48857. }
  48858. }
  48859. function spanOf$3(node) {
  48860. return { start: node.getStart(), end: node.getEnd() };
  48861. }
  48862. function shrink(span, offset) {
  48863. if (offset == null)
  48864. offset = 1;
  48865. return { start: span.start + offset, end: span.end - offset };
  48866. }
  48867. function spanAt$1(sourceFile, line, column) {
  48868. if (line != null && column != null) {
  48869. var position_1 = ts.getPositionOfLineAndCharacter(sourceFile, line, column);
  48870. var findChild = function findChild(node) {
  48871. if (node.kind > ts.SyntaxKind.LastToken && node.pos <= position_1 && node.end > position_1) {
  48872. var betterNode = ts.forEachChild(node, findChild);
  48873. return betterNode || node;
  48874. }
  48875. };
  48876. var node = ts.forEachChild(sourceFile, findChild);
  48877. if (node) {
  48878. return { start: node.getStart(), end: node.getEnd() };
  48879. }
  48880. }
  48881. }
  48882. function convertChain(chain) {
  48883. return { message: chain.message, next: chain.next ? convertChain(chain.next) : undefined };
  48884. }
  48885. function errorToDiagnosticWithChain(error, span) {
  48886. return { message: error.chain ? convertChain(error.chain) : error.message, span: span };
  48887. }
  48888. /**
  48889. * @license
  48890. * Copyright Google Inc. All Rights Reserved.
  48891. *
  48892. * Use of this source code is governed by an MIT-style license that can be
  48893. * found in the LICENSE file at https://angular.io/license
  48894. */
  48895. var projectHostMap = new WeakMap();
  48896. function getExternalFiles(project) {
  48897. var host = projectHostMap.get(project);
  48898. if (host) {
  48899. var externalFiles = host.getTemplateReferences();
  48900. return externalFiles;
  48901. }
  48902. }
  48903. function completionToEntry(c) {
  48904. return {
  48905. // TODO: remove any and fix type error.
  48906. kind: c.kind,
  48907. name: c.name,
  48908. sortText: c.sort,
  48909. kindModifiers: ''
  48910. };
  48911. }
  48912. function diagnosticChainToDiagnosticChain(chain) {
  48913. return {
  48914. messageText: chain.message,
  48915. category: ts.DiagnosticCategory.Error,
  48916. code: 0,
  48917. next: chain.next ? diagnosticChainToDiagnosticChain(chain.next) : undefined
  48918. };
  48919. }
  48920. function diagnosticMessageToDiagnosticMessageText(message) {
  48921. if (typeof message === 'string') {
  48922. return message;
  48923. }
  48924. return diagnosticChainToDiagnosticChain(message);
  48925. }
  48926. function diagnosticToDiagnostic(d, file) {
  48927. var result = {
  48928. file: file,
  48929. start: d.span.start,
  48930. length: d.span.end - d.span.start,
  48931. messageText: diagnosticMessageToDiagnosticMessageText(d.message),
  48932. category: ts.DiagnosticCategory.Error,
  48933. code: 0,
  48934. source: 'ng'
  48935. };
  48936. return result;
  48937. }
  48938. function create(info) {
  48939. var oldLS = info.languageService;
  48940. var proxy = Object.assign({}, oldLS);
  48941. var logger = info.project.projectService.logger;
  48942. function tryOperation(attempting, callback) {
  48943. try {
  48944. return callback();
  48945. }
  48946. catch (e) {
  48947. logger.info("Failed to " + attempting + ": " + e.toString());
  48948. logger.info("Stack trace: " + e.stack);
  48949. return null;
  48950. }
  48951. }
  48952. var serviceHost = new TypeScriptServiceHost(info.languageServiceHost, oldLS);
  48953. var ls = createLanguageService(serviceHost);
  48954. projectHostMap.set(info.project, serviceHost);
  48955. proxy.getCompletionsAtPosition = function (fileName, position, options) {
  48956. var base = oldLS.getCompletionsAtPosition(fileName, position, options) || {
  48957. isGlobalCompletion: false,
  48958. isMemberCompletion: false,
  48959. isNewIdentifierLocation: false,
  48960. entries: []
  48961. };
  48962. tryOperation('get completions', function () {
  48963. var e_1, _a;
  48964. var results = ls.getCompletionsAt(fileName, position);
  48965. if (results && results.length) {
  48966. if (base === undefined) {
  48967. base = {
  48968. isGlobalCompletion: false,
  48969. isMemberCompletion: false,
  48970. isNewIdentifierLocation: false,
  48971. entries: []
  48972. };
  48973. }
  48974. try {
  48975. for (var results_1 = __values(results), results_1_1 = results_1.next(); !results_1_1.done; results_1_1 = results_1.next()) {
  48976. var entry = results_1_1.value;
  48977. base.entries.push(completionToEntry(entry));
  48978. }
  48979. }
  48980. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  48981. finally {
  48982. try {
  48983. if (results_1_1 && !results_1_1.done && (_a = results_1.return)) _a.call(results_1);
  48984. }
  48985. finally { if (e_1) throw e_1.error; }
  48986. }
  48987. }
  48988. });
  48989. return base;
  48990. };
  48991. proxy.getQuickInfoAtPosition = function (fileName, position) {
  48992. var base = oldLS.getQuickInfoAtPosition(fileName, position);
  48993. var ours = ls.getHoverAt(fileName, position);
  48994. if (!ours) {
  48995. return base;
  48996. }
  48997. var result = {
  48998. kind: ts.ScriptElementKind.unknown,
  48999. kindModifiers: ts.ScriptElementKindModifier.none,
  49000. textSpan: {
  49001. start: ours.span.start,
  49002. length: ours.span.end - ours.span.start,
  49003. },
  49004. displayParts: ours.text.map(function (part) {
  49005. return {
  49006. text: part.text,
  49007. kind: part.language || 'angular',
  49008. };
  49009. }),
  49010. documentation: [],
  49011. };
  49012. if (base && base.tags) {
  49013. result.tags = base.tags;
  49014. }
  49015. return result;
  49016. };
  49017. proxy.getSemanticDiagnostics = function (fileName) {
  49018. var result = oldLS.getSemanticDiagnostics(fileName);
  49019. var base = result || [];
  49020. tryOperation('get diagnostics', function () {
  49021. logger.info("Computing Angular semantic diagnostics...");
  49022. var ours = ls.getDiagnostics(fileName);
  49023. if (ours && ours.length) {
  49024. var file_1 = oldLS.getProgram().getSourceFile(fileName);
  49025. if (file_1) {
  49026. base.push.apply(base, ours.map(function (d) { return diagnosticToDiagnostic(d, file_1); }));
  49027. }
  49028. }
  49029. });
  49030. return base;
  49031. };
  49032. proxy.getDefinitionAtPosition = function (fileName, position) {
  49033. var base = oldLS.getDefinitionAtPosition(fileName, position);
  49034. if (base && base.length) {
  49035. return base;
  49036. }
  49037. var ours = ls.getDefinitionAt(fileName, position);
  49038. if (ours && ours.length) {
  49039. return ours.map(function (loc) {
  49040. return {
  49041. fileName: loc.fileName,
  49042. textSpan: {
  49043. start: loc.span.start,
  49044. length: loc.span.end - loc.span.start,
  49045. },
  49046. name: '',
  49047. kind: ts.ScriptElementKind.unknown,
  49048. containerName: loc.fileName,
  49049. containerKind: ts.ScriptElementKind.unknown,
  49050. };
  49051. });
  49052. }
  49053. };
  49054. proxy.getDefinitionAndBoundSpan = function (fileName, position) {
  49055. var base = oldLS.getDefinitionAndBoundSpan(fileName, position);
  49056. if (base && base.definitions && base.definitions.length) {
  49057. return base;
  49058. }
  49059. var ours = ls.getDefinitionAt(fileName, position);
  49060. if (ours && ours.length) {
  49061. return {
  49062. definitions: ours.map(function (loc) {
  49063. return {
  49064. fileName: loc.fileName,
  49065. textSpan: {
  49066. start: loc.span.start,
  49067. length: loc.span.end - loc.span.start,
  49068. },
  49069. name: '',
  49070. kind: ts.ScriptElementKind.unknown,
  49071. containerName: loc.fileName,
  49072. containerKind: ts.ScriptElementKind.unknown,
  49073. };
  49074. }),
  49075. textSpan: {
  49076. start: ours[0].span.start,
  49077. length: ours[0].span.end - ours[0].span.start,
  49078. },
  49079. };
  49080. }
  49081. };
  49082. return proxy;
  49083. }
  49084. /**
  49085. * @license
  49086. * Copyright Google Inc. All Rights Reserved.
  49087. *
  49088. * Use of this source code is governed by an MIT-style license that can be
  49089. * found in the LICENSE file at https://angular.io/license
  49090. */
  49091. var VERSION$3 = new Version$1('8.1.3');
  49092. /**
  49093. * @license
  49094. * Copyright Google Inc. All Rights Reserved.
  49095. *
  49096. * Use of this source code is governed by an MIT-style license that can be
  49097. * found in the LICENSE file at https://angular.io/license
  49098. */
  49099. /**
  49100. * @license
  49101. * Copyright Google Inc. All Rights Reserved.
  49102. *
  49103. * Use of this source code is governed by an MIT-style license that can be
  49104. * found in the LICENSE file at https://angular.io/license
  49105. */
  49106. exports.createLanguageService = createLanguageService;
  49107. exports.TypeScriptServiceHost = TypeScriptServiceHost;
  49108. exports.createLanguageServiceFromTypescript = createLanguageServiceFromTypescript;
  49109. exports.VERSION = VERSION$3;
  49110. exports.getExternalFiles = getExternalFiles;
  49111. exports.create = create;
  49112. Object.defineProperty(exports, '__esModule', { value: true });
  49113. });
  49114. //# sourceMappingURL=language-service.umd.js.map