compiler.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. /**
  7. * @license
  8. * Copyright Google Inc. All Rights Reserved.
  9. *
  10. * Use of this source code is governed by an MIT-style license that can be
  11. * found in the LICENSE file at https://angular.io/license
  12. */
  13. var TagContentType;
  14. (function (TagContentType) {
  15. TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
  16. TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
  17. TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
  18. })(TagContentType || (TagContentType = {}));
  19. function splitNsName(elementName) {
  20. if (elementName[0] != ':') {
  21. return [null, elementName];
  22. }
  23. const colonIndex = elementName.indexOf(':', 1);
  24. if (colonIndex == -1) {
  25. throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`);
  26. }
  27. return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
  28. }
  29. // `<ng-container>` tags work the same regardless the namespace
  30. function isNgContainer(tagName) {
  31. return splitNsName(tagName)[1] === 'ng-container';
  32. }
  33. // `<ng-content>` tags work the same regardless the namespace
  34. function isNgContent(tagName) {
  35. return splitNsName(tagName)[1] === 'ng-content';
  36. }
  37. // `<ng-template>` tags work the same regardless the namespace
  38. function isNgTemplate(tagName) {
  39. return splitNsName(tagName)[1] === 'ng-template';
  40. }
  41. function getNsPrefix(fullName) {
  42. return fullName === null ? null : splitNsName(fullName)[0];
  43. }
  44. function mergeNsAndName(prefix, localName) {
  45. return prefix ? `:${prefix}:${localName}` : localName;
  46. }
  47. // see http://www.w3.org/TR/html51/syntax.html#named-character-references
  48. // see https://html.spec.whatwg.org/multipage/entities.json
  49. // This list is not exhaustive to keep the compiler footprint low.
  50. // The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
  51. // exist.
  52. const NAMED_ENTITIES = {
  53. 'Aacute': '\u00C1',
  54. 'aacute': '\u00E1',
  55. 'Acirc': '\u00C2',
  56. 'acirc': '\u00E2',
  57. 'acute': '\u00B4',
  58. 'AElig': '\u00C6',
  59. 'aelig': '\u00E6',
  60. 'Agrave': '\u00C0',
  61. 'agrave': '\u00E0',
  62. 'alefsym': '\u2135',
  63. 'Alpha': '\u0391',
  64. 'alpha': '\u03B1',
  65. 'amp': '&',
  66. 'and': '\u2227',
  67. 'ang': '\u2220',
  68. 'apos': '\u0027',
  69. 'Aring': '\u00C5',
  70. 'aring': '\u00E5',
  71. 'asymp': '\u2248',
  72. 'Atilde': '\u00C3',
  73. 'atilde': '\u00E3',
  74. 'Auml': '\u00C4',
  75. 'auml': '\u00E4',
  76. 'bdquo': '\u201E',
  77. 'Beta': '\u0392',
  78. 'beta': '\u03B2',
  79. 'brvbar': '\u00A6',
  80. 'bull': '\u2022',
  81. 'cap': '\u2229',
  82. 'Ccedil': '\u00C7',
  83. 'ccedil': '\u00E7',
  84. 'cedil': '\u00B8',
  85. 'cent': '\u00A2',
  86. 'Chi': '\u03A7',
  87. 'chi': '\u03C7',
  88. 'circ': '\u02C6',
  89. 'clubs': '\u2663',
  90. 'cong': '\u2245',
  91. 'copy': '\u00A9',
  92. 'crarr': '\u21B5',
  93. 'cup': '\u222A',
  94. 'curren': '\u00A4',
  95. 'dagger': '\u2020',
  96. 'Dagger': '\u2021',
  97. 'darr': '\u2193',
  98. 'dArr': '\u21D3',
  99. 'deg': '\u00B0',
  100. 'Delta': '\u0394',
  101. 'delta': '\u03B4',
  102. 'diams': '\u2666',
  103. 'divide': '\u00F7',
  104. 'Eacute': '\u00C9',
  105. 'eacute': '\u00E9',
  106. 'Ecirc': '\u00CA',
  107. 'ecirc': '\u00EA',
  108. 'Egrave': '\u00C8',
  109. 'egrave': '\u00E8',
  110. 'empty': '\u2205',
  111. 'emsp': '\u2003',
  112. 'ensp': '\u2002',
  113. 'Epsilon': '\u0395',
  114. 'epsilon': '\u03B5',
  115. 'equiv': '\u2261',
  116. 'Eta': '\u0397',
  117. 'eta': '\u03B7',
  118. 'ETH': '\u00D0',
  119. 'eth': '\u00F0',
  120. 'Euml': '\u00CB',
  121. 'euml': '\u00EB',
  122. 'euro': '\u20AC',
  123. 'exist': '\u2203',
  124. 'fnof': '\u0192',
  125. 'forall': '\u2200',
  126. 'frac12': '\u00BD',
  127. 'frac14': '\u00BC',
  128. 'frac34': '\u00BE',
  129. 'frasl': '\u2044',
  130. 'Gamma': '\u0393',
  131. 'gamma': '\u03B3',
  132. 'ge': '\u2265',
  133. 'gt': '>',
  134. 'harr': '\u2194',
  135. 'hArr': '\u21D4',
  136. 'hearts': '\u2665',
  137. 'hellip': '\u2026',
  138. 'Iacute': '\u00CD',
  139. 'iacute': '\u00ED',
  140. 'Icirc': '\u00CE',
  141. 'icirc': '\u00EE',
  142. 'iexcl': '\u00A1',
  143. 'Igrave': '\u00CC',
  144. 'igrave': '\u00EC',
  145. 'image': '\u2111',
  146. 'infin': '\u221E',
  147. 'int': '\u222B',
  148. 'Iota': '\u0399',
  149. 'iota': '\u03B9',
  150. 'iquest': '\u00BF',
  151. 'isin': '\u2208',
  152. 'Iuml': '\u00CF',
  153. 'iuml': '\u00EF',
  154. 'Kappa': '\u039A',
  155. 'kappa': '\u03BA',
  156. 'Lambda': '\u039B',
  157. 'lambda': '\u03BB',
  158. 'lang': '\u27E8',
  159. 'laquo': '\u00AB',
  160. 'larr': '\u2190',
  161. 'lArr': '\u21D0',
  162. 'lceil': '\u2308',
  163. 'ldquo': '\u201C',
  164. 'le': '\u2264',
  165. 'lfloor': '\u230A',
  166. 'lowast': '\u2217',
  167. 'loz': '\u25CA',
  168. 'lrm': '\u200E',
  169. 'lsaquo': '\u2039',
  170. 'lsquo': '\u2018',
  171. 'lt': '<',
  172. 'macr': '\u00AF',
  173. 'mdash': '\u2014',
  174. 'micro': '\u00B5',
  175. 'middot': '\u00B7',
  176. 'minus': '\u2212',
  177. 'Mu': '\u039C',
  178. 'mu': '\u03BC',
  179. 'nabla': '\u2207',
  180. 'nbsp': '\u00A0',
  181. 'ndash': '\u2013',
  182. 'ne': '\u2260',
  183. 'ni': '\u220B',
  184. 'not': '\u00AC',
  185. 'notin': '\u2209',
  186. 'nsub': '\u2284',
  187. 'Ntilde': '\u00D1',
  188. 'ntilde': '\u00F1',
  189. 'Nu': '\u039D',
  190. 'nu': '\u03BD',
  191. 'Oacute': '\u00D3',
  192. 'oacute': '\u00F3',
  193. 'Ocirc': '\u00D4',
  194. 'ocirc': '\u00F4',
  195. 'OElig': '\u0152',
  196. 'oelig': '\u0153',
  197. 'Ograve': '\u00D2',
  198. 'ograve': '\u00F2',
  199. 'oline': '\u203E',
  200. 'Omega': '\u03A9',
  201. 'omega': '\u03C9',
  202. 'Omicron': '\u039F',
  203. 'omicron': '\u03BF',
  204. 'oplus': '\u2295',
  205. 'or': '\u2228',
  206. 'ordf': '\u00AA',
  207. 'ordm': '\u00BA',
  208. 'Oslash': '\u00D8',
  209. 'oslash': '\u00F8',
  210. 'Otilde': '\u00D5',
  211. 'otilde': '\u00F5',
  212. 'otimes': '\u2297',
  213. 'Ouml': '\u00D6',
  214. 'ouml': '\u00F6',
  215. 'para': '\u00B6',
  216. 'permil': '\u2030',
  217. 'perp': '\u22A5',
  218. 'Phi': '\u03A6',
  219. 'phi': '\u03C6',
  220. 'Pi': '\u03A0',
  221. 'pi': '\u03C0',
  222. 'piv': '\u03D6',
  223. 'plusmn': '\u00B1',
  224. 'pound': '\u00A3',
  225. 'prime': '\u2032',
  226. 'Prime': '\u2033',
  227. 'prod': '\u220F',
  228. 'prop': '\u221D',
  229. 'Psi': '\u03A8',
  230. 'psi': '\u03C8',
  231. 'quot': '\u0022',
  232. 'radic': '\u221A',
  233. 'rang': '\u27E9',
  234. 'raquo': '\u00BB',
  235. 'rarr': '\u2192',
  236. 'rArr': '\u21D2',
  237. 'rceil': '\u2309',
  238. 'rdquo': '\u201D',
  239. 'real': '\u211C',
  240. 'reg': '\u00AE',
  241. 'rfloor': '\u230B',
  242. 'Rho': '\u03A1',
  243. 'rho': '\u03C1',
  244. 'rlm': '\u200F',
  245. 'rsaquo': '\u203A',
  246. 'rsquo': '\u2019',
  247. 'sbquo': '\u201A',
  248. 'Scaron': '\u0160',
  249. 'scaron': '\u0161',
  250. 'sdot': '\u22C5',
  251. 'sect': '\u00A7',
  252. 'shy': '\u00AD',
  253. 'Sigma': '\u03A3',
  254. 'sigma': '\u03C3',
  255. 'sigmaf': '\u03C2',
  256. 'sim': '\u223C',
  257. 'spades': '\u2660',
  258. 'sub': '\u2282',
  259. 'sube': '\u2286',
  260. 'sum': '\u2211',
  261. 'sup': '\u2283',
  262. 'sup1': '\u00B9',
  263. 'sup2': '\u00B2',
  264. 'sup3': '\u00B3',
  265. 'supe': '\u2287',
  266. 'szlig': '\u00DF',
  267. 'Tau': '\u03A4',
  268. 'tau': '\u03C4',
  269. 'there4': '\u2234',
  270. 'Theta': '\u0398',
  271. 'theta': '\u03B8',
  272. 'thetasym': '\u03D1',
  273. 'thinsp': '\u2009',
  274. 'THORN': '\u00DE',
  275. 'thorn': '\u00FE',
  276. 'tilde': '\u02DC',
  277. 'times': '\u00D7',
  278. 'trade': '\u2122',
  279. 'Uacute': '\u00DA',
  280. 'uacute': '\u00FA',
  281. 'uarr': '\u2191',
  282. 'uArr': '\u21D1',
  283. 'Ucirc': '\u00DB',
  284. 'ucirc': '\u00FB',
  285. 'Ugrave': '\u00D9',
  286. 'ugrave': '\u00F9',
  287. 'uml': '\u00A8',
  288. 'upsih': '\u03D2',
  289. 'Upsilon': '\u03A5',
  290. 'upsilon': '\u03C5',
  291. 'Uuml': '\u00DC',
  292. 'uuml': '\u00FC',
  293. 'weierp': '\u2118',
  294. 'Xi': '\u039E',
  295. 'xi': '\u03BE',
  296. 'Yacute': '\u00DD',
  297. 'yacute': '\u00FD',
  298. 'yen': '\u00A5',
  299. 'yuml': '\u00FF',
  300. 'Yuml': '\u0178',
  301. 'Zeta': '\u0396',
  302. 'zeta': '\u03B6',
  303. 'zwj': '\u200D',
  304. 'zwnj': '\u200C',
  305. };
  306. // The &ngsp; pseudo-entity is denoting a space. see:
  307. // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
  308. const NGSP_UNICODE = '\uE500';
  309. NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
  310. /**
  311. * @license
  312. * Copyright Google Inc. All Rights Reserved.
  313. *
  314. * Use of this source code is governed by an MIT-style license that can be
  315. * found in the LICENSE file at https://angular.io/license
  316. */
  317. class HtmlTagDefinition {
  318. constructor({ closedByChildren, implicitNamespacePrefix, contentType = TagContentType.PARSABLE_DATA, closedByParent = false, isVoid = false, ignoreFirstLf = false } = {}) {
  319. this.closedByChildren = {};
  320. this.closedByParent = false;
  321. this.canSelfClose = false;
  322. if (closedByChildren && closedByChildren.length > 0) {
  323. closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true);
  324. }
  325. this.isVoid = isVoid;
  326. this.closedByParent = closedByParent || isVoid;
  327. this.implicitNamespacePrefix = implicitNamespacePrefix || null;
  328. this.contentType = contentType;
  329. this.ignoreFirstLf = ignoreFirstLf;
  330. }
  331. isClosedByChild(name) {
  332. return this.isVoid || name.toLowerCase() in this.closedByChildren;
  333. }
  334. }
  335. let _DEFAULT_TAG_DEFINITION;
  336. // see http://www.w3.org/TR/html51/syntax.html#optional-tags
  337. // This implementation does not fully conform to the HTML5 spec.
  338. let TAG_DEFINITIONS;
  339. function getHtmlTagDefinition(tagName) {
  340. if (!TAG_DEFINITIONS) {
  341. _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
  342. TAG_DEFINITIONS = {
  343. 'base': new HtmlTagDefinition({ isVoid: true }),
  344. 'meta': new HtmlTagDefinition({ isVoid: true }),
  345. 'area': new HtmlTagDefinition({ isVoid: true }),
  346. 'embed': new HtmlTagDefinition({ isVoid: true }),
  347. 'link': new HtmlTagDefinition({ isVoid: true }),
  348. 'img': new HtmlTagDefinition({ isVoid: true }),
  349. 'input': new HtmlTagDefinition({ isVoid: true }),
  350. 'param': new HtmlTagDefinition({ isVoid: true }),
  351. 'hr': new HtmlTagDefinition({ isVoid: true }),
  352. 'br': new HtmlTagDefinition({ isVoid: true }),
  353. 'source': new HtmlTagDefinition({ isVoid: true }),
  354. 'track': new HtmlTagDefinition({ isVoid: true }),
  355. 'wbr': new HtmlTagDefinition({ isVoid: true }),
  356. 'p': new HtmlTagDefinition({
  357. closedByChildren: [
  358. 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
  359. 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
  360. 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
  361. 'p', 'pre', 'section', 'table', 'ul'
  362. ],
  363. closedByParent: true
  364. }),
  365. 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
  366. 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
  367. 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
  368. 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
  369. 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  370. 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  371. 'col': new HtmlTagDefinition({ isVoid: true }),
  372. 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
  373. 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
  374. 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
  375. 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
  376. 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
  377. 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  378. 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  379. 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
  380. 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  381. 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
  382. 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
  383. 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
  384. 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
  385. 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
  386. 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
  387. 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }),
  388. 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
  389. };
  390. }
  391. return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION;
  392. }
  393. /**
  394. * @license
  395. * Copyright Google Inc. All Rights Reserved.
  396. *
  397. * Use of this source code is governed by an MIT-style license that can be
  398. * found in the LICENSE file at https://angular.io/license
  399. */
  400. const _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + //":not("
  401. '([-\\w]+)|' + // "tag"
  402. '(?:\\.([-\\w]+))|' + // ".class"
  403. // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
  404. '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
  405. // "[name="value"]",
  406. // "[name='value']"
  407. '(\\))|' + // ")"
  408. '(\\s*,\\s*)', // ","
  409. 'g');
  410. /**
  411. * A css selector contains an element name,
  412. * css classes and attribute/value pairs with the purpose
  413. * of selecting subsets out of them.
  414. */
  415. class CssSelector {
  416. constructor() {
  417. this.element = null;
  418. this.classNames = [];
  419. /**
  420. * The selectors are encoded in pairs where:
  421. * - even locations are attribute names
  422. * - odd locations are attribute values.
  423. *
  424. * Example:
  425. * Selector: `[key1=value1][key2]` would parse to:
  426. * ```
  427. * ['key1', 'value1', 'key2', '']
  428. * ```
  429. */
  430. this.attrs = [];
  431. this.notSelectors = [];
  432. }
  433. static parse(selector) {
  434. const results = [];
  435. const _addResult = (res, cssSel) => {
  436. if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
  437. cssSel.attrs.length == 0) {
  438. cssSel.element = '*';
  439. }
  440. res.push(cssSel);
  441. };
  442. let cssSelector = new CssSelector();
  443. let match;
  444. let current = cssSelector;
  445. let inNot = false;
  446. _SELECTOR_REGEXP.lastIndex = 0;
  447. while (match = _SELECTOR_REGEXP.exec(selector)) {
  448. if (match[1]) {
  449. if (inNot) {
  450. throw new Error('Nesting :not is not allowed in a selector');
  451. }
  452. inNot = true;
  453. current = new CssSelector();
  454. cssSelector.notSelectors.push(current);
  455. }
  456. if (match[2]) {
  457. current.setElement(match[2]);
  458. }
  459. if (match[3]) {
  460. current.addClassName(match[3]);
  461. }
  462. if (match[4]) {
  463. current.addAttribute(match[4], match[6]);
  464. }
  465. if (match[7]) {
  466. inNot = false;
  467. current = cssSelector;
  468. }
  469. if (match[8]) {
  470. if (inNot) {
  471. throw new Error('Multiple selectors in :not are not supported');
  472. }
  473. _addResult(results, cssSelector);
  474. cssSelector = current = new CssSelector();
  475. }
  476. }
  477. _addResult(results, cssSelector);
  478. return results;
  479. }
  480. isElementSelector() {
  481. return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
  482. this.notSelectors.length === 0;
  483. }
  484. hasElementSelector() { return !!this.element; }
  485. setElement(element = null) { this.element = element; }
  486. /** Gets a template string for an element that matches the selector. */
  487. getMatchingElementTemplate() {
  488. const tagName = this.element || 'div';
  489. const classAttr = this.classNames.length > 0 ? ` class="${this.classNames.join(' ')}"` : '';
  490. let attrs = '';
  491. for (let i = 0; i < this.attrs.length; i += 2) {
  492. const attrName = this.attrs[i];
  493. const attrValue = this.attrs[i + 1] !== '' ? `="${this.attrs[i + 1]}"` : '';
  494. attrs += ` ${attrName}${attrValue}`;
  495. }
  496. return getHtmlTagDefinition(tagName).isVoid ? `<${tagName}${classAttr}${attrs}/>` :
  497. `<${tagName}${classAttr}${attrs}></${tagName}>`;
  498. }
  499. getAttrs() {
  500. const result = [];
  501. if (this.classNames.length > 0) {
  502. result.push('class', this.classNames.join(' '));
  503. }
  504. return result.concat(this.attrs);
  505. }
  506. addAttribute(name, value = '') {
  507. this.attrs.push(name, value && value.toLowerCase() || '');
  508. }
  509. addClassName(name) { this.classNames.push(name.toLowerCase()); }
  510. toString() {
  511. let res = this.element || '';
  512. if (this.classNames) {
  513. this.classNames.forEach(klass => res += `.${klass}`);
  514. }
  515. if (this.attrs) {
  516. for (let i = 0; i < this.attrs.length; i += 2) {
  517. const name = this.attrs[i];
  518. const value = this.attrs[i + 1];
  519. res += `[${name}${value ? '=' + value : ''}]`;
  520. }
  521. }
  522. this.notSelectors.forEach(notSelector => res += `:not(${notSelector})`);
  523. return res;
  524. }
  525. }
  526. /**
  527. * Reads a list of CssSelectors and allows to calculate which ones
  528. * are contained in a given CssSelector.
  529. */
  530. class SelectorMatcher {
  531. constructor() {
  532. this._elementMap = new Map();
  533. this._elementPartialMap = new Map();
  534. this._classMap = new Map();
  535. this._classPartialMap = new Map();
  536. this._attrValueMap = new Map();
  537. this._attrValuePartialMap = new Map();
  538. this._listContexts = [];
  539. }
  540. static createNotMatcher(notSelectors) {
  541. const notMatcher = new SelectorMatcher();
  542. notMatcher.addSelectables(notSelectors, null);
  543. return notMatcher;
  544. }
  545. addSelectables(cssSelectors, callbackCtxt) {
  546. let listContext = null;
  547. if (cssSelectors.length > 1) {
  548. listContext = new SelectorListContext(cssSelectors);
  549. this._listContexts.push(listContext);
  550. }
  551. for (let i = 0; i < cssSelectors.length; i++) {
  552. this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
  553. }
  554. }
  555. /**
  556. * Add an object that can be found later on by calling `match`.
  557. * @param cssSelector A css selector
  558. * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
  559. */
  560. _addSelectable(cssSelector, callbackCtxt, listContext) {
  561. let matcher = this;
  562. const element = cssSelector.element;
  563. const classNames = cssSelector.classNames;
  564. const attrs = cssSelector.attrs;
  565. const selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
  566. if (element) {
  567. const isTerminal = attrs.length === 0 && classNames.length === 0;
  568. if (isTerminal) {
  569. this._addTerminal(matcher._elementMap, element, selectable);
  570. }
  571. else {
  572. matcher = this._addPartial(matcher._elementPartialMap, element);
  573. }
  574. }
  575. if (classNames) {
  576. for (let i = 0; i < classNames.length; i++) {
  577. const isTerminal = attrs.length === 0 && i === classNames.length - 1;
  578. const className = classNames[i];
  579. if (isTerminal) {
  580. this._addTerminal(matcher._classMap, className, selectable);
  581. }
  582. else {
  583. matcher = this._addPartial(matcher._classPartialMap, className);
  584. }
  585. }
  586. }
  587. if (attrs) {
  588. for (let i = 0; i < attrs.length; i += 2) {
  589. const isTerminal = i === attrs.length - 2;
  590. const name = attrs[i];
  591. const value = attrs[i + 1];
  592. if (isTerminal) {
  593. const terminalMap = matcher._attrValueMap;
  594. let terminalValuesMap = terminalMap.get(name);
  595. if (!terminalValuesMap) {
  596. terminalValuesMap = new Map();
  597. terminalMap.set(name, terminalValuesMap);
  598. }
  599. this._addTerminal(terminalValuesMap, value, selectable);
  600. }
  601. else {
  602. const partialMap = matcher._attrValuePartialMap;
  603. let partialValuesMap = partialMap.get(name);
  604. if (!partialValuesMap) {
  605. partialValuesMap = new Map();
  606. partialMap.set(name, partialValuesMap);
  607. }
  608. matcher = this._addPartial(partialValuesMap, value);
  609. }
  610. }
  611. }
  612. }
  613. _addTerminal(map, name, selectable) {
  614. let terminalList = map.get(name);
  615. if (!terminalList) {
  616. terminalList = [];
  617. map.set(name, terminalList);
  618. }
  619. terminalList.push(selectable);
  620. }
  621. _addPartial(map, name) {
  622. let matcher = map.get(name);
  623. if (!matcher) {
  624. matcher = new SelectorMatcher();
  625. map.set(name, matcher);
  626. }
  627. return matcher;
  628. }
  629. /**
  630. * Find the objects that have been added via `addSelectable`
  631. * whose css selector is contained in the given css selector.
  632. * @param cssSelector A css selector
  633. * @param matchedCallback This callback will be called with the object handed into `addSelectable`
  634. * @return boolean true if a match was found
  635. */
  636. match(cssSelector, matchedCallback) {
  637. let result = false;
  638. const element = cssSelector.element;
  639. const classNames = cssSelector.classNames;
  640. const attrs = cssSelector.attrs;
  641. for (let i = 0; i < this._listContexts.length; i++) {
  642. this._listContexts[i].alreadyMatched = false;
  643. }
  644. result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
  645. result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
  646. result;
  647. if (classNames) {
  648. for (let i = 0; i < classNames.length; i++) {
  649. const className = classNames[i];
  650. result =
  651. this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
  652. result =
  653. this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
  654. result;
  655. }
  656. }
  657. if (attrs) {
  658. for (let i = 0; i < attrs.length; i += 2) {
  659. const name = attrs[i];
  660. const value = attrs[i + 1];
  661. const terminalValuesMap = this._attrValueMap.get(name);
  662. if (value) {
  663. result =
  664. this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
  665. }
  666. result =
  667. this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
  668. const partialValuesMap = this._attrValuePartialMap.get(name);
  669. if (value) {
  670. result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
  671. }
  672. result =
  673. this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
  674. }
  675. }
  676. return result;
  677. }
  678. /** @internal */
  679. _matchTerminal(map, name, cssSelector, matchedCallback) {
  680. if (!map || typeof name !== 'string') {
  681. return false;
  682. }
  683. let selectables = map.get(name) || [];
  684. const starSelectables = map.get('*');
  685. if (starSelectables) {
  686. selectables = selectables.concat(starSelectables);
  687. }
  688. if (selectables.length === 0) {
  689. return false;
  690. }
  691. let selectable;
  692. let result = false;
  693. for (let i = 0; i < selectables.length; i++) {
  694. selectable = selectables[i];
  695. result = selectable.finalize(cssSelector, matchedCallback) || result;
  696. }
  697. return result;
  698. }
  699. /** @internal */
  700. _matchPartial(map, name, cssSelector, matchedCallback) {
  701. if (!map || typeof name !== 'string') {
  702. return false;
  703. }
  704. const nestedSelector = map.get(name);
  705. if (!nestedSelector) {
  706. return false;
  707. }
  708. // TODO(perf): get rid of recursion and measure again
  709. // TODO(perf): don't pass the whole selector into the recursion,
  710. // but only the not processed parts
  711. return nestedSelector.match(cssSelector, matchedCallback);
  712. }
  713. }
  714. class SelectorListContext {
  715. constructor(selectors) {
  716. this.selectors = selectors;
  717. this.alreadyMatched = false;
  718. }
  719. }
  720. // Store context to pass back selector and context when a selector is matched
  721. class SelectorContext {
  722. constructor(selector, cbContext, listContext) {
  723. this.selector = selector;
  724. this.cbContext = cbContext;
  725. this.listContext = listContext;
  726. this.notSelectors = selector.notSelectors;
  727. }
  728. finalize(cssSelector, callback) {
  729. let result = true;
  730. if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
  731. const notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
  732. result = !notMatcher.match(cssSelector, null);
  733. }
  734. if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
  735. if (this.listContext) {
  736. this.listContext.alreadyMatched = true;
  737. }
  738. callback(this.selector, this.cbContext);
  739. }
  740. return result;
  741. }
  742. }
  743. /**
  744. * @license
  745. * Copyright Google Inc. All Rights Reserved.
  746. *
  747. * Use of this source code is governed by an MIT-style license that can be
  748. * found in the LICENSE file at https://angular.io/license
  749. */
  750. const createInject = makeMetadataFactory('Inject', (token) => ({ token }));
  751. const createInjectionToken = makeMetadataFactory('InjectionToken', (desc) => ({ _desc: desc, ngInjectableDef: undefined }));
  752. const createAttribute = makeMetadataFactory('Attribute', (attributeName) => ({ attributeName }));
  753. const createContentChildren = makeMetadataFactory('ContentChildren', (selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: false, descendants: false }, data)));
  754. const createContentChild = makeMetadataFactory('ContentChild', (selector, data = {}) => (Object.assign({ selector, first: true, isViewQuery: false, descendants: true }, data)));
  755. const createViewChildren = makeMetadataFactory('ViewChildren', (selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: true, descendants: true }, data)));
  756. const createViewChild = makeMetadataFactory('ViewChild', (selector, data) => (Object.assign({ selector, first: true, isViewQuery: true, descendants: true }, data)));
  757. const createDirective = makeMetadataFactory('Directive', (dir = {}) => dir);
  758. var ViewEncapsulation;
  759. (function (ViewEncapsulation) {
  760. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  761. ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
  762. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  763. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  764. })(ViewEncapsulation || (ViewEncapsulation = {}));
  765. var ChangeDetectionStrategy;
  766. (function (ChangeDetectionStrategy) {
  767. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  768. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  769. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  770. const createComponent = makeMetadataFactory('Component', (c = {}) => (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c)));
  771. const createPipe = makeMetadataFactory('Pipe', (p) => (Object.assign({ pure: true }, p)));
  772. const createInput = makeMetadataFactory('Input', (bindingPropertyName) => ({ bindingPropertyName }));
  773. const createOutput = makeMetadataFactory('Output', (bindingPropertyName) => ({ bindingPropertyName }));
  774. const createHostBinding = makeMetadataFactory('HostBinding', (hostPropertyName) => ({ hostPropertyName }));
  775. const createHostListener = makeMetadataFactory('HostListener', (eventName, args) => ({ eventName, args }));
  776. const createNgModule = makeMetadataFactory('NgModule', (ngModule) => ngModule);
  777. const createInjectable = makeMetadataFactory('Injectable', (injectable = {}) => injectable);
  778. const CUSTOM_ELEMENTS_SCHEMA = {
  779. name: 'custom-elements'
  780. };
  781. const NO_ERRORS_SCHEMA = {
  782. name: 'no-errors-schema'
  783. };
  784. const createOptional = makeMetadataFactory('Optional');
  785. const createSelf = makeMetadataFactory('Self');
  786. const createSkipSelf = makeMetadataFactory('SkipSelf');
  787. const createHost = makeMetadataFactory('Host');
  788. const Type = Function;
  789. var SecurityContext;
  790. (function (SecurityContext) {
  791. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  792. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  793. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  794. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  795. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  796. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  797. })(SecurityContext || (SecurityContext = {}));
  798. var MissingTranslationStrategy;
  799. (function (MissingTranslationStrategy) {
  800. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  801. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  802. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  803. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  804. function makeMetadataFactory(name, props) {
  805. // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
  806. // that works with the static_reflector.ts in the ViewEngine compiler.
  807. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
  808. // new'ed.
  809. function factory(...args) {
  810. const values = props ? props(...args) : {};
  811. return Object.assign({ ngMetadataName: name }, values);
  812. }
  813. factory.isTypeOf = (obj) => obj && obj.ngMetadataName === name;
  814. factory.ngMetadataName = name;
  815. return factory;
  816. }
  817. function parserSelectorToSimpleSelector(selector) {
  818. const classes = selector.classNames && selector.classNames.length ?
  819. [8 /* CLASS */, ...selector.classNames] :
  820. [];
  821. const elementName = selector.element && selector.element !== '*' ? selector.element : '';
  822. return [elementName, ...selector.attrs, ...classes];
  823. }
  824. function parserSelectorToNegativeSelector(selector) {
  825. const classes = selector.classNames && selector.classNames.length ?
  826. [8 /* CLASS */, ...selector.classNames] :
  827. [];
  828. if (selector.element) {
  829. return [
  830. 1 /* NOT */ | 4 /* ELEMENT */, selector.element, ...selector.attrs, ...classes
  831. ];
  832. }
  833. else if (selector.attrs.length) {
  834. return [1 /* NOT */ | 2 /* ATTRIBUTE */, ...selector.attrs, ...classes];
  835. }
  836. else {
  837. return selector.classNames && selector.classNames.length ?
  838. [1 /* NOT */ | 8 /* CLASS */, ...selector.classNames] :
  839. [];
  840. }
  841. }
  842. function parserSelectorToR3Selector(selector) {
  843. const positive = parserSelectorToSimpleSelector(selector);
  844. const negative = selector.notSelectors && selector.notSelectors.length ?
  845. selector.notSelectors.map(notSelector => parserSelectorToNegativeSelector(notSelector)) :
  846. [];
  847. return positive.concat(...negative);
  848. }
  849. function parseSelectorToR3Selector(selector) {
  850. return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
  851. }
  852. var core = /*#__PURE__*/Object.freeze({
  853. createInject: createInject,
  854. createInjectionToken: createInjectionToken,
  855. createAttribute: createAttribute,
  856. createContentChildren: createContentChildren,
  857. createContentChild: createContentChild,
  858. createViewChildren: createViewChildren,
  859. createViewChild: createViewChild,
  860. createDirective: createDirective,
  861. get ViewEncapsulation () { return ViewEncapsulation; },
  862. get ChangeDetectionStrategy () { return ChangeDetectionStrategy; },
  863. createComponent: createComponent,
  864. createPipe: createPipe,
  865. createInput: createInput,
  866. createOutput: createOutput,
  867. createHostBinding: createHostBinding,
  868. createHostListener: createHostListener,
  869. createNgModule: createNgModule,
  870. createInjectable: createInjectable,
  871. CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA,
  872. NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA,
  873. createOptional: createOptional,
  874. createSelf: createSelf,
  875. createSkipSelf: createSkipSelf,
  876. createHost: createHost,
  877. Type: Type,
  878. get SecurityContext () { return SecurityContext; },
  879. get MissingTranslationStrategy () { return MissingTranslationStrategy; },
  880. parseSelectorToR3Selector: parseSelectorToR3Selector
  881. });
  882. /**
  883. * @license
  884. * Copyright Google Inc. All Rights Reserved.
  885. *
  886. * Use of this source code is governed by an MIT-style license that can be
  887. * found in the LICENSE file at https://angular.io/license
  888. */
  889. //// Types
  890. var TypeModifier;
  891. (function (TypeModifier) {
  892. TypeModifier[TypeModifier["Const"] = 0] = "Const";
  893. })(TypeModifier || (TypeModifier = {}));
  894. class Type$1 {
  895. constructor(modifiers = null) {
  896. this.modifiers = modifiers;
  897. if (!modifiers) {
  898. this.modifiers = [];
  899. }
  900. }
  901. hasModifier(modifier) { return this.modifiers.indexOf(modifier) !== -1; }
  902. }
  903. var BuiltinTypeName;
  904. (function (BuiltinTypeName) {
  905. BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
  906. BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
  907. BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
  908. BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
  909. BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
  910. BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
  911. BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
  912. BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None";
  913. })(BuiltinTypeName || (BuiltinTypeName = {}));
  914. class BuiltinType extends Type$1 {
  915. constructor(name, modifiers = null) {
  916. super(modifiers);
  917. this.name = name;
  918. }
  919. visitType(visitor, context) {
  920. return visitor.visitBuiltinType(this, context);
  921. }
  922. }
  923. class ExpressionType extends Type$1 {
  924. constructor(value, modifiers = null, typeParams = null) {
  925. super(modifiers);
  926. this.value = value;
  927. this.typeParams = typeParams;
  928. }
  929. visitType(visitor, context) {
  930. return visitor.visitExpressionType(this, context);
  931. }
  932. }
  933. class ArrayType extends Type$1 {
  934. constructor(of, modifiers = null) {
  935. super(modifiers);
  936. this.of = of;
  937. }
  938. visitType(visitor, context) {
  939. return visitor.visitArrayType(this, context);
  940. }
  941. }
  942. class MapType extends Type$1 {
  943. constructor(valueType, modifiers = null) {
  944. super(modifiers);
  945. this.valueType = valueType || null;
  946. }
  947. visitType(visitor, context) { return visitor.visitMapType(this, context); }
  948. }
  949. const DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
  950. const INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
  951. const BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
  952. const INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
  953. const NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
  954. const STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
  955. const FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
  956. const NONE_TYPE = new BuiltinType(BuiltinTypeName.None);
  957. ///// Expressions
  958. var BinaryOperator;
  959. (function (BinaryOperator) {
  960. BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
  961. BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
  962. BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
  963. BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
  964. BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
  965. BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
  966. BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
  967. BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
  968. BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
  969. BinaryOperator[BinaryOperator["And"] = 9] = "And";
  970. BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
  971. BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
  972. BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
  973. BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
  974. BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
  975. BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
  976. })(BinaryOperator || (BinaryOperator = {}));
  977. function nullSafeIsEquivalent(base, other) {
  978. if (base == null || other == null) {
  979. return base == other;
  980. }
  981. return base.isEquivalent(other);
  982. }
  983. function areAllEquivalent(base, other) {
  984. const len = base.length;
  985. if (len !== other.length) {
  986. return false;
  987. }
  988. for (let i = 0; i < len; i++) {
  989. if (!base[i].isEquivalent(other[i])) {
  990. return false;
  991. }
  992. }
  993. return true;
  994. }
  995. class Expression {
  996. constructor(type, sourceSpan) {
  997. this.type = type || null;
  998. this.sourceSpan = sourceSpan || null;
  999. }
  1000. prop(name, sourceSpan) {
  1001. return new ReadPropExpr(this, name, null, sourceSpan);
  1002. }
  1003. key(index, type, sourceSpan) {
  1004. return new ReadKeyExpr(this, index, type, sourceSpan);
  1005. }
  1006. callMethod(name, params, sourceSpan) {
  1007. return new InvokeMethodExpr(this, name, params, null, sourceSpan);
  1008. }
  1009. callFn(params, sourceSpan) {
  1010. return new InvokeFunctionExpr(this, params, null, sourceSpan);
  1011. }
  1012. instantiate(params, type, sourceSpan) {
  1013. return new InstantiateExpr(this, params, type, sourceSpan);
  1014. }
  1015. conditional(trueCase, falseCase = null, sourceSpan) {
  1016. return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
  1017. }
  1018. equals(rhs, sourceSpan) {
  1019. return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
  1020. }
  1021. notEquals(rhs, sourceSpan) {
  1022. return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
  1023. }
  1024. identical(rhs, sourceSpan) {
  1025. return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
  1026. }
  1027. notIdentical(rhs, sourceSpan) {
  1028. return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
  1029. }
  1030. minus(rhs, sourceSpan) {
  1031. return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
  1032. }
  1033. plus(rhs, sourceSpan) {
  1034. return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
  1035. }
  1036. divide(rhs, sourceSpan) {
  1037. return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
  1038. }
  1039. multiply(rhs, sourceSpan) {
  1040. return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
  1041. }
  1042. modulo(rhs, sourceSpan) {
  1043. return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
  1044. }
  1045. and(rhs, sourceSpan) {
  1046. return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
  1047. }
  1048. bitwiseAnd(rhs, sourceSpan, parens = true) {
  1049. return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
  1050. }
  1051. or(rhs, sourceSpan) {
  1052. return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
  1053. }
  1054. lower(rhs, sourceSpan) {
  1055. return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
  1056. }
  1057. lowerEquals(rhs, sourceSpan) {
  1058. return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
  1059. }
  1060. bigger(rhs, sourceSpan) {
  1061. return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
  1062. }
  1063. biggerEquals(rhs, sourceSpan) {
  1064. return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
  1065. }
  1066. isBlank(sourceSpan) {
  1067. // Note: We use equals by purpose here to compare to null and undefined in JS.
  1068. // We use the typed null to allow strictNullChecks to narrow types.
  1069. return this.equals(TYPED_NULL_EXPR, sourceSpan);
  1070. }
  1071. cast(type, sourceSpan) {
  1072. return new CastExpr(this, type, sourceSpan);
  1073. }
  1074. toStmt() { return new ExpressionStatement(this, null); }
  1075. }
  1076. var BuiltinVar;
  1077. (function (BuiltinVar) {
  1078. BuiltinVar[BuiltinVar["This"] = 0] = "This";
  1079. BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
  1080. BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
  1081. BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
  1082. })(BuiltinVar || (BuiltinVar = {}));
  1083. class ReadVarExpr extends Expression {
  1084. constructor(name, type, sourceSpan) {
  1085. super(type, sourceSpan);
  1086. if (typeof name === 'string') {
  1087. this.name = name;
  1088. this.builtin = null;
  1089. }
  1090. else {
  1091. this.name = null;
  1092. this.builtin = name;
  1093. }
  1094. }
  1095. isEquivalent(e) {
  1096. return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
  1097. }
  1098. isConstant() { return false; }
  1099. visitExpression(visitor, context) {
  1100. return visitor.visitReadVarExpr(this, context);
  1101. }
  1102. set(value) {
  1103. if (!this.name) {
  1104. throw new Error(`Built in variable ${this.builtin} can not be assigned to.`);
  1105. }
  1106. return new WriteVarExpr(this.name, value, null, this.sourceSpan);
  1107. }
  1108. }
  1109. class TypeofExpr extends Expression {
  1110. constructor(expr, type, sourceSpan) {
  1111. super(type, sourceSpan);
  1112. this.expr = expr;
  1113. }
  1114. visitExpression(visitor, context) {
  1115. return visitor.visitTypeofExpr(this, context);
  1116. }
  1117. isEquivalent(e) {
  1118. return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
  1119. }
  1120. isConstant() { return this.expr.isConstant(); }
  1121. }
  1122. class WrappedNodeExpr extends Expression {
  1123. constructor(node, type, sourceSpan) {
  1124. super(type, sourceSpan);
  1125. this.node = node;
  1126. }
  1127. isEquivalent(e) {
  1128. return e instanceof WrappedNodeExpr && this.node === e.node;
  1129. }
  1130. isConstant() { return false; }
  1131. visitExpression(visitor, context) {
  1132. return visitor.visitWrappedNodeExpr(this, context);
  1133. }
  1134. }
  1135. class WriteVarExpr extends Expression {
  1136. constructor(name, value, type, sourceSpan) {
  1137. super(type || value.type, sourceSpan);
  1138. this.name = name;
  1139. this.value = value;
  1140. }
  1141. isEquivalent(e) {
  1142. return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
  1143. }
  1144. isConstant() { return false; }
  1145. visitExpression(visitor, context) {
  1146. return visitor.visitWriteVarExpr(this, context);
  1147. }
  1148. toDeclStmt(type, modifiers) {
  1149. return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
  1150. }
  1151. toConstDecl() { return this.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]); }
  1152. }
  1153. class WriteKeyExpr extends Expression {
  1154. constructor(receiver, index, value, type, sourceSpan) {
  1155. super(type || value.type, sourceSpan);
  1156. this.receiver = receiver;
  1157. this.index = index;
  1158. this.value = value;
  1159. }
  1160. isEquivalent(e) {
  1161. return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1162. this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
  1163. }
  1164. isConstant() { return false; }
  1165. visitExpression(visitor, context) {
  1166. return visitor.visitWriteKeyExpr(this, context);
  1167. }
  1168. }
  1169. class WritePropExpr extends Expression {
  1170. constructor(receiver, name, value, type, sourceSpan) {
  1171. super(type || value.type, sourceSpan);
  1172. this.receiver = receiver;
  1173. this.name = name;
  1174. this.value = value;
  1175. }
  1176. isEquivalent(e) {
  1177. return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
  1178. this.name === e.name && this.value.isEquivalent(e.value);
  1179. }
  1180. isConstant() { return false; }
  1181. visitExpression(visitor, context) {
  1182. return visitor.visitWritePropExpr(this, context);
  1183. }
  1184. }
  1185. var BuiltinMethod;
  1186. (function (BuiltinMethod) {
  1187. BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
  1188. BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
  1189. BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
  1190. })(BuiltinMethod || (BuiltinMethod = {}));
  1191. class InvokeMethodExpr extends Expression {
  1192. constructor(receiver, method, args, type, sourceSpan) {
  1193. super(type, sourceSpan);
  1194. this.receiver = receiver;
  1195. this.args = args;
  1196. if (typeof method === 'string') {
  1197. this.name = method;
  1198. this.builtin = null;
  1199. }
  1200. else {
  1201. this.name = null;
  1202. this.builtin = method;
  1203. }
  1204. }
  1205. isEquivalent(e) {
  1206. return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
  1207. this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
  1208. }
  1209. isConstant() { return false; }
  1210. visitExpression(visitor, context) {
  1211. return visitor.visitInvokeMethodExpr(this, context);
  1212. }
  1213. }
  1214. class InvokeFunctionExpr extends Expression {
  1215. constructor(fn, args, type, sourceSpan, pure = false) {
  1216. super(type, sourceSpan);
  1217. this.fn = fn;
  1218. this.args = args;
  1219. this.pure = pure;
  1220. }
  1221. isEquivalent(e) {
  1222. return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
  1223. areAllEquivalent(this.args, e.args) && this.pure === e.pure;
  1224. }
  1225. isConstant() { return false; }
  1226. visitExpression(visitor, context) {
  1227. return visitor.visitInvokeFunctionExpr(this, context);
  1228. }
  1229. }
  1230. class InstantiateExpr extends Expression {
  1231. constructor(classExpr, args, type, sourceSpan) {
  1232. super(type, sourceSpan);
  1233. this.classExpr = classExpr;
  1234. this.args = args;
  1235. }
  1236. isEquivalent(e) {
  1237. return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
  1238. areAllEquivalent(this.args, e.args);
  1239. }
  1240. isConstant() { return false; }
  1241. visitExpression(visitor, context) {
  1242. return visitor.visitInstantiateExpr(this, context);
  1243. }
  1244. }
  1245. class LiteralExpr extends Expression {
  1246. constructor(value, type, sourceSpan) {
  1247. super(type, sourceSpan);
  1248. this.value = value;
  1249. }
  1250. isEquivalent(e) {
  1251. return e instanceof LiteralExpr && this.value === e.value;
  1252. }
  1253. isConstant() { return true; }
  1254. visitExpression(visitor, context) {
  1255. return visitor.visitLiteralExpr(this, context);
  1256. }
  1257. }
  1258. class ExternalExpr extends Expression {
  1259. constructor(value, type, typeParams = null, sourceSpan) {
  1260. super(type, sourceSpan);
  1261. this.value = value;
  1262. this.typeParams = typeParams;
  1263. }
  1264. isEquivalent(e) {
  1265. return e instanceof ExternalExpr && this.value.name === e.value.name &&
  1266. this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
  1267. }
  1268. isConstant() { return false; }
  1269. visitExpression(visitor, context) {
  1270. return visitor.visitExternalExpr(this, context);
  1271. }
  1272. }
  1273. class ExternalReference {
  1274. constructor(moduleName, name, runtime) {
  1275. this.moduleName = moduleName;
  1276. this.name = name;
  1277. this.runtime = runtime;
  1278. }
  1279. }
  1280. class ConditionalExpr extends Expression {
  1281. constructor(condition, trueCase, falseCase = null, type, sourceSpan) {
  1282. super(type || trueCase.type, sourceSpan);
  1283. this.condition = condition;
  1284. this.falseCase = falseCase;
  1285. this.trueCase = trueCase;
  1286. }
  1287. isEquivalent(e) {
  1288. return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
  1289. this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
  1290. }
  1291. isConstant() { return false; }
  1292. visitExpression(visitor, context) {
  1293. return visitor.visitConditionalExpr(this, context);
  1294. }
  1295. }
  1296. class NotExpr extends Expression {
  1297. constructor(condition, sourceSpan) {
  1298. super(BOOL_TYPE, sourceSpan);
  1299. this.condition = condition;
  1300. }
  1301. isEquivalent(e) {
  1302. return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
  1303. }
  1304. isConstant() { return false; }
  1305. visitExpression(visitor, context) {
  1306. return visitor.visitNotExpr(this, context);
  1307. }
  1308. }
  1309. class AssertNotNull extends Expression {
  1310. constructor(condition, sourceSpan) {
  1311. super(condition.type, sourceSpan);
  1312. this.condition = condition;
  1313. }
  1314. isEquivalent(e) {
  1315. return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
  1316. }
  1317. isConstant() { return false; }
  1318. visitExpression(visitor, context) {
  1319. return visitor.visitAssertNotNullExpr(this, context);
  1320. }
  1321. }
  1322. class CastExpr extends Expression {
  1323. constructor(value, type, sourceSpan) {
  1324. super(type, sourceSpan);
  1325. this.value = value;
  1326. }
  1327. isEquivalent(e) {
  1328. return e instanceof CastExpr && this.value.isEquivalent(e.value);
  1329. }
  1330. isConstant() { return false; }
  1331. visitExpression(visitor, context) {
  1332. return visitor.visitCastExpr(this, context);
  1333. }
  1334. }
  1335. class FnParam {
  1336. constructor(name, type = null) {
  1337. this.name = name;
  1338. this.type = type;
  1339. }
  1340. isEquivalent(param) { return this.name === param.name; }
  1341. }
  1342. class FunctionExpr extends Expression {
  1343. constructor(params, statements, type, sourceSpan, name) {
  1344. super(type, sourceSpan);
  1345. this.params = params;
  1346. this.statements = statements;
  1347. this.name = name;
  1348. }
  1349. isEquivalent(e) {
  1350. return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
  1351. areAllEquivalent(this.statements, e.statements);
  1352. }
  1353. isConstant() { return false; }
  1354. visitExpression(visitor, context) {
  1355. return visitor.visitFunctionExpr(this, context);
  1356. }
  1357. toDeclStmt(name, modifiers = null) {
  1358. return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
  1359. }
  1360. }
  1361. class BinaryOperatorExpr extends Expression {
  1362. constructor(operator, lhs, rhs, type, sourceSpan, parens = true) {
  1363. super(type || lhs.type, sourceSpan);
  1364. this.operator = operator;
  1365. this.rhs = rhs;
  1366. this.parens = parens;
  1367. this.lhs = lhs;
  1368. }
  1369. isEquivalent(e) {
  1370. return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
  1371. this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
  1372. }
  1373. isConstant() { return false; }
  1374. visitExpression(visitor, context) {
  1375. return visitor.visitBinaryOperatorExpr(this, context);
  1376. }
  1377. }
  1378. class ReadPropExpr extends Expression {
  1379. constructor(receiver, name, type, sourceSpan) {
  1380. super(type, sourceSpan);
  1381. this.receiver = receiver;
  1382. this.name = name;
  1383. }
  1384. isEquivalent(e) {
  1385. return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
  1386. this.name === e.name;
  1387. }
  1388. isConstant() { return false; }
  1389. visitExpression(visitor, context) {
  1390. return visitor.visitReadPropExpr(this, context);
  1391. }
  1392. set(value) {
  1393. return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
  1394. }
  1395. }
  1396. class ReadKeyExpr extends Expression {
  1397. constructor(receiver, index, type, sourceSpan) {
  1398. super(type, sourceSpan);
  1399. this.receiver = receiver;
  1400. this.index = index;
  1401. }
  1402. isEquivalent(e) {
  1403. return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1404. this.index.isEquivalent(e.index);
  1405. }
  1406. isConstant() { return false; }
  1407. visitExpression(visitor, context) {
  1408. return visitor.visitReadKeyExpr(this, context);
  1409. }
  1410. set(value) {
  1411. return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
  1412. }
  1413. }
  1414. class LiteralArrayExpr extends Expression {
  1415. constructor(entries, type, sourceSpan) {
  1416. super(type, sourceSpan);
  1417. this.entries = entries;
  1418. }
  1419. isConstant() { return this.entries.every(e => e.isConstant()); }
  1420. isEquivalent(e) {
  1421. return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
  1422. }
  1423. visitExpression(visitor, context) {
  1424. return visitor.visitLiteralArrayExpr(this, context);
  1425. }
  1426. }
  1427. class LiteralMapEntry {
  1428. constructor(key, value, quoted) {
  1429. this.key = key;
  1430. this.value = value;
  1431. this.quoted = quoted;
  1432. }
  1433. isEquivalent(e) {
  1434. return this.key === e.key && this.value.isEquivalent(e.value);
  1435. }
  1436. }
  1437. class LiteralMapExpr extends Expression {
  1438. constructor(entries, type, sourceSpan) {
  1439. super(type, sourceSpan);
  1440. this.entries = entries;
  1441. this.valueType = null;
  1442. if (type) {
  1443. this.valueType = type.valueType;
  1444. }
  1445. }
  1446. isEquivalent(e) {
  1447. return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
  1448. }
  1449. isConstant() { return this.entries.every(e => e.value.isConstant()); }
  1450. visitExpression(visitor, context) {
  1451. return visitor.visitLiteralMapExpr(this, context);
  1452. }
  1453. }
  1454. class CommaExpr extends Expression {
  1455. constructor(parts, sourceSpan) {
  1456. super(parts[parts.length - 1].type, sourceSpan);
  1457. this.parts = parts;
  1458. }
  1459. isEquivalent(e) {
  1460. return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
  1461. }
  1462. isConstant() { return false; }
  1463. visitExpression(visitor, context) {
  1464. return visitor.visitCommaExpr(this, context);
  1465. }
  1466. }
  1467. const THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
  1468. const SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
  1469. const CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
  1470. const CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
  1471. const NULL_EXPR = new LiteralExpr(null, null, null);
  1472. const TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
  1473. //// Statements
  1474. var StmtModifier;
  1475. (function (StmtModifier) {
  1476. StmtModifier[StmtModifier["Final"] = 0] = "Final";
  1477. StmtModifier[StmtModifier["Private"] = 1] = "Private";
  1478. StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
  1479. StmtModifier[StmtModifier["Static"] = 3] = "Static";
  1480. })(StmtModifier || (StmtModifier = {}));
  1481. class Statement {
  1482. constructor(modifiers, sourceSpan) {
  1483. this.modifiers = modifiers || [];
  1484. this.sourceSpan = sourceSpan || null;
  1485. }
  1486. hasModifier(modifier) { return this.modifiers.indexOf(modifier) !== -1; }
  1487. }
  1488. class DeclareVarStmt extends Statement {
  1489. constructor(name, value, type, modifiers = null, sourceSpan) {
  1490. super(modifiers, sourceSpan);
  1491. this.name = name;
  1492. this.value = value;
  1493. this.type = type || (value && value.type) || null;
  1494. }
  1495. isEquivalent(stmt) {
  1496. return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
  1497. (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
  1498. }
  1499. visitStatement(visitor, context) {
  1500. return visitor.visitDeclareVarStmt(this, context);
  1501. }
  1502. }
  1503. class DeclareFunctionStmt extends Statement {
  1504. constructor(name, params, statements, type, modifiers = null, sourceSpan) {
  1505. super(modifiers, sourceSpan);
  1506. this.name = name;
  1507. this.params = params;
  1508. this.statements = statements;
  1509. this.type = type || null;
  1510. }
  1511. isEquivalent(stmt) {
  1512. return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
  1513. areAllEquivalent(this.statements, stmt.statements);
  1514. }
  1515. visitStatement(visitor, context) {
  1516. return visitor.visitDeclareFunctionStmt(this, context);
  1517. }
  1518. }
  1519. class ExpressionStatement extends Statement {
  1520. constructor(expr, sourceSpan) {
  1521. super(null, sourceSpan);
  1522. this.expr = expr;
  1523. }
  1524. isEquivalent(stmt) {
  1525. return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
  1526. }
  1527. visitStatement(visitor, context) {
  1528. return visitor.visitExpressionStmt(this, context);
  1529. }
  1530. }
  1531. class ReturnStatement extends Statement {
  1532. constructor(value, sourceSpan) {
  1533. super(null, sourceSpan);
  1534. this.value = value;
  1535. }
  1536. isEquivalent(stmt) {
  1537. return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
  1538. }
  1539. visitStatement(visitor, context) {
  1540. return visitor.visitReturnStmt(this, context);
  1541. }
  1542. }
  1543. class AbstractClassPart {
  1544. constructor(type, modifiers) {
  1545. this.modifiers = modifiers;
  1546. if (!modifiers) {
  1547. this.modifiers = [];
  1548. }
  1549. this.type = type || null;
  1550. }
  1551. hasModifier(modifier) { return this.modifiers.indexOf(modifier) !== -1; }
  1552. }
  1553. class ClassField extends AbstractClassPart {
  1554. constructor(name, type, modifiers = null, initializer) {
  1555. super(type, modifiers);
  1556. this.name = name;
  1557. this.initializer = initializer;
  1558. }
  1559. isEquivalent(f) { return this.name === f.name; }
  1560. }
  1561. class ClassMethod extends AbstractClassPart {
  1562. constructor(name, params, body, type, modifiers = null) {
  1563. super(type, modifiers);
  1564. this.name = name;
  1565. this.params = params;
  1566. this.body = body;
  1567. }
  1568. isEquivalent(m) {
  1569. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1570. }
  1571. }
  1572. class ClassGetter extends AbstractClassPart {
  1573. constructor(name, body, type, modifiers = null) {
  1574. super(type, modifiers);
  1575. this.name = name;
  1576. this.body = body;
  1577. }
  1578. isEquivalent(m) {
  1579. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1580. }
  1581. }
  1582. class ClassStmt extends Statement {
  1583. constructor(name, parent, fields, getters, constructorMethod, methods, modifiers = null, sourceSpan) {
  1584. super(modifiers, sourceSpan);
  1585. this.name = name;
  1586. this.parent = parent;
  1587. this.fields = fields;
  1588. this.getters = getters;
  1589. this.constructorMethod = constructorMethod;
  1590. this.methods = methods;
  1591. }
  1592. isEquivalent(stmt) {
  1593. return stmt instanceof ClassStmt && this.name === stmt.name &&
  1594. nullSafeIsEquivalent(this.parent, stmt.parent) &&
  1595. areAllEquivalent(this.fields, stmt.fields) &&
  1596. areAllEquivalent(this.getters, stmt.getters) &&
  1597. this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
  1598. areAllEquivalent(this.methods, stmt.methods);
  1599. }
  1600. visitStatement(visitor, context) {
  1601. return visitor.visitDeclareClassStmt(this, context);
  1602. }
  1603. }
  1604. class IfStmt extends Statement {
  1605. constructor(condition, trueCase, falseCase = [], sourceSpan) {
  1606. super(null, sourceSpan);
  1607. this.condition = condition;
  1608. this.trueCase = trueCase;
  1609. this.falseCase = falseCase;
  1610. }
  1611. isEquivalent(stmt) {
  1612. return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
  1613. areAllEquivalent(this.trueCase, stmt.trueCase) &&
  1614. areAllEquivalent(this.falseCase, stmt.falseCase);
  1615. }
  1616. visitStatement(visitor, context) {
  1617. return visitor.visitIfStmt(this, context);
  1618. }
  1619. }
  1620. class CommentStmt extends Statement {
  1621. constructor(comment, multiline = false, sourceSpan) {
  1622. super(null, sourceSpan);
  1623. this.comment = comment;
  1624. this.multiline = multiline;
  1625. }
  1626. isEquivalent(stmt) { return stmt instanceof CommentStmt; }
  1627. visitStatement(visitor, context) {
  1628. return visitor.visitCommentStmt(this, context);
  1629. }
  1630. }
  1631. class JSDocCommentStmt extends Statement {
  1632. constructor(tags = [], sourceSpan) {
  1633. super(null, sourceSpan);
  1634. this.tags = tags;
  1635. }
  1636. isEquivalent(stmt) {
  1637. return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString();
  1638. }
  1639. visitStatement(visitor, context) {
  1640. return visitor.visitJSDocCommentStmt(this, context);
  1641. }
  1642. toString() { return serializeTags(this.tags); }
  1643. }
  1644. class TryCatchStmt extends Statement {
  1645. constructor(bodyStmts, catchStmts, sourceSpan) {
  1646. super(null, sourceSpan);
  1647. this.bodyStmts = bodyStmts;
  1648. this.catchStmts = catchStmts;
  1649. }
  1650. isEquivalent(stmt) {
  1651. return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
  1652. areAllEquivalent(this.catchStmts, stmt.catchStmts);
  1653. }
  1654. visitStatement(visitor, context) {
  1655. return visitor.visitTryCatchStmt(this, context);
  1656. }
  1657. }
  1658. class ThrowStmt extends Statement {
  1659. constructor(error, sourceSpan) {
  1660. super(null, sourceSpan);
  1661. this.error = error;
  1662. }
  1663. isEquivalent(stmt) {
  1664. return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
  1665. }
  1666. visitStatement(visitor, context) {
  1667. return visitor.visitThrowStmt(this, context);
  1668. }
  1669. }
  1670. class AstTransformer {
  1671. transformExpr(expr, context) { return expr; }
  1672. transformStmt(stmt, context) { return stmt; }
  1673. visitReadVarExpr(ast, context) { return this.transformExpr(ast, context); }
  1674. visitWrappedNodeExpr(ast, context) {
  1675. return this.transformExpr(ast, context);
  1676. }
  1677. visitTypeofExpr(expr, context) {
  1678. return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1679. }
  1680. visitWriteVarExpr(expr, context) {
  1681. return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1682. }
  1683. visitWriteKeyExpr(expr, context) {
  1684. 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);
  1685. }
  1686. visitWritePropExpr(expr, context) {
  1687. return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1688. }
  1689. visitInvokeMethodExpr(ast, context) {
  1690. const method = ast.builtin || ast.name;
  1691. return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1692. }
  1693. visitInvokeFunctionExpr(ast, context) {
  1694. return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1695. }
  1696. visitInstantiateExpr(ast, context) {
  1697. return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1698. }
  1699. visitLiteralExpr(ast, context) { return this.transformExpr(ast, context); }
  1700. visitExternalExpr(ast, context) {
  1701. return this.transformExpr(ast, context);
  1702. }
  1703. visitConditionalExpr(ast, context) {
  1704. 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);
  1705. }
  1706. visitNotExpr(ast, context) {
  1707. return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1708. }
  1709. visitAssertNotNullExpr(ast, context) {
  1710. return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1711. }
  1712. visitCastExpr(ast, context) {
  1713. return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1714. }
  1715. visitFunctionExpr(ast, context) {
  1716. return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
  1717. }
  1718. visitBinaryOperatorExpr(ast, context) {
  1719. return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1720. }
  1721. visitReadPropExpr(ast, context) {
  1722. return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
  1723. }
  1724. visitReadKeyExpr(ast, context) {
  1725. return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1726. }
  1727. visitLiteralArrayExpr(ast, context) {
  1728. return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
  1729. }
  1730. visitLiteralMapExpr(ast, context) {
  1731. const entries = ast.entries.map((entry) => new LiteralMapEntry(entry.key, entry.value.visitExpression(this, context), entry.quoted));
  1732. const mapType = new MapType(ast.valueType, null);
  1733. return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
  1734. }
  1735. visitCommaExpr(ast, context) {
  1736. return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
  1737. }
  1738. visitAllExpressions(exprs, context) {
  1739. return exprs.map(expr => expr.visitExpression(this, context));
  1740. }
  1741. visitDeclareVarStmt(stmt, context) {
  1742. const value = stmt.value && stmt.value.visitExpression(this, context);
  1743. return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1744. }
  1745. visitDeclareFunctionStmt(stmt, context) {
  1746. return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1747. }
  1748. visitExpressionStmt(stmt, context) {
  1749. return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
  1750. }
  1751. visitReturnStmt(stmt, context) {
  1752. return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
  1753. }
  1754. visitDeclareClassStmt(stmt, context) {
  1755. const parent = stmt.parent.visitExpression(this, context);
  1756. const getters = stmt.getters.map(getter => new ClassGetter(getter.name, this.visitAllStatements(getter.body, context), getter.type, getter.modifiers));
  1757. const ctorMethod = stmt.constructorMethod &&
  1758. new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
  1759. const methods = stmt.methods.map(method => new ClassMethod(method.name, method.params, this.visitAllStatements(method.body, context), method.type, method.modifiers));
  1760. return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
  1761. }
  1762. visitIfStmt(stmt, context) {
  1763. return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
  1764. }
  1765. visitTryCatchStmt(stmt, context) {
  1766. return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
  1767. }
  1768. visitThrowStmt(stmt, context) {
  1769. return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
  1770. }
  1771. visitCommentStmt(stmt, context) {
  1772. return this.transformStmt(stmt, context);
  1773. }
  1774. visitJSDocCommentStmt(stmt, context) {
  1775. return this.transformStmt(stmt, context);
  1776. }
  1777. visitAllStatements(stmts, context) {
  1778. return stmts.map(stmt => stmt.visitStatement(this, context));
  1779. }
  1780. }
  1781. class RecursiveAstVisitor {
  1782. visitType(ast, context) { return ast; }
  1783. visitExpression(ast, context) {
  1784. if (ast.type) {
  1785. ast.type.visitType(this, context);
  1786. }
  1787. return ast;
  1788. }
  1789. visitBuiltinType(type, context) { return this.visitType(type, context); }
  1790. visitExpressionType(type, context) {
  1791. type.value.visitExpression(this, context);
  1792. if (type.typeParams !== null) {
  1793. type.typeParams.forEach(param => this.visitType(param, context));
  1794. }
  1795. return this.visitType(type, context);
  1796. }
  1797. visitArrayType(type, context) { return this.visitType(type, context); }
  1798. visitMapType(type, context) { return this.visitType(type, context); }
  1799. visitWrappedNodeExpr(ast, context) { return ast; }
  1800. visitTypeofExpr(ast, context) { return this.visitExpression(ast, context); }
  1801. visitReadVarExpr(ast, context) {
  1802. return this.visitExpression(ast, context);
  1803. }
  1804. visitWriteVarExpr(ast, context) {
  1805. ast.value.visitExpression(this, context);
  1806. return this.visitExpression(ast, context);
  1807. }
  1808. visitWriteKeyExpr(ast, context) {
  1809. ast.receiver.visitExpression(this, context);
  1810. ast.index.visitExpression(this, context);
  1811. ast.value.visitExpression(this, context);
  1812. return this.visitExpression(ast, context);
  1813. }
  1814. visitWritePropExpr(ast, context) {
  1815. ast.receiver.visitExpression(this, context);
  1816. ast.value.visitExpression(this, context);
  1817. return this.visitExpression(ast, context);
  1818. }
  1819. visitInvokeMethodExpr(ast, context) {
  1820. ast.receiver.visitExpression(this, context);
  1821. this.visitAllExpressions(ast.args, context);
  1822. return this.visitExpression(ast, context);
  1823. }
  1824. visitInvokeFunctionExpr(ast, context) {
  1825. ast.fn.visitExpression(this, context);
  1826. this.visitAllExpressions(ast.args, context);
  1827. return this.visitExpression(ast, context);
  1828. }
  1829. visitInstantiateExpr(ast, context) {
  1830. ast.classExpr.visitExpression(this, context);
  1831. this.visitAllExpressions(ast.args, context);
  1832. return this.visitExpression(ast, context);
  1833. }
  1834. visitLiteralExpr(ast, context) {
  1835. return this.visitExpression(ast, context);
  1836. }
  1837. visitExternalExpr(ast, context) {
  1838. if (ast.typeParams) {
  1839. ast.typeParams.forEach(type => type.visitType(this, context));
  1840. }
  1841. return this.visitExpression(ast, context);
  1842. }
  1843. visitConditionalExpr(ast, context) {
  1844. ast.condition.visitExpression(this, context);
  1845. ast.trueCase.visitExpression(this, context);
  1846. ast.falseCase.visitExpression(this, context);
  1847. return this.visitExpression(ast, context);
  1848. }
  1849. visitNotExpr(ast, context) {
  1850. ast.condition.visitExpression(this, context);
  1851. return this.visitExpression(ast, context);
  1852. }
  1853. visitAssertNotNullExpr(ast, context) {
  1854. ast.condition.visitExpression(this, context);
  1855. return this.visitExpression(ast, context);
  1856. }
  1857. visitCastExpr(ast, context) {
  1858. ast.value.visitExpression(this, context);
  1859. return this.visitExpression(ast, context);
  1860. }
  1861. visitFunctionExpr(ast, context) {
  1862. this.visitAllStatements(ast.statements, context);
  1863. return this.visitExpression(ast, context);
  1864. }
  1865. visitBinaryOperatorExpr(ast, context) {
  1866. ast.lhs.visitExpression(this, context);
  1867. ast.rhs.visitExpression(this, context);
  1868. return this.visitExpression(ast, context);
  1869. }
  1870. visitReadPropExpr(ast, context) {
  1871. ast.receiver.visitExpression(this, context);
  1872. return this.visitExpression(ast, context);
  1873. }
  1874. visitReadKeyExpr(ast, context) {
  1875. ast.receiver.visitExpression(this, context);
  1876. ast.index.visitExpression(this, context);
  1877. return this.visitExpression(ast, context);
  1878. }
  1879. visitLiteralArrayExpr(ast, context) {
  1880. this.visitAllExpressions(ast.entries, context);
  1881. return this.visitExpression(ast, context);
  1882. }
  1883. visitLiteralMapExpr(ast, context) {
  1884. ast.entries.forEach((entry) => entry.value.visitExpression(this, context));
  1885. return this.visitExpression(ast, context);
  1886. }
  1887. visitCommaExpr(ast, context) {
  1888. this.visitAllExpressions(ast.parts, context);
  1889. return this.visitExpression(ast, context);
  1890. }
  1891. visitAllExpressions(exprs, context) {
  1892. exprs.forEach(expr => expr.visitExpression(this, context));
  1893. }
  1894. visitDeclareVarStmt(stmt, context) {
  1895. if (stmt.value) {
  1896. stmt.value.visitExpression(this, context);
  1897. }
  1898. if (stmt.type) {
  1899. stmt.type.visitType(this, context);
  1900. }
  1901. return stmt;
  1902. }
  1903. visitDeclareFunctionStmt(stmt, context) {
  1904. this.visitAllStatements(stmt.statements, context);
  1905. if (stmt.type) {
  1906. stmt.type.visitType(this, context);
  1907. }
  1908. return stmt;
  1909. }
  1910. visitExpressionStmt(stmt, context) {
  1911. stmt.expr.visitExpression(this, context);
  1912. return stmt;
  1913. }
  1914. visitReturnStmt(stmt, context) {
  1915. stmt.value.visitExpression(this, context);
  1916. return stmt;
  1917. }
  1918. visitDeclareClassStmt(stmt, context) {
  1919. stmt.parent.visitExpression(this, context);
  1920. stmt.getters.forEach(getter => this.visitAllStatements(getter.body, context));
  1921. if (stmt.constructorMethod) {
  1922. this.visitAllStatements(stmt.constructorMethod.body, context);
  1923. }
  1924. stmt.methods.forEach(method => this.visitAllStatements(method.body, context));
  1925. return stmt;
  1926. }
  1927. visitIfStmt(stmt, context) {
  1928. stmt.condition.visitExpression(this, context);
  1929. this.visitAllStatements(stmt.trueCase, context);
  1930. this.visitAllStatements(stmt.falseCase, context);
  1931. return stmt;
  1932. }
  1933. visitTryCatchStmt(stmt, context) {
  1934. this.visitAllStatements(stmt.bodyStmts, context);
  1935. this.visitAllStatements(stmt.catchStmts, context);
  1936. return stmt;
  1937. }
  1938. visitThrowStmt(stmt, context) {
  1939. stmt.error.visitExpression(this, context);
  1940. return stmt;
  1941. }
  1942. visitCommentStmt(stmt, context) { return stmt; }
  1943. visitJSDocCommentStmt(stmt, context) { return stmt; }
  1944. visitAllStatements(stmts, context) {
  1945. stmts.forEach(stmt => stmt.visitStatement(this, context));
  1946. }
  1947. }
  1948. function findReadVarNames(stmts) {
  1949. const visitor = new _ReadVarVisitor();
  1950. visitor.visitAllStatements(stmts, null);
  1951. return visitor.varNames;
  1952. }
  1953. class _ReadVarVisitor extends RecursiveAstVisitor {
  1954. constructor() {
  1955. super(...arguments);
  1956. this.varNames = new Set();
  1957. }
  1958. visitDeclareFunctionStmt(stmt, context) {
  1959. // Don't descend into nested functions
  1960. return stmt;
  1961. }
  1962. visitDeclareClassStmt(stmt, context) {
  1963. // Don't descend into nested classes
  1964. return stmt;
  1965. }
  1966. visitReadVarExpr(ast, context) {
  1967. if (ast.name) {
  1968. this.varNames.add(ast.name);
  1969. }
  1970. return null;
  1971. }
  1972. }
  1973. function collectExternalReferences(stmts) {
  1974. const visitor = new _FindExternalReferencesVisitor();
  1975. visitor.visitAllStatements(stmts, null);
  1976. return visitor.externalReferences;
  1977. }
  1978. class _FindExternalReferencesVisitor extends RecursiveAstVisitor {
  1979. constructor() {
  1980. super(...arguments);
  1981. this.externalReferences = [];
  1982. }
  1983. visitExternalExpr(e, context) {
  1984. this.externalReferences.push(e.value);
  1985. return super.visitExternalExpr(e, context);
  1986. }
  1987. }
  1988. function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
  1989. if (!sourceSpan) {
  1990. return stmt;
  1991. }
  1992. const transformer = new _ApplySourceSpanTransformer(sourceSpan);
  1993. return stmt.visitStatement(transformer, null);
  1994. }
  1995. function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
  1996. if (!sourceSpan) {
  1997. return expr;
  1998. }
  1999. const transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2000. return expr.visitExpression(transformer, null);
  2001. }
  2002. class _ApplySourceSpanTransformer extends AstTransformer {
  2003. constructor(sourceSpan) {
  2004. super();
  2005. this.sourceSpan = sourceSpan;
  2006. }
  2007. _clone(obj) {
  2008. const clone = Object.create(obj.constructor.prototype);
  2009. for (let prop in obj) {
  2010. clone[prop] = obj[prop];
  2011. }
  2012. return clone;
  2013. }
  2014. transformExpr(expr, context) {
  2015. if (!expr.sourceSpan) {
  2016. expr = this._clone(expr);
  2017. expr.sourceSpan = this.sourceSpan;
  2018. }
  2019. return expr;
  2020. }
  2021. transformStmt(stmt, context) {
  2022. if (!stmt.sourceSpan) {
  2023. stmt = this._clone(stmt);
  2024. stmt.sourceSpan = this.sourceSpan;
  2025. }
  2026. return stmt;
  2027. }
  2028. }
  2029. function variable(name, type, sourceSpan) {
  2030. return new ReadVarExpr(name, type, sourceSpan);
  2031. }
  2032. function importExpr(id, typeParams = null, sourceSpan) {
  2033. return new ExternalExpr(id, null, typeParams, sourceSpan);
  2034. }
  2035. function importType(id, typeParams = null, typeModifiers = null) {
  2036. return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
  2037. }
  2038. function expressionType(expr, typeModifiers = null, typeParams = null) {
  2039. return new ExpressionType(expr, typeModifiers, typeParams);
  2040. }
  2041. function typeofExpr(expr) {
  2042. return new TypeofExpr(expr);
  2043. }
  2044. function literalArr(values, type, sourceSpan) {
  2045. return new LiteralArrayExpr(values, type, sourceSpan);
  2046. }
  2047. function literalMap(values, type = null) {
  2048. return new LiteralMapExpr(values.map(e => new LiteralMapEntry(e.key, e.value, e.quoted)), type, null);
  2049. }
  2050. function not(expr, sourceSpan) {
  2051. return new NotExpr(expr, sourceSpan);
  2052. }
  2053. function assertNotNull(expr, sourceSpan) {
  2054. return new AssertNotNull(expr, sourceSpan);
  2055. }
  2056. function fn(params, body, type, sourceSpan, name) {
  2057. return new FunctionExpr(params, body, type, sourceSpan, name);
  2058. }
  2059. function ifStmt(condition, thenClause, elseClause) {
  2060. return new IfStmt(condition, thenClause, elseClause);
  2061. }
  2062. function literal(value, type, sourceSpan) {
  2063. return new LiteralExpr(value, type, sourceSpan);
  2064. }
  2065. function isNull(exp) {
  2066. return exp instanceof LiteralExpr && exp.value === null;
  2067. }
  2068. /*
  2069. * Serializes a `Tag` into a string.
  2070. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
  2071. */
  2072. function tagToString(tag) {
  2073. let out = '';
  2074. if (tag.tagName) {
  2075. out += ` @${tag.tagName}`;
  2076. }
  2077. if (tag.text) {
  2078. if (tag.text.match(/\/\*|\*\//)) {
  2079. throw new Error('JSDoc text cannot contain "/*" and "*/"');
  2080. }
  2081. out += ' ' + tag.text.replace(/@/g, '\\@');
  2082. }
  2083. return out;
  2084. }
  2085. function serializeTags(tags) {
  2086. if (tags.length === 0)
  2087. return '';
  2088. let out = '*\n';
  2089. for (const tag of tags) {
  2090. out += ' *';
  2091. // If the tagToString is multi-line, insert " * " prefixes on subsequent lines.
  2092. out += tagToString(tag).replace(/\n/g, '\n * ');
  2093. out += '\n';
  2094. }
  2095. out += ' ';
  2096. return out;
  2097. }
  2098. /**
  2099. * @license
  2100. * Copyright Google Inc. All Rights Reserved.
  2101. *
  2102. * Use of this source code is governed by an MIT-style license that can be
  2103. * found in the LICENSE file at https://angular.io/license
  2104. */
  2105. const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
  2106. function dashCaseToCamelCase(input) {
  2107. return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
  2108. }
  2109. function splitAtColon(input, defaultValues) {
  2110. return _splitAt(input, ':', defaultValues);
  2111. }
  2112. function splitAtPeriod(input, defaultValues) {
  2113. return _splitAt(input, '.', defaultValues);
  2114. }
  2115. function _splitAt(input, character, defaultValues) {
  2116. const characterIndex = input.indexOf(character);
  2117. if (characterIndex == -1)
  2118. return defaultValues;
  2119. return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
  2120. }
  2121. function visitValue(value, visitor, context) {
  2122. if (Array.isArray(value)) {
  2123. return visitor.visitArray(value, context);
  2124. }
  2125. if (isStrictStringMap(value)) {
  2126. return visitor.visitStringMap(value, context);
  2127. }
  2128. if (value == null || typeof value == 'string' || typeof value == 'number' ||
  2129. typeof value == 'boolean') {
  2130. return visitor.visitPrimitive(value, context);
  2131. }
  2132. return visitor.visitOther(value, context);
  2133. }
  2134. function isDefined(val) {
  2135. return val !== null && val !== undefined;
  2136. }
  2137. function noUndefined(val) {
  2138. return val === undefined ? null : val;
  2139. }
  2140. class ValueTransformer {
  2141. visitArray(arr, context) {
  2142. return arr.map(value => visitValue(value, this, context));
  2143. }
  2144. visitStringMap(map, context) {
  2145. const result = {};
  2146. Object.keys(map).forEach(key => { result[key] = visitValue(map[key], this, context); });
  2147. return result;
  2148. }
  2149. visitPrimitive(value, context) { return value; }
  2150. visitOther(value, context) { return value; }
  2151. }
  2152. const SyncAsync = {
  2153. assertSync: (value) => {
  2154. if (isPromise(value)) {
  2155. throw new Error(`Illegal state: value cannot be a promise`);
  2156. }
  2157. return value;
  2158. },
  2159. then: (value, cb) => { return isPromise(value) ? value.then(cb) : cb(value); },
  2160. all: (syncAsyncValues) => {
  2161. return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
  2162. }
  2163. };
  2164. function error(msg) {
  2165. throw new Error(`Internal Error: ${msg}`);
  2166. }
  2167. function syntaxError(msg, parseErrors) {
  2168. const error = Error(msg);
  2169. error[ERROR_SYNTAX_ERROR] = true;
  2170. if (parseErrors)
  2171. error[ERROR_PARSE_ERRORS] = parseErrors;
  2172. return error;
  2173. }
  2174. const ERROR_SYNTAX_ERROR = 'ngSyntaxError';
  2175. const ERROR_PARSE_ERRORS = 'ngParseErrors';
  2176. function isSyntaxError(error) {
  2177. return error[ERROR_SYNTAX_ERROR];
  2178. }
  2179. function getParseErrors(error) {
  2180. return error[ERROR_PARSE_ERRORS] || [];
  2181. }
  2182. // Escape characters that have a special meaning in Regular Expressions
  2183. function escapeRegExp(s) {
  2184. return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  2185. }
  2186. const STRING_MAP_PROTO = Object.getPrototypeOf({});
  2187. function isStrictStringMap(obj) {
  2188. return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
  2189. }
  2190. function utf8Encode(str) {
  2191. let encoded = '';
  2192. for (let index = 0; index < str.length; index++) {
  2193. let codePoint = str.charCodeAt(index);
  2194. // decode surrogate
  2195. // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  2196. if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
  2197. const low = str.charCodeAt(index + 1);
  2198. if (low >= 0xdc00 && low <= 0xdfff) {
  2199. index++;
  2200. codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
  2201. }
  2202. }
  2203. if (codePoint <= 0x7f) {
  2204. encoded += String.fromCharCode(codePoint);
  2205. }
  2206. else if (codePoint <= 0x7ff) {
  2207. encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
  2208. }
  2209. else if (codePoint <= 0xffff) {
  2210. encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2211. }
  2212. else if (codePoint <= 0x1fffff) {
  2213. encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2214. }
  2215. }
  2216. return encoded;
  2217. }
  2218. function stringify(token) {
  2219. if (typeof token === 'string') {
  2220. return token;
  2221. }
  2222. if (token instanceof Array) {
  2223. return '[' + token.map(stringify).join(', ') + ']';
  2224. }
  2225. if (token == null) {
  2226. return '' + token;
  2227. }
  2228. if (token.overriddenName) {
  2229. return `${token.overriddenName}`;
  2230. }
  2231. if (token.name) {
  2232. return `${token.name}`;
  2233. }
  2234. if (!token.toString) {
  2235. return 'object';
  2236. }
  2237. // WARNING: do not try to `JSON.stringify(token)` here
  2238. // see https://github.com/angular/angular/issues/23440
  2239. const res = token.toString();
  2240. if (res == null) {
  2241. return '' + res;
  2242. }
  2243. const newLineIndex = res.indexOf('\n');
  2244. return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
  2245. }
  2246. /**
  2247. * Lazily retrieves the reference value from a forwardRef.
  2248. */
  2249. function resolveForwardRef(type) {
  2250. if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
  2251. return type();
  2252. }
  2253. else {
  2254. return type;
  2255. }
  2256. }
  2257. /**
  2258. * Determine if the argument is shaped like a Promise
  2259. */
  2260. function isPromise(obj) {
  2261. // allow any Promise/A+ compliant thenable.
  2262. // It's up to the caller to ensure that obj.then conforms to the spec
  2263. return !!obj && typeof obj.then === 'function';
  2264. }
  2265. class Version {
  2266. constructor(full) {
  2267. this.full = full;
  2268. const splits = full.split('.');
  2269. this.major = splits[0];
  2270. this.minor = splits[1];
  2271. this.patch = splits.slice(2).join('.');
  2272. }
  2273. }
  2274. const __window = typeof window !== 'undefined' && window;
  2275. const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  2276. self instanceof WorkerGlobalScope && self;
  2277. const __global = typeof global !== 'undefined' && global;
  2278. // Check __global first, because in Node tests both __global and __window may be defined and _global
  2279. // should be __global in that case.
  2280. const _global = __global || __window || __self;
  2281. /**
  2282. * @license
  2283. * Copyright Google Inc. All Rights Reserved.
  2284. *
  2285. * Use of this source code is governed by an MIT-style license that can be
  2286. * found in the LICENSE file at https://angular.io/license
  2287. */
  2288. const CONSTANT_PREFIX = '_c';
  2289. /**
  2290. * Context to use when producing a key.
  2291. *
  2292. * This ensures we see the constant not the reference variable when producing
  2293. * a key.
  2294. */
  2295. const KEY_CONTEXT = {};
  2296. /**
  2297. * A node that is a place-holder that allows the node to be replaced when the actual
  2298. * node is known.
  2299. *
  2300. * This allows the constant pool to change an expression from a direct reference to
  2301. * a constant to a shared constant. It returns a fix-up node that is later allowed to
  2302. * change the referenced expression.
  2303. */
  2304. class FixupExpression extends Expression {
  2305. constructor(resolved) {
  2306. super(resolved.type);
  2307. this.resolved = resolved;
  2308. this.original = resolved;
  2309. }
  2310. visitExpression(visitor, context) {
  2311. if (context === KEY_CONTEXT) {
  2312. // When producing a key we want to traverse the constant not the
  2313. // variable used to refer to it.
  2314. return this.original.visitExpression(visitor, context);
  2315. }
  2316. else {
  2317. return this.resolved.visitExpression(visitor, context);
  2318. }
  2319. }
  2320. isEquivalent(e) {
  2321. return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
  2322. }
  2323. isConstant() { return true; }
  2324. fixup(expression) {
  2325. this.resolved = expression;
  2326. this.shared = true;
  2327. }
  2328. }
  2329. /**
  2330. * A constant pool allows a code emitter to share constant in an output context.
  2331. *
  2332. * The constant pool also supports sharing access to ivy definitions references.
  2333. */
  2334. class ConstantPool {
  2335. constructor() {
  2336. this.statements = [];
  2337. this.literals = new Map();
  2338. this.literalFactories = new Map();
  2339. this.injectorDefinitions = new Map();
  2340. this.directiveDefinitions = new Map();
  2341. this.componentDefinitions = new Map();
  2342. this.pipeDefinitions = new Map();
  2343. this.nextNameIndex = 0;
  2344. }
  2345. getConstLiteral(literal, forceShared) {
  2346. if (literal instanceof LiteralExpr || literal instanceof FixupExpression) {
  2347. // Do no put simple literals into the constant pool or try to produce a constant for a
  2348. // reference to a constant.
  2349. return literal;
  2350. }
  2351. const key = this.keyOf(literal);
  2352. let fixup = this.literals.get(key);
  2353. let newValue = false;
  2354. if (!fixup) {
  2355. fixup = new FixupExpression(literal);
  2356. this.literals.set(key, fixup);
  2357. newValue = true;
  2358. }
  2359. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2360. // Replace the expression with a variable
  2361. const name = this.freshName();
  2362. this.statements.push(variable(name).set(literal).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
  2363. fixup.fixup(variable(name));
  2364. }
  2365. return fixup;
  2366. }
  2367. getDefinition(type, kind, ctx, forceShared = false) {
  2368. const definitions = this.definitionsOf(kind);
  2369. let fixup = definitions.get(type);
  2370. let newValue = false;
  2371. if (!fixup) {
  2372. const property = this.propertyNameOf(kind);
  2373. fixup = new FixupExpression(ctx.importExpr(type).prop(property));
  2374. definitions.set(type, fixup);
  2375. newValue = true;
  2376. }
  2377. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2378. const name = this.freshName();
  2379. this.statements.push(variable(name).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
  2380. fixup.fixup(variable(name));
  2381. }
  2382. return fixup;
  2383. }
  2384. getLiteralFactory(literal$1) {
  2385. // Create a pure function that builds an array of a mix of constant and variable expressions
  2386. if (literal$1 instanceof LiteralArrayExpr) {
  2387. const argumentsForKey = literal$1.entries.map(e => e.isConstant() ? e : literal(null));
  2388. const key = this.keyOf(literalArr(argumentsForKey));
  2389. return this._getLiteralFactory(key, literal$1.entries, entries => literalArr(entries));
  2390. }
  2391. else {
  2392. const expressionForKey = literalMap(literal$1.entries.map(e => ({
  2393. key: e.key,
  2394. value: e.value.isConstant() ? e.value : literal(null),
  2395. quoted: e.quoted
  2396. })));
  2397. const key = this.keyOf(expressionForKey);
  2398. return this._getLiteralFactory(key, literal$1.entries.map(e => e.value), entries => literalMap(entries.map((value, index) => ({
  2399. key: literal$1.entries[index].key,
  2400. value,
  2401. quoted: literal$1.entries[index].quoted
  2402. }))));
  2403. }
  2404. }
  2405. _getLiteralFactory(key, values, resultMap) {
  2406. let literalFactory = this.literalFactories.get(key);
  2407. const literalFactoryArguments = values.filter((e => !e.isConstant()));
  2408. if (!literalFactory) {
  2409. const resultExpressions = values.map((e, index) => e.isConstant() ? this.getConstLiteral(e, true) : variable(`a${index}`));
  2410. const parameters = resultExpressions.filter(isVariable).map(e => new FnParam(e.name, DYNAMIC_TYPE));
  2411. const pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
  2412. const name = this.freshName();
  2413. this.statements.push(variable(name).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
  2414. StmtModifier.Final
  2415. ]));
  2416. literalFactory = variable(name);
  2417. this.literalFactories.set(key, literalFactory);
  2418. }
  2419. return { literalFactory, literalFactoryArguments };
  2420. }
  2421. /**
  2422. * Produce a unique name.
  2423. *
  2424. * The name might be unique among different prefixes if any of the prefixes end in
  2425. * a digit so the prefix should be a constant string (not based on user input) and
  2426. * must not end in a digit.
  2427. */
  2428. uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }
  2429. definitionsOf(kind) {
  2430. switch (kind) {
  2431. case 2 /* Component */:
  2432. return this.componentDefinitions;
  2433. case 1 /* Directive */:
  2434. return this.directiveDefinitions;
  2435. case 0 /* Injector */:
  2436. return this.injectorDefinitions;
  2437. case 3 /* Pipe */:
  2438. return this.pipeDefinitions;
  2439. }
  2440. error(`Unknown definition kind ${kind}`);
  2441. return this.componentDefinitions;
  2442. }
  2443. propertyNameOf(kind) {
  2444. switch (kind) {
  2445. case 2 /* Component */:
  2446. return 'ngComponentDef';
  2447. case 1 /* Directive */:
  2448. return 'ngDirectiveDef';
  2449. case 0 /* Injector */:
  2450. return 'ngInjectorDef';
  2451. case 3 /* Pipe */:
  2452. return 'ngPipeDef';
  2453. }
  2454. error(`Unknown definition kind ${kind}`);
  2455. return '<unknown>';
  2456. }
  2457. freshName() { return this.uniqueName(CONSTANT_PREFIX); }
  2458. keyOf(expression) {
  2459. return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
  2460. }
  2461. }
  2462. /**
  2463. * Visitor used to determine if 2 expressions are equivalent and can be shared in the
  2464. * `ConstantPool`.
  2465. *
  2466. * When the id (string) generated by the visitor is equal, expressions are considered equivalent.
  2467. */
  2468. class KeyVisitor {
  2469. constructor() {
  2470. this.visitWrappedNodeExpr = invalid;
  2471. this.visitWriteVarExpr = invalid;
  2472. this.visitWriteKeyExpr = invalid;
  2473. this.visitWritePropExpr = invalid;
  2474. this.visitInvokeMethodExpr = invalid;
  2475. this.visitInvokeFunctionExpr = invalid;
  2476. this.visitInstantiateExpr = invalid;
  2477. this.visitConditionalExpr = invalid;
  2478. this.visitNotExpr = invalid;
  2479. this.visitAssertNotNullExpr = invalid;
  2480. this.visitCastExpr = invalid;
  2481. this.visitFunctionExpr = invalid;
  2482. this.visitBinaryOperatorExpr = invalid;
  2483. this.visitReadPropExpr = invalid;
  2484. this.visitReadKeyExpr = invalid;
  2485. this.visitCommaExpr = invalid;
  2486. }
  2487. visitLiteralExpr(ast) {
  2488. return `${typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value}`;
  2489. }
  2490. visitLiteralArrayExpr(ast, context) {
  2491. return `[${ast.entries.map(entry => entry.visitExpression(this, context)).join(',')}]`;
  2492. }
  2493. visitLiteralMapExpr(ast, context) {
  2494. const mapKey = (entry) => {
  2495. const quote = entry.quoted ? '"' : '';
  2496. return `${quote}${entry.key}${quote}`;
  2497. };
  2498. const mapEntry = (entry) => `${mapKey(entry)}:${entry.value.visitExpression(this, context)}`;
  2499. return `{${ast.entries.map(mapEntry).join(',')}`;
  2500. }
  2501. visitExternalExpr(ast) {
  2502. return ast.value.moduleName ? `EX:${ast.value.moduleName}:${ast.value.name}` :
  2503. `EX:${ast.value.runtime.name}`;
  2504. }
  2505. visitReadVarExpr(node) { return `VAR:${node.name}`; }
  2506. visitTypeofExpr(node, context) {
  2507. return `TYPEOF:${node.expr.visitExpression(this, context)}`;
  2508. }
  2509. }
  2510. function invalid(arg) {
  2511. throw new Error(`Invalid state: Visitor ${this.constructor.name} doesn't handle ${arg.constructor.name}`);
  2512. }
  2513. function isVariable(e) {
  2514. return e instanceof ReadVarExpr;
  2515. }
  2516. /**
  2517. * @license
  2518. * Copyright Google Inc. All Rights Reserved.
  2519. *
  2520. * Use of this source code is governed by an MIT-style license that can be
  2521. * found in the LICENSE file at https://angular.io/license
  2522. */
  2523. const CORE = '@angular/core';
  2524. class Identifiers {
  2525. }
  2526. Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
  2527. name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
  2528. moduleName: CORE,
  2529. };
  2530. Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE };
  2531. Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE };
  2532. Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE };
  2533. Identifiers.ChangeDetectorRef = {
  2534. name: 'ChangeDetectorRef',
  2535. moduleName: CORE,
  2536. };
  2537. Identifiers.QueryList = { name: 'QueryList', moduleName: CORE };
  2538. Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE };
  2539. Identifiers.Renderer2 = { name: 'Renderer2', moduleName: CORE };
  2540. Identifiers.CodegenComponentFactoryResolver = {
  2541. name: 'ɵCodegenComponentFactoryResolver',
  2542. moduleName: CORE,
  2543. };
  2544. Identifiers.ComponentFactoryResolver = {
  2545. name: 'ComponentFactoryResolver',
  2546. moduleName: CORE,
  2547. };
  2548. Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE };
  2549. Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE };
  2550. Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE };
  2551. Identifiers.createModuleFactory = {
  2552. name: 'ɵcmf',
  2553. moduleName: CORE,
  2554. };
  2555. Identifiers.moduleDef = {
  2556. name: 'ɵmod',
  2557. moduleName: CORE,
  2558. };
  2559. Identifiers.moduleProviderDef = {
  2560. name: 'ɵmpd',
  2561. moduleName: CORE,
  2562. };
  2563. Identifiers.RegisterModuleFactoryFn = {
  2564. name: 'ɵregisterModuleFactory',
  2565. moduleName: CORE,
  2566. };
  2567. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE };
  2568. Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
  2569. Identifiers.Injector = { name: 'Injector', moduleName: CORE };
  2570. Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
  2571. Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', moduleName: CORE };
  2572. Identifiers.ViewEncapsulation = {
  2573. name: 'ViewEncapsulation',
  2574. moduleName: CORE,
  2575. };
  2576. Identifiers.ChangeDetectionStrategy = {
  2577. name: 'ChangeDetectionStrategy',
  2578. moduleName: CORE,
  2579. };
  2580. Identifiers.SecurityContext = {
  2581. name: 'SecurityContext',
  2582. moduleName: CORE,
  2583. };
  2584. Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE };
  2585. Identifiers.TRANSLATIONS_FORMAT = {
  2586. name: 'TRANSLATIONS_FORMAT',
  2587. moduleName: CORE,
  2588. };
  2589. Identifiers.inlineInterpolate = {
  2590. name: 'ɵinlineInterpolate',
  2591. moduleName: CORE,
  2592. };
  2593. Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE };
  2594. Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE };
  2595. Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE };
  2596. Identifiers.Renderer = { name: 'Renderer', moduleName: CORE };
  2597. Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE };
  2598. Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE };
  2599. Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE };
  2600. Identifiers.textDef = { name: 'ɵted', moduleName: CORE };
  2601. Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE };
  2602. Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE };
  2603. Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE };
  2604. Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE };
  2605. Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE };
  2606. Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE };
  2607. Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE };
  2608. Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE };
  2609. Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE };
  2610. Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE };
  2611. Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE };
  2612. // type only
  2613. Identifiers.RendererType2 = {
  2614. name: 'RendererType2',
  2615. moduleName: CORE,
  2616. };
  2617. // type only
  2618. Identifiers.ViewDefinition = {
  2619. name: 'ɵViewDefinition',
  2620. moduleName: CORE,
  2621. };
  2622. Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE };
  2623. Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
  2624. function createTokenForReference(reference) {
  2625. return { identifier: { reference: reference } };
  2626. }
  2627. function createTokenForExternalReference(reflector, reference) {
  2628. return createTokenForReference(reflector.resolveExternalReference(reference));
  2629. }
  2630. /**
  2631. * @license
  2632. * Copyright Google Inc. All Rights Reserved.
  2633. *
  2634. * Use of this source code is governed by an MIT-style license that can be
  2635. * found in the LICENSE file at https://angular.io/license
  2636. */
  2637. /**
  2638. * A token representing the a reference to a static type.
  2639. *
  2640. * This token is unique for a filePath and name and can be used as a hash table key.
  2641. */
  2642. class StaticSymbol {
  2643. constructor(filePath, name, members) {
  2644. this.filePath = filePath;
  2645. this.name = name;
  2646. this.members = members;
  2647. }
  2648. assertNoMembers() {
  2649. if (this.members.length) {
  2650. throw new Error(`Illegal state: symbol without members expected, but got ${JSON.stringify(this)}.`);
  2651. }
  2652. }
  2653. }
  2654. /**
  2655. * A cache of static symbol used by the StaticReflector to return the same symbol for the
  2656. * same symbol values.
  2657. */
  2658. class StaticSymbolCache {
  2659. constructor() {
  2660. this.cache = new Map();
  2661. }
  2662. get(declarationFile, name, members) {
  2663. members = members || [];
  2664. const memberSuffix = members.length ? `.${members.join('.')}` : '';
  2665. const key = `"${declarationFile}".${name}${memberSuffix}`;
  2666. let result = this.cache.get(key);
  2667. if (!result) {
  2668. result = new StaticSymbol(declarationFile, name, members);
  2669. this.cache.set(key, result);
  2670. }
  2671. return result;
  2672. }
  2673. }
  2674. /**
  2675. * @license
  2676. * Copyright Google Inc. All Rights Reserved.
  2677. *
  2678. * Use of this source code is governed by an MIT-style license that can be
  2679. * found in the LICENSE file at https://angular.io/license
  2680. */
  2681. // group 0: "[prop] or (event) or @trigger"
  2682. // group 1: "prop" from "[prop]"
  2683. // group 2: "event" from "(event)"
  2684. // group 3: "@trigger" from "@trigger"
  2685. const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
  2686. function sanitizeIdentifier(name) {
  2687. return name.replace(/\W/g, '_');
  2688. }
  2689. let _anonymousTypeIndex = 0;
  2690. function identifierName(compileIdentifier) {
  2691. if (!compileIdentifier || !compileIdentifier.reference) {
  2692. return null;
  2693. }
  2694. const ref = compileIdentifier.reference;
  2695. if (ref instanceof StaticSymbol) {
  2696. return ref.name;
  2697. }
  2698. if (ref['__anonymousType']) {
  2699. return ref['__anonymousType'];
  2700. }
  2701. let identifier = stringify(ref);
  2702. if (identifier.indexOf('(') >= 0) {
  2703. // case: anonymous functions!
  2704. identifier = `anonymous_${_anonymousTypeIndex++}`;
  2705. ref['__anonymousType'] = identifier;
  2706. }
  2707. else {
  2708. identifier = sanitizeIdentifier(identifier);
  2709. }
  2710. return identifier;
  2711. }
  2712. function identifierModuleUrl(compileIdentifier) {
  2713. const ref = compileIdentifier.reference;
  2714. if (ref instanceof StaticSymbol) {
  2715. return ref.filePath;
  2716. }
  2717. // Runtime type
  2718. return `./${stringify(ref)}`;
  2719. }
  2720. function viewClassName(compType, embeddedTemplateIndex) {
  2721. return `View_${identifierName({ reference: compType })}_${embeddedTemplateIndex}`;
  2722. }
  2723. function rendererTypeName(compType) {
  2724. return `RenderType_${identifierName({ reference: compType })}`;
  2725. }
  2726. function hostViewClassName(compType) {
  2727. return `HostView_${identifierName({ reference: compType })}`;
  2728. }
  2729. function componentFactoryName(compType) {
  2730. return `${identifierName({ reference: compType })}NgFactory`;
  2731. }
  2732. var CompileSummaryKind;
  2733. (function (CompileSummaryKind) {
  2734. CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
  2735. CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
  2736. CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
  2737. CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
  2738. })(CompileSummaryKind || (CompileSummaryKind = {}));
  2739. function tokenName(token) {
  2740. return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
  2741. }
  2742. function tokenReference(token) {
  2743. if (token.identifier != null) {
  2744. return token.identifier.reference;
  2745. }
  2746. else {
  2747. return token.value;
  2748. }
  2749. }
  2750. /**
  2751. * Metadata about a stylesheet
  2752. */
  2753. class CompileStylesheetMetadata {
  2754. constructor({ moduleUrl, styles, styleUrls } = {}) {
  2755. this.moduleUrl = moduleUrl || null;
  2756. this.styles = _normalizeArray(styles);
  2757. this.styleUrls = _normalizeArray(styleUrls);
  2758. }
  2759. }
  2760. /**
  2761. * Metadata regarding compilation of a template.
  2762. */
  2763. class CompileTemplateMetadata {
  2764. constructor({ encapsulation, template, templateUrl, htmlAst, styles, styleUrls, externalStylesheets, animations, ngContentSelectors, interpolation, isInline, preserveWhitespaces }) {
  2765. this.encapsulation = encapsulation;
  2766. this.template = template;
  2767. this.templateUrl = templateUrl;
  2768. this.htmlAst = htmlAst;
  2769. this.styles = _normalizeArray(styles);
  2770. this.styleUrls = _normalizeArray(styleUrls);
  2771. this.externalStylesheets = _normalizeArray(externalStylesheets);
  2772. this.animations = animations ? flatten(animations) : [];
  2773. this.ngContentSelectors = ngContentSelectors || [];
  2774. if (interpolation && interpolation.length != 2) {
  2775. throw new Error(`'interpolation' should have a start and an end symbol.`);
  2776. }
  2777. this.interpolation = interpolation;
  2778. this.isInline = isInline;
  2779. this.preserveWhitespaces = preserveWhitespaces;
  2780. }
  2781. toSummary() {
  2782. return {
  2783. ngContentSelectors: this.ngContentSelectors,
  2784. encapsulation: this.encapsulation,
  2785. styles: this.styles,
  2786. animations: this.animations
  2787. };
  2788. }
  2789. }
  2790. /**
  2791. * Metadata regarding compilation of a directive.
  2792. */
  2793. class CompileDirectiveMetadata {
  2794. static create({ isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, host, providers, viewProviders, queries, guards, viewQueries, entryComponents, template, componentViewType, rendererType, componentFactory }) {
  2795. const hostListeners = {};
  2796. const hostProperties = {};
  2797. const hostAttributes = {};
  2798. if (host != null) {
  2799. Object.keys(host).forEach(key => {
  2800. const value = host[key];
  2801. const matches = key.match(HOST_REG_EXP);
  2802. if (matches === null) {
  2803. hostAttributes[key] = value;
  2804. }
  2805. else if (matches[1] != null) {
  2806. hostProperties[matches[1]] = value;
  2807. }
  2808. else if (matches[2] != null) {
  2809. hostListeners[matches[2]] = value;
  2810. }
  2811. });
  2812. }
  2813. const inputsMap = {};
  2814. if (inputs != null) {
  2815. inputs.forEach((bindConfig) => {
  2816. // canonical syntax: `dirProp: elProp`
  2817. // if there is no `:`, use dirProp = elProp
  2818. const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  2819. inputsMap[parts[0]] = parts[1];
  2820. });
  2821. }
  2822. const outputsMap = {};
  2823. if (outputs != null) {
  2824. outputs.forEach((bindConfig) => {
  2825. // canonical syntax: `dirProp: elProp`
  2826. // if there is no `:`, use dirProp = elProp
  2827. const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  2828. outputsMap[parts[0]] = parts[1];
  2829. });
  2830. }
  2831. return new CompileDirectiveMetadata({
  2832. isHost,
  2833. type,
  2834. isComponent: !!isComponent, selector, exportAs, changeDetection,
  2835. inputs: inputsMap,
  2836. outputs: outputsMap,
  2837. hostListeners,
  2838. hostProperties,
  2839. hostAttributes,
  2840. providers,
  2841. viewProviders,
  2842. queries,
  2843. guards,
  2844. viewQueries,
  2845. entryComponents,
  2846. template,
  2847. componentViewType,
  2848. rendererType,
  2849. componentFactory,
  2850. });
  2851. }
  2852. constructor({ isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, hostListeners, hostProperties, hostAttributes, providers, viewProviders, queries, guards, viewQueries, entryComponents, template, componentViewType, rendererType, componentFactory }) {
  2853. this.isHost = !!isHost;
  2854. this.type = type;
  2855. this.isComponent = isComponent;
  2856. this.selector = selector;
  2857. this.exportAs = exportAs;
  2858. this.changeDetection = changeDetection;
  2859. this.inputs = inputs;
  2860. this.outputs = outputs;
  2861. this.hostListeners = hostListeners;
  2862. this.hostProperties = hostProperties;
  2863. this.hostAttributes = hostAttributes;
  2864. this.providers = _normalizeArray(providers);
  2865. this.viewProviders = _normalizeArray(viewProviders);
  2866. this.queries = _normalizeArray(queries);
  2867. this.guards = guards;
  2868. this.viewQueries = _normalizeArray(viewQueries);
  2869. this.entryComponents = _normalizeArray(entryComponents);
  2870. this.template = template;
  2871. this.componentViewType = componentViewType;
  2872. this.rendererType = rendererType;
  2873. this.componentFactory = componentFactory;
  2874. }
  2875. toSummary() {
  2876. return {
  2877. summaryKind: CompileSummaryKind.Directive,
  2878. type: this.type,
  2879. isComponent: this.isComponent,
  2880. selector: this.selector,
  2881. exportAs: this.exportAs,
  2882. inputs: this.inputs,
  2883. outputs: this.outputs,
  2884. hostListeners: this.hostListeners,
  2885. hostProperties: this.hostProperties,
  2886. hostAttributes: this.hostAttributes,
  2887. providers: this.providers,
  2888. viewProviders: this.viewProviders,
  2889. queries: this.queries,
  2890. guards: this.guards,
  2891. viewQueries: this.viewQueries,
  2892. entryComponents: this.entryComponents,
  2893. changeDetection: this.changeDetection,
  2894. template: this.template && this.template.toSummary(),
  2895. componentViewType: this.componentViewType,
  2896. rendererType: this.rendererType,
  2897. componentFactory: this.componentFactory
  2898. };
  2899. }
  2900. }
  2901. class CompilePipeMetadata {
  2902. constructor({ type, name, pure }) {
  2903. this.type = type;
  2904. this.name = name;
  2905. this.pure = !!pure;
  2906. }
  2907. toSummary() {
  2908. return {
  2909. summaryKind: CompileSummaryKind.Pipe,
  2910. type: this.type,
  2911. name: this.name,
  2912. pure: this.pure
  2913. };
  2914. }
  2915. }
  2916. class CompileShallowModuleMetadata {
  2917. }
  2918. /**
  2919. * Metadata regarding compilation of a module.
  2920. */
  2921. class CompileNgModuleMetadata {
  2922. constructor({ type, providers, declaredDirectives, exportedDirectives, declaredPipes, exportedPipes, entryComponents, bootstrapComponents, importedModules, exportedModules, schemas, transitiveModule, id }) {
  2923. this.type = type || null;
  2924. this.declaredDirectives = _normalizeArray(declaredDirectives);
  2925. this.exportedDirectives = _normalizeArray(exportedDirectives);
  2926. this.declaredPipes = _normalizeArray(declaredPipes);
  2927. this.exportedPipes = _normalizeArray(exportedPipes);
  2928. this.providers = _normalizeArray(providers);
  2929. this.entryComponents = _normalizeArray(entryComponents);
  2930. this.bootstrapComponents = _normalizeArray(bootstrapComponents);
  2931. this.importedModules = _normalizeArray(importedModules);
  2932. this.exportedModules = _normalizeArray(exportedModules);
  2933. this.schemas = _normalizeArray(schemas);
  2934. this.id = id || null;
  2935. this.transitiveModule = transitiveModule || null;
  2936. }
  2937. toSummary() {
  2938. const module = this.transitiveModule;
  2939. return {
  2940. summaryKind: CompileSummaryKind.NgModule,
  2941. type: this.type,
  2942. entryComponents: module.entryComponents,
  2943. providers: module.providers,
  2944. modules: module.modules,
  2945. exportedDirectives: module.exportedDirectives,
  2946. exportedPipes: module.exportedPipes
  2947. };
  2948. }
  2949. }
  2950. class TransitiveCompileNgModuleMetadata {
  2951. constructor() {
  2952. this.directivesSet = new Set();
  2953. this.directives = [];
  2954. this.exportedDirectivesSet = new Set();
  2955. this.exportedDirectives = [];
  2956. this.pipesSet = new Set();
  2957. this.pipes = [];
  2958. this.exportedPipesSet = new Set();
  2959. this.exportedPipes = [];
  2960. this.modulesSet = new Set();
  2961. this.modules = [];
  2962. this.entryComponentsSet = new Set();
  2963. this.entryComponents = [];
  2964. this.providers = [];
  2965. }
  2966. addProvider(provider, module) {
  2967. this.providers.push({ provider: provider, module: module });
  2968. }
  2969. addDirective(id) {
  2970. if (!this.directivesSet.has(id.reference)) {
  2971. this.directivesSet.add(id.reference);
  2972. this.directives.push(id);
  2973. }
  2974. }
  2975. addExportedDirective(id) {
  2976. if (!this.exportedDirectivesSet.has(id.reference)) {
  2977. this.exportedDirectivesSet.add(id.reference);
  2978. this.exportedDirectives.push(id);
  2979. }
  2980. }
  2981. addPipe(id) {
  2982. if (!this.pipesSet.has(id.reference)) {
  2983. this.pipesSet.add(id.reference);
  2984. this.pipes.push(id);
  2985. }
  2986. }
  2987. addExportedPipe(id) {
  2988. if (!this.exportedPipesSet.has(id.reference)) {
  2989. this.exportedPipesSet.add(id.reference);
  2990. this.exportedPipes.push(id);
  2991. }
  2992. }
  2993. addModule(id) {
  2994. if (!this.modulesSet.has(id.reference)) {
  2995. this.modulesSet.add(id.reference);
  2996. this.modules.push(id);
  2997. }
  2998. }
  2999. addEntryComponent(ec) {
  3000. if (!this.entryComponentsSet.has(ec.componentType)) {
  3001. this.entryComponentsSet.add(ec.componentType);
  3002. this.entryComponents.push(ec);
  3003. }
  3004. }
  3005. }
  3006. function _normalizeArray(obj) {
  3007. return obj || [];
  3008. }
  3009. class ProviderMeta {
  3010. constructor(token, { useClass, useValue, useExisting, useFactory, deps, multi }) {
  3011. this.token = token;
  3012. this.useClass = useClass || null;
  3013. this.useValue = useValue;
  3014. this.useExisting = useExisting;
  3015. this.useFactory = useFactory || null;
  3016. this.dependencies = deps || null;
  3017. this.multi = !!multi;
  3018. }
  3019. }
  3020. function flatten(list) {
  3021. return list.reduce((flat, item) => {
  3022. const flatItem = Array.isArray(item) ? flatten(item) : item;
  3023. return flat.concat(flatItem);
  3024. }, []);
  3025. }
  3026. function jitSourceUrl(url) {
  3027. // Note: We need 3 "/" so that ng shows up as a separate domain
  3028. // in the chrome dev tools.
  3029. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
  3030. }
  3031. function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
  3032. let url;
  3033. if (templateMeta.isInline) {
  3034. if (compMeta.type.reference instanceof StaticSymbol) {
  3035. // Note: a .ts file might contain multiple components with inline templates,
  3036. // so we need to give them unique urls, as these will be used for sourcemaps.
  3037. url = `${compMeta.type.reference.filePath}.${compMeta.type.reference.name}.html`;
  3038. }
  3039. else {
  3040. url = `${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.html`;
  3041. }
  3042. }
  3043. else {
  3044. url = templateMeta.templateUrl;
  3045. }
  3046. return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
  3047. }
  3048. function sharedStylesheetJitUrl(meta, id) {
  3049. const pathParts = meta.moduleUrl.split(/\/\\/g);
  3050. const baseName = pathParts[pathParts.length - 1];
  3051. return jitSourceUrl(`css/${id}${baseName}.ngstyle.js`);
  3052. }
  3053. function ngModuleJitUrl(moduleMeta) {
  3054. return jitSourceUrl(`${identifierName(moduleMeta.type)}/module.ngfactory.js`);
  3055. }
  3056. function templateJitUrl(ngModuleType, compMeta) {
  3057. return jitSourceUrl(`${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.ngfactory.js`);
  3058. }
  3059. /**
  3060. * @license
  3061. * Copyright Google Inc. All Rights Reserved.
  3062. *
  3063. * Use of this source code is governed by an MIT-style license that can be
  3064. * found in the LICENSE file at https://angular.io/license
  3065. */
  3066. const CORE$1 = '@angular/core';
  3067. class Identifiers$1 {
  3068. }
  3069. /* Methods */
  3070. Identifiers$1.NEW_METHOD = 'factory';
  3071. Identifiers$1.TRANSFORM_METHOD = 'transform';
  3072. Identifiers$1.PATCH_DEPS = 'patchedDeps';
  3073. /* Instructions */
  3074. Identifiers$1.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 };
  3075. Identifiers$1.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 };
  3076. Identifiers$1.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 };
  3077. Identifiers$1.element = { name: 'ɵɵelement', moduleName: CORE$1 };
  3078. Identifiers$1.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 };
  3079. Identifiers$1.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 };
  3080. Identifiers$1.select = { name: 'ɵɵselect', moduleName: CORE$1 };
  3081. Identifiers$1.updateSyntheticHostBinding = { name: 'ɵɵupdateSyntheticHostBinding', moduleName: CORE$1 };
  3082. Identifiers$1.componentHostSyntheticListener = { name: 'ɵɵcomponentHostSyntheticListener', moduleName: CORE$1 };
  3083. Identifiers$1.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 };
  3084. Identifiers$1.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 };
  3085. Identifiers$1.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 };
  3086. Identifiers$1.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 };
  3087. Identifiers$1.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 };
  3088. Identifiers$1.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 };
  3089. Identifiers$1.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 };
  3090. Identifiers$1.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 };
  3091. Identifiers$1.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 };
  3092. Identifiers$1.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 };
  3093. Identifiers$1.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 };
  3094. Identifiers$1.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 };
  3095. Identifiers$1.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 };
  3096. Identifiers$1.styling = { name: 'ɵɵstyling', moduleName: CORE$1 };
  3097. Identifiers$1.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 };
  3098. Identifiers$1.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 };
  3099. Identifiers$1.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 };
  3100. Identifiers$1.stylingApply = { name: 'ɵɵstylingApply', moduleName: CORE$1 };
  3101. Identifiers$1.styleSanitizer = { name: 'ɵɵstyleSanitizer', moduleName: CORE$1 };
  3102. Identifiers$1.elementHostAttrs = { name: 'ɵɵelementHostAttrs', moduleName: CORE$1 };
  3103. Identifiers$1.containerCreate = { name: 'ɵɵcontainer', moduleName: CORE$1 };
  3104. Identifiers$1.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 };
  3105. Identifiers$1.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 };
  3106. Identifiers$1.text = { name: 'ɵɵtext', moduleName: CORE$1 };
  3107. Identifiers$1.textBinding = { name: 'ɵɵtextBinding', moduleName: CORE$1 };
  3108. Identifiers$1.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 };
  3109. Identifiers$1.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 };
  3110. Identifiers$1.allocHostVars = { name: 'ɵɵallocHostVars', moduleName: CORE$1 };
  3111. Identifiers$1.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 };
  3112. Identifiers$1.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 };
  3113. Identifiers$1.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 };
  3114. Identifiers$1.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 };
  3115. Identifiers$1.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 };
  3116. Identifiers$1.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 };
  3117. Identifiers$1.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 };
  3118. Identifiers$1.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 };
  3119. Identifiers$1.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 };
  3120. Identifiers$1.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 };
  3121. Identifiers$1.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 };
  3122. Identifiers$1.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 };
  3123. Identifiers$1.interpolation1 = { name: 'ɵɵinterpolation1', moduleName: CORE$1 };
  3124. Identifiers$1.interpolation2 = { name: 'ɵɵinterpolation2', moduleName: CORE$1 };
  3125. Identifiers$1.interpolation3 = { name: 'ɵɵinterpolation3', moduleName: CORE$1 };
  3126. Identifiers$1.interpolation4 = { name: 'ɵɵinterpolation4', moduleName: CORE$1 };
  3127. Identifiers$1.interpolation5 = { name: 'ɵɵinterpolation5', moduleName: CORE$1 };
  3128. Identifiers$1.interpolation6 = { name: 'ɵɵinterpolation6', moduleName: CORE$1 };
  3129. Identifiers$1.interpolation7 = { name: 'ɵɵinterpolation7', moduleName: CORE$1 };
  3130. Identifiers$1.interpolation8 = { name: 'ɵɵinterpolation8', moduleName: CORE$1 };
  3131. Identifiers$1.interpolationV = { name: 'ɵɵinterpolationV', moduleName: CORE$1 };
  3132. Identifiers$1.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 };
  3133. Identifiers$1.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 };
  3134. Identifiers$1.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 };
  3135. Identifiers$1.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 };
  3136. Identifiers$1.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 };
  3137. Identifiers$1.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 };
  3138. Identifiers$1.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 };
  3139. Identifiers$1.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 };
  3140. Identifiers$1.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 };
  3141. Identifiers$1.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 };
  3142. Identifiers$1.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 };
  3143. Identifiers$1.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 };
  3144. Identifiers$1.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 };
  3145. Identifiers$1.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 };
  3146. Identifiers$1.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 };
  3147. Identifiers$1.property = { name: 'ɵɵproperty', moduleName: CORE$1 };
  3148. Identifiers$1.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 };
  3149. Identifiers$1.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 };
  3150. Identifiers$1.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 };
  3151. Identifiers$1.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 };
  3152. Identifiers$1.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 };
  3153. Identifiers$1.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 };
  3154. Identifiers$1.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 };
  3155. Identifiers$1.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 };
  3156. Identifiers$1.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 };
  3157. Identifiers$1.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 };
  3158. Identifiers$1.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 };
  3159. Identifiers$1.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 };
  3160. Identifiers$1.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 };
  3161. Identifiers$1.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 };
  3162. Identifiers$1.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 };
  3163. Identifiers$1.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 };
  3164. Identifiers$1.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 };
  3165. Identifiers$1.i18nLocalize = { name: 'ɵɵi18nLocalize', moduleName: CORE$1 };
  3166. Identifiers$1.load = { name: 'ɵɵload', moduleName: CORE$1 };
  3167. Identifiers$1.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 };
  3168. Identifiers$1.projection = { name: 'ɵɵprojection', moduleName: CORE$1 };
  3169. Identifiers$1.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 };
  3170. Identifiers$1.reference = { name: 'ɵɵreference', moduleName: CORE$1 };
  3171. Identifiers$1.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
  3172. Identifiers$1.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 };
  3173. Identifiers$1.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
  3174. Identifiers$1.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 };
  3175. Identifiers$1.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 };
  3176. Identifiers$1.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 };
  3177. Identifiers$1.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 };
  3178. Identifiers$1.defineBase = { name: 'ɵɵdefineBase', moduleName: CORE$1 };
  3179. Identifiers$1.BaseDef = {
  3180. name: 'ɵɵBaseDef',
  3181. moduleName: CORE$1,
  3182. };
  3183. Identifiers$1.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 };
  3184. Identifiers$1.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 };
  3185. Identifiers$1.ComponentDefWithMeta = {
  3186. name: 'ɵɵComponentDefWithMeta',
  3187. moduleName: CORE$1,
  3188. };
  3189. Identifiers$1.defineDirective = {
  3190. name: 'ɵɵdefineDirective',
  3191. moduleName: CORE$1,
  3192. };
  3193. Identifiers$1.DirectiveDefWithMeta = {
  3194. name: 'ɵɵDirectiveDefWithMeta',
  3195. moduleName: CORE$1,
  3196. };
  3197. Identifiers$1.InjectorDef = {
  3198. name: 'ɵɵInjectorDef',
  3199. moduleName: CORE$1,
  3200. };
  3201. Identifiers$1.defineInjector = {
  3202. name: 'ɵɵdefineInjector',
  3203. moduleName: CORE$1,
  3204. };
  3205. Identifiers$1.NgModuleDefWithMeta = {
  3206. name: 'ɵɵNgModuleDefWithMeta',
  3207. moduleName: CORE$1,
  3208. };
  3209. Identifiers$1.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 };
  3210. Identifiers$1.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 };
  3211. Identifiers$1.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 };
  3212. Identifiers$1.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 };
  3213. Identifiers$1.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 };
  3214. Identifiers$1.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 };
  3215. Identifiers$1.staticViewQuery = { name: 'ɵɵstaticViewQuery', moduleName: CORE$1 };
  3216. Identifiers$1.staticContentQuery = { name: 'ɵɵstaticContentQuery', moduleName: CORE$1 };
  3217. Identifiers$1.loadViewQuery = { name: 'ɵɵloadViewQuery', moduleName: CORE$1 };
  3218. Identifiers$1.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 };
  3219. Identifiers$1.loadContentQuery = { name: 'ɵɵloadContentQuery', moduleName: CORE$1 };
  3220. Identifiers$1.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 };
  3221. Identifiers$1.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 };
  3222. Identifiers$1.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 };
  3223. Identifiers$1.listener = { name: 'ɵɵlistener', moduleName: CORE$1 };
  3224. Identifiers$1.getFactoryOf = {
  3225. name: 'ɵɵgetFactoryOf',
  3226. moduleName: CORE$1,
  3227. };
  3228. Identifiers$1.getInheritedFactory = {
  3229. name: 'ɵɵgetInheritedFactory',
  3230. moduleName: CORE$1,
  3231. };
  3232. // sanitization-related functions
  3233. Identifiers$1.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 };
  3234. Identifiers$1.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 };
  3235. Identifiers$1.defaultStyleSanitizer = { name: 'ɵɵdefaultStyleSanitizer', moduleName: CORE$1 };
  3236. Identifiers$1.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 };
  3237. Identifiers$1.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 };
  3238. Identifiers$1.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 };
  3239. Identifiers$1.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 };
  3240. /**
  3241. * @license
  3242. * Copyright Google Inc. All Rights Reserved.
  3243. *
  3244. * Use of this source code is governed by an MIT-style license that can be
  3245. * found in the LICENSE file at https://angular.io/license
  3246. */
  3247. const $EOF = 0;
  3248. const $BSPACE = 8;
  3249. const $TAB = 9;
  3250. const $LF = 10;
  3251. const $VTAB = 11;
  3252. const $FF = 12;
  3253. const $CR = 13;
  3254. const $SPACE = 32;
  3255. const $BANG = 33;
  3256. const $DQ = 34;
  3257. const $HASH = 35;
  3258. const $$ = 36;
  3259. const $PERCENT = 37;
  3260. const $AMPERSAND = 38;
  3261. const $SQ = 39;
  3262. const $LPAREN = 40;
  3263. const $RPAREN = 41;
  3264. const $STAR = 42;
  3265. const $PLUS = 43;
  3266. const $COMMA = 44;
  3267. const $MINUS = 45;
  3268. const $PERIOD = 46;
  3269. const $SLASH = 47;
  3270. const $COLON = 58;
  3271. const $SEMICOLON = 59;
  3272. const $LT = 60;
  3273. const $EQ = 61;
  3274. const $GT = 62;
  3275. const $QUESTION = 63;
  3276. const $0 = 48;
  3277. const $7 = 55;
  3278. const $9 = 57;
  3279. const $A = 65;
  3280. const $E = 69;
  3281. const $F = 70;
  3282. const $X = 88;
  3283. const $Z = 90;
  3284. const $LBRACKET = 91;
  3285. const $BACKSLASH = 92;
  3286. const $RBRACKET = 93;
  3287. const $CARET = 94;
  3288. const $_ = 95;
  3289. const $a = 97;
  3290. const $b = 98;
  3291. const $e = 101;
  3292. const $f = 102;
  3293. const $n = 110;
  3294. const $r = 114;
  3295. const $t = 116;
  3296. const $u = 117;
  3297. const $v = 118;
  3298. const $x = 120;
  3299. const $z = 122;
  3300. const $LBRACE = 123;
  3301. const $BAR = 124;
  3302. const $RBRACE = 125;
  3303. const $NBSP = 160;
  3304. const $BT = 96;
  3305. function isWhitespace(code) {
  3306. return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
  3307. }
  3308. function isDigit(code) {
  3309. return $0 <= code && code <= $9;
  3310. }
  3311. function isAsciiLetter(code) {
  3312. return code >= $a && code <= $z || code >= $A && code <= $Z;
  3313. }
  3314. function isAsciiHexDigit(code) {
  3315. return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
  3316. }
  3317. function isNewLine(code) {
  3318. return code === $LF || code === $CR;
  3319. }
  3320. function isOctalDigit(code) {
  3321. return $0 <= code && code <= $7;
  3322. }
  3323. /**
  3324. * @license
  3325. * Copyright Google Inc. All Rights Reserved.
  3326. *
  3327. * Use of this source code is governed by an MIT-style license that can be
  3328. * found in the LICENSE file at https://angular.io/license
  3329. */
  3330. class ParseLocation {
  3331. constructor(file, offset, line, col) {
  3332. this.file = file;
  3333. this.offset = offset;
  3334. this.line = line;
  3335. this.col = col;
  3336. }
  3337. toString() {
  3338. return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
  3339. }
  3340. moveBy(delta) {
  3341. const source = this.file.content;
  3342. const len = source.length;
  3343. let offset = this.offset;
  3344. let line = this.line;
  3345. let col = this.col;
  3346. while (offset > 0 && delta < 0) {
  3347. offset--;
  3348. delta++;
  3349. const ch = source.charCodeAt(offset);
  3350. if (ch == $LF) {
  3351. line--;
  3352. const priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
  3353. col = priorLine > 0 ? offset - priorLine : offset;
  3354. }
  3355. else {
  3356. col--;
  3357. }
  3358. }
  3359. while (offset < len && delta > 0) {
  3360. const ch = source.charCodeAt(offset);
  3361. offset++;
  3362. delta--;
  3363. if (ch == $LF) {
  3364. line++;
  3365. col = 0;
  3366. }
  3367. else {
  3368. col++;
  3369. }
  3370. }
  3371. return new ParseLocation(this.file, offset, line, col);
  3372. }
  3373. // Return the source around the location
  3374. // Up to `maxChars` or `maxLines` on each side of the location
  3375. getContext(maxChars, maxLines) {
  3376. const content = this.file.content;
  3377. let startOffset = this.offset;
  3378. if (startOffset != null) {
  3379. if (startOffset > content.length - 1) {
  3380. startOffset = content.length - 1;
  3381. }
  3382. let endOffset = startOffset;
  3383. let ctxChars = 0;
  3384. let ctxLines = 0;
  3385. while (ctxChars < maxChars && startOffset > 0) {
  3386. startOffset--;
  3387. ctxChars++;
  3388. if (content[startOffset] == '\n') {
  3389. if (++ctxLines == maxLines) {
  3390. break;
  3391. }
  3392. }
  3393. }
  3394. ctxChars = 0;
  3395. ctxLines = 0;
  3396. while (ctxChars < maxChars && endOffset < content.length - 1) {
  3397. endOffset++;
  3398. ctxChars++;
  3399. if (content[endOffset] == '\n') {
  3400. if (++ctxLines == maxLines) {
  3401. break;
  3402. }
  3403. }
  3404. }
  3405. return {
  3406. before: content.substring(startOffset, this.offset),
  3407. after: content.substring(this.offset, endOffset + 1),
  3408. };
  3409. }
  3410. return null;
  3411. }
  3412. }
  3413. class ParseSourceFile {
  3414. constructor(content, url) {
  3415. this.content = content;
  3416. this.url = url;
  3417. }
  3418. }
  3419. class ParseSourceSpan {
  3420. constructor(start, end, details = null) {
  3421. this.start = start;
  3422. this.end = end;
  3423. this.details = details;
  3424. }
  3425. toString() {
  3426. return this.start.file.content.substring(this.start.offset, this.end.offset);
  3427. }
  3428. }
  3429. var ParseErrorLevel;
  3430. (function (ParseErrorLevel) {
  3431. ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
  3432. ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
  3433. })(ParseErrorLevel || (ParseErrorLevel = {}));
  3434. class ParseError {
  3435. constructor(span, msg, level = ParseErrorLevel.ERROR) {
  3436. this.span = span;
  3437. this.msg = msg;
  3438. this.level = level;
  3439. }
  3440. contextualMessage() {
  3441. const ctx = this.span.start.getContext(100, 3);
  3442. return ctx ? `${this.msg} ("${ctx.before}[${ParseErrorLevel[this.level]} ->]${ctx.after}")` :
  3443. this.msg;
  3444. }
  3445. toString() {
  3446. const details = this.span.details ? `, ${this.span.details}` : '';
  3447. return `${this.contextualMessage()}: ${this.span.start}${details}`;
  3448. }
  3449. }
  3450. function typeSourceSpan(kind, type) {
  3451. const moduleUrl = identifierModuleUrl(type);
  3452. const sourceFileName = moduleUrl != null ? `in ${kind} ${identifierName(type)} in ${moduleUrl}` :
  3453. `in ${kind} ${identifierName(type)}`;
  3454. const sourceFile = new ParseSourceFile('', sourceFileName);
  3455. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3456. }
  3457. /**
  3458. * Generates Source Span object for a given R3 Type for JIT mode.
  3459. *
  3460. * @param kind Component or Directive.
  3461. * @param typeName name of the Component or Directive.
  3462. * @param sourceUrl reference to Component or Directive source.
  3463. * @returns instance of ParseSourceSpan that represent a given Component or Directive.
  3464. */
  3465. function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
  3466. const sourceFileName = `in ${kind} ${typeName} in ${sourceUrl}`;
  3467. const sourceFile = new ParseSourceFile('', sourceFileName);
  3468. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3469. }
  3470. /**
  3471. * @license
  3472. * Copyright Google Inc. All Rights Reserved.
  3473. *
  3474. * Use of this source code is governed by an MIT-style license that can be
  3475. * found in the LICENSE file at https://angular.io/license
  3476. */
  3477. class Text {
  3478. constructor(value, sourceSpan) {
  3479. this.value = value;
  3480. this.sourceSpan = sourceSpan;
  3481. }
  3482. visit(visitor) { return visitor.visitText(this); }
  3483. }
  3484. class BoundText {
  3485. constructor(value, sourceSpan, i18n) {
  3486. this.value = value;
  3487. this.sourceSpan = sourceSpan;
  3488. this.i18n = i18n;
  3489. }
  3490. visit(visitor) { return visitor.visitBoundText(this); }
  3491. }
  3492. class TextAttribute {
  3493. constructor(name, value, sourceSpan, valueSpan, i18n) {
  3494. this.name = name;
  3495. this.value = value;
  3496. this.sourceSpan = sourceSpan;
  3497. this.valueSpan = valueSpan;
  3498. this.i18n = i18n;
  3499. }
  3500. visit(visitor) { return visitor.visitTextAttribute(this); }
  3501. }
  3502. class BoundAttribute {
  3503. constructor(name, type, securityContext, value, unit, sourceSpan, i18n) {
  3504. this.name = name;
  3505. this.type = type;
  3506. this.securityContext = securityContext;
  3507. this.value = value;
  3508. this.unit = unit;
  3509. this.sourceSpan = sourceSpan;
  3510. this.i18n = i18n;
  3511. }
  3512. static fromBoundElementProperty(prop, i18n) {
  3513. return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, i18n);
  3514. }
  3515. visit(visitor) { return visitor.visitBoundAttribute(this); }
  3516. }
  3517. class BoundEvent {
  3518. constructor(name, type, handler, target, phase, sourceSpan, handlerSpan) {
  3519. this.name = name;
  3520. this.type = type;
  3521. this.handler = handler;
  3522. this.target = target;
  3523. this.phase = phase;
  3524. this.sourceSpan = sourceSpan;
  3525. this.handlerSpan = handlerSpan;
  3526. }
  3527. static fromParsedEvent(event) {
  3528. const target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  3529. const phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  3530. return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan);
  3531. }
  3532. visit(visitor) { return visitor.visitBoundEvent(this); }
  3533. }
  3534. class Element {
  3535. constructor(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3536. this.name = name;
  3537. this.attributes = attributes;
  3538. this.inputs = inputs;
  3539. this.outputs = outputs;
  3540. this.children = children;
  3541. this.references = references;
  3542. this.sourceSpan = sourceSpan;
  3543. this.startSourceSpan = startSourceSpan;
  3544. this.endSourceSpan = endSourceSpan;
  3545. this.i18n = i18n;
  3546. // If the element is empty then the source span should include any closing tag
  3547. if (children.length === 0 && startSourceSpan && endSourceSpan) {
  3548. this.sourceSpan = new ParseSourceSpan(sourceSpan.start, endSourceSpan.end);
  3549. }
  3550. }
  3551. visit(visitor) { return visitor.visitElement(this); }
  3552. }
  3553. class Template {
  3554. constructor(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3555. this.tagName = tagName;
  3556. this.attributes = attributes;
  3557. this.inputs = inputs;
  3558. this.outputs = outputs;
  3559. this.templateAttrs = templateAttrs;
  3560. this.children = children;
  3561. this.references = references;
  3562. this.variables = variables;
  3563. this.sourceSpan = sourceSpan;
  3564. this.startSourceSpan = startSourceSpan;
  3565. this.endSourceSpan = endSourceSpan;
  3566. this.i18n = i18n;
  3567. }
  3568. visit(visitor) { return visitor.visitTemplate(this); }
  3569. }
  3570. class Content {
  3571. constructor(selector, attributes, sourceSpan, i18n) {
  3572. this.selector = selector;
  3573. this.attributes = attributes;
  3574. this.sourceSpan = sourceSpan;
  3575. this.i18n = i18n;
  3576. }
  3577. visit(visitor) { return visitor.visitContent(this); }
  3578. }
  3579. class Variable {
  3580. constructor(name, value, sourceSpan) {
  3581. this.name = name;
  3582. this.value = value;
  3583. this.sourceSpan = sourceSpan;
  3584. }
  3585. visit(visitor) { return visitor.visitVariable(this); }
  3586. }
  3587. class Reference {
  3588. constructor(name, value, sourceSpan) {
  3589. this.name = name;
  3590. this.value = value;
  3591. this.sourceSpan = sourceSpan;
  3592. }
  3593. visit(visitor) { return visitor.visitReference(this); }
  3594. }
  3595. class Icu {
  3596. constructor(vars, placeholders, sourceSpan, i18n) {
  3597. this.vars = vars;
  3598. this.placeholders = placeholders;
  3599. this.sourceSpan = sourceSpan;
  3600. this.i18n = i18n;
  3601. }
  3602. visit(visitor) { return visitor.visitIcu(this); }
  3603. }
  3604. function visitAll(visitor, nodes) {
  3605. const result = [];
  3606. if (visitor.visit) {
  3607. for (const node of nodes) {
  3608. const newNode = visitor.visit(node) || node.visit(visitor);
  3609. }
  3610. }
  3611. else {
  3612. for (const node of nodes) {
  3613. const newNode = node.visit(visitor);
  3614. if (newNode) {
  3615. result.push(newNode);
  3616. }
  3617. }
  3618. }
  3619. return result;
  3620. }
  3621. /**
  3622. * @license
  3623. * Copyright Google Inc. All Rights Reserved.
  3624. *
  3625. * Use of this source code is governed by an MIT-style license that can be
  3626. * found in the LICENSE file at https://angular.io/license
  3627. */
  3628. class Message {
  3629. /**
  3630. * @param nodes message AST
  3631. * @param placeholders maps placeholder names to static content
  3632. * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
  3633. * @param meaning
  3634. * @param description
  3635. * @param id
  3636. */
  3637. constructor(nodes, placeholders, placeholderToMessage, meaning, description, id) {
  3638. this.nodes = nodes;
  3639. this.placeholders = placeholders;
  3640. this.placeholderToMessage = placeholderToMessage;
  3641. this.meaning = meaning;
  3642. this.description = description;
  3643. this.id = id;
  3644. if (nodes.length) {
  3645. this.sources = [{
  3646. filePath: nodes[0].sourceSpan.start.file.url,
  3647. startLine: nodes[0].sourceSpan.start.line + 1,
  3648. startCol: nodes[0].sourceSpan.start.col + 1,
  3649. endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
  3650. endCol: nodes[0].sourceSpan.start.col + 1
  3651. }];
  3652. }
  3653. else {
  3654. this.sources = [];
  3655. }
  3656. }
  3657. }
  3658. class Text$1 {
  3659. constructor(value, sourceSpan) {
  3660. this.value = value;
  3661. this.sourceSpan = sourceSpan;
  3662. }
  3663. visit(visitor, context) { return visitor.visitText(this, context); }
  3664. }
  3665. // TODO(vicb): do we really need this node (vs an array) ?
  3666. class Container {
  3667. constructor(children, sourceSpan) {
  3668. this.children = children;
  3669. this.sourceSpan = sourceSpan;
  3670. }
  3671. visit(visitor, context) { return visitor.visitContainer(this, context); }
  3672. }
  3673. class Icu$1 {
  3674. constructor(expression, type, cases, sourceSpan) {
  3675. this.expression = expression;
  3676. this.type = type;
  3677. this.cases = cases;
  3678. this.sourceSpan = sourceSpan;
  3679. }
  3680. visit(visitor, context) { return visitor.visitIcu(this, context); }
  3681. }
  3682. class TagPlaceholder {
  3683. constructor(tag, attrs, startName, closeName, children, isVoid, sourceSpan) {
  3684. this.tag = tag;
  3685. this.attrs = attrs;
  3686. this.startName = startName;
  3687. this.closeName = closeName;
  3688. this.children = children;
  3689. this.isVoid = isVoid;
  3690. this.sourceSpan = sourceSpan;
  3691. }
  3692. visit(visitor, context) { return visitor.visitTagPlaceholder(this, context); }
  3693. }
  3694. class Placeholder {
  3695. constructor(value, name, sourceSpan) {
  3696. this.value = value;
  3697. this.name = name;
  3698. this.sourceSpan = sourceSpan;
  3699. }
  3700. visit(visitor, context) { return visitor.visitPlaceholder(this, context); }
  3701. }
  3702. class IcuPlaceholder {
  3703. constructor(value, name, sourceSpan) {
  3704. this.value = value;
  3705. this.name = name;
  3706. this.sourceSpan = sourceSpan;
  3707. }
  3708. visit(visitor, context) { return visitor.visitIcuPlaceholder(this, context); }
  3709. }
  3710. // Clone the AST
  3711. class CloneVisitor {
  3712. visitText(text, context) { return new Text$1(text.value, text.sourceSpan); }
  3713. visitContainer(container, context) {
  3714. const children = container.children.map(n => n.visit(this, context));
  3715. return new Container(children, container.sourceSpan);
  3716. }
  3717. visitIcu(icu, context) {
  3718. const cases = {};
  3719. Object.keys(icu.cases).forEach(key => cases[key] = icu.cases[key].visit(this, context));
  3720. const msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
  3721. msg.expressionPlaceholder = icu.expressionPlaceholder;
  3722. return msg;
  3723. }
  3724. visitTagPlaceholder(ph, context) {
  3725. const children = ph.children.map(n => n.visit(this, context));
  3726. return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan);
  3727. }
  3728. visitPlaceholder(ph, context) {
  3729. return new Placeholder(ph.value, ph.name, ph.sourceSpan);
  3730. }
  3731. visitIcuPlaceholder(ph, context) {
  3732. return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
  3733. }
  3734. }
  3735. // Visit all the nodes recursively
  3736. class RecurseVisitor {
  3737. visitText(text, context) { }
  3738. visitContainer(container, context) {
  3739. container.children.forEach(child => child.visit(this));
  3740. }
  3741. visitIcu(icu, context) {
  3742. Object.keys(icu.cases).forEach(k => { icu.cases[k].visit(this); });
  3743. }
  3744. visitTagPlaceholder(ph, context) {
  3745. ph.children.forEach(child => child.visit(this));
  3746. }
  3747. visitPlaceholder(ph, context) { }
  3748. visitIcuPlaceholder(ph, context) { }
  3749. }
  3750. /**
  3751. * @license
  3752. * Copyright Google Inc. All Rights Reserved.
  3753. *
  3754. * Use of this source code is governed by an MIT-style license that can be
  3755. * found in the LICENSE file at https://angular.io/license
  3756. */
  3757. function digest(message) {
  3758. return message.id || sha1(serializeNodes(message.nodes).join('') + `[${message.meaning}]`);
  3759. }
  3760. function decimalDigest(message) {
  3761. if (message.id) {
  3762. return message.id;
  3763. }
  3764. const visitor = new _SerializerIgnoreIcuExpVisitor();
  3765. const parts = message.nodes.map(a => a.visit(visitor, null));
  3766. return computeMsgId(parts.join(''), message.meaning);
  3767. }
  3768. /**
  3769. * Serialize the i18n ast to something xml-like in order to generate an UID.
  3770. *
  3771. * The visitor is also used in the i18n parser tests
  3772. *
  3773. * @internal
  3774. */
  3775. class _SerializerVisitor {
  3776. visitText(text, context) { return text.value; }
  3777. visitContainer(container, context) {
  3778. return `[${container.children.map(child => child.visit(this)).join(', ')}]`;
  3779. }
  3780. visitIcu(icu, context) {
  3781. const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
  3782. return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
  3783. }
  3784. visitTagPlaceholder(ph, context) {
  3785. return ph.isVoid ?
  3786. `<ph tag name="${ph.startName}"/>` :
  3787. `<ph tag name="${ph.startName}">${ph.children.map(child => child.visit(this)).join(', ')}</ph name="${ph.closeName}">`;
  3788. }
  3789. visitPlaceholder(ph, context) {
  3790. return ph.value ? `<ph name="${ph.name}">${ph.value}</ph>` : `<ph name="${ph.name}"/>`;
  3791. }
  3792. visitIcuPlaceholder(ph, context) {
  3793. return `<ph icu name="${ph.name}">${ph.value.visit(this)}</ph>`;
  3794. }
  3795. }
  3796. const serializerVisitor = new _SerializerVisitor();
  3797. function serializeNodes(nodes) {
  3798. return nodes.map(a => a.visit(serializerVisitor, null));
  3799. }
  3800. /**
  3801. * Serialize the i18n ast to something xml-like in order to generate an UID.
  3802. *
  3803. * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
  3804. *
  3805. * @internal
  3806. */
  3807. class _SerializerIgnoreIcuExpVisitor extends _SerializerVisitor {
  3808. visitIcu(icu, context) {
  3809. let strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
  3810. // Do not take the expression into account
  3811. return `{${icu.type}, ${strCases.join(', ')}}`;
  3812. }
  3813. }
  3814. /**
  3815. * Compute the SHA1 of the given string
  3816. *
  3817. * see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
  3818. *
  3819. * WARNING: this function has not been designed not tested with security in mind.
  3820. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
  3821. */
  3822. function sha1(str) {
  3823. const utf8 = utf8Encode(str);
  3824. const words32 = stringToWords32(utf8, Endian.Big);
  3825. const len = utf8.length * 8;
  3826. const w = new Array(80);
  3827. let [a, b, c, d, e] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  3828. words32[len >> 5] |= 0x80 << (24 - len % 32);
  3829. words32[((len + 64 >> 9) << 4) + 15] = len;
  3830. for (let i = 0; i < words32.length; i += 16) {
  3831. const [h0, h1, h2, h3, h4] = [a, b, c, d, e];
  3832. for (let j = 0; j < 80; j++) {
  3833. if (j < 16) {
  3834. w[j] = words32[i + j];
  3835. }
  3836. else {
  3837. w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  3838. }
  3839. const [f, k] = fk(j, b, c, d);
  3840. const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
  3841. [e, d, c, b, a] = [d, c, rol32(b, 30), a, temp];
  3842. }
  3843. [a, b, c, d, e] = [add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)];
  3844. }
  3845. return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
  3846. }
  3847. function fk(index, b, c, d) {
  3848. if (index < 20) {
  3849. return [(b & c) | (~b & d), 0x5a827999];
  3850. }
  3851. if (index < 40) {
  3852. return [b ^ c ^ d, 0x6ed9eba1];
  3853. }
  3854. if (index < 60) {
  3855. return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
  3856. }
  3857. return [b ^ c ^ d, 0xca62c1d6];
  3858. }
  3859. /**
  3860. * Compute the fingerprint of the given string
  3861. *
  3862. * The output is 64 bit number encoded as a decimal string
  3863. *
  3864. * based on:
  3865. * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
  3866. */
  3867. function fingerprint(str) {
  3868. const utf8 = utf8Encode(str);
  3869. let [hi, lo] = [hash32(utf8, 0), hash32(utf8, 102072)];
  3870. if (hi == 0 && (lo == 0 || lo == 1)) {
  3871. hi = hi ^ 0x130f9bef;
  3872. lo = lo ^ -0x6b5f56d8;
  3873. }
  3874. return [hi, lo];
  3875. }
  3876. function computeMsgId(msg, meaning) {
  3877. let [hi, lo] = fingerprint(msg);
  3878. if (meaning) {
  3879. const [him, lom] = fingerprint(meaning);
  3880. [hi, lo] = add64(rol64([hi, lo], 1), [him, lom]);
  3881. }
  3882. return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
  3883. }
  3884. function hash32(str, c) {
  3885. let [a, b] = [0x9e3779b9, 0x9e3779b9];
  3886. let i;
  3887. const len = str.length;
  3888. for (i = 0; i + 12 <= len; i += 12) {
  3889. a = add32(a, wordAt(str, i, Endian.Little));
  3890. b = add32(b, wordAt(str, i + 4, Endian.Little));
  3891. c = add32(c, wordAt(str, i + 8, Endian.Little));
  3892. [a, b, c] = mix([a, b, c]);
  3893. }
  3894. a = add32(a, wordAt(str, i, Endian.Little));
  3895. b = add32(b, wordAt(str, i + 4, Endian.Little));
  3896. // the first byte of c is reserved for the length
  3897. c = add32(c, len);
  3898. c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
  3899. return mix([a, b, c])[2];
  3900. }
  3901. // clang-format off
  3902. function mix([a, b, c]) {
  3903. a = sub32(a, b);
  3904. a = sub32(a, c);
  3905. a ^= c >>> 13;
  3906. b = sub32(b, c);
  3907. b = sub32(b, a);
  3908. b ^= a << 8;
  3909. c = sub32(c, a);
  3910. c = sub32(c, b);
  3911. c ^= b >>> 13;
  3912. a = sub32(a, b);
  3913. a = sub32(a, c);
  3914. a ^= c >>> 12;
  3915. b = sub32(b, c);
  3916. b = sub32(b, a);
  3917. b ^= a << 16;
  3918. c = sub32(c, a);
  3919. c = sub32(c, b);
  3920. c ^= b >>> 5;
  3921. a = sub32(a, b);
  3922. a = sub32(a, c);
  3923. a ^= c >>> 3;
  3924. b = sub32(b, c);
  3925. b = sub32(b, a);
  3926. b ^= a << 10;
  3927. c = sub32(c, a);
  3928. c = sub32(c, b);
  3929. c ^= b >>> 15;
  3930. return [a, b, c];
  3931. }
  3932. // clang-format on
  3933. // Utils
  3934. var Endian;
  3935. (function (Endian) {
  3936. Endian[Endian["Little"] = 0] = "Little";
  3937. Endian[Endian["Big"] = 1] = "Big";
  3938. })(Endian || (Endian = {}));
  3939. function add32(a, b) {
  3940. return add32to64(a, b)[1];
  3941. }
  3942. function add32to64(a, b) {
  3943. const low = (a & 0xffff) + (b & 0xffff);
  3944. const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
  3945. return [high >>> 16, (high << 16) | (low & 0xffff)];
  3946. }
  3947. function add64([ah, al], [bh, bl]) {
  3948. const [carry, l] = add32to64(al, bl);
  3949. const h = add32(add32(ah, bh), carry);
  3950. return [h, l];
  3951. }
  3952. function sub32(a, b) {
  3953. const low = (a & 0xffff) - (b & 0xffff);
  3954. const high = (a >> 16) - (b >> 16) + (low >> 16);
  3955. return (high << 16) | (low & 0xffff);
  3956. }
  3957. // Rotate a 32b number left `count` position
  3958. function rol32(a, count) {
  3959. return (a << count) | (a >>> (32 - count));
  3960. }
  3961. // Rotate a 64b number left `count` position
  3962. function rol64([hi, lo], count) {
  3963. const h = (hi << count) | (lo >>> (32 - count));
  3964. const l = (lo << count) | (hi >>> (32 - count));
  3965. return [h, l];
  3966. }
  3967. function stringToWords32(str, endian) {
  3968. const words32 = Array((str.length + 3) >>> 2);
  3969. for (let i = 0; i < words32.length; i++) {
  3970. words32[i] = wordAt(str, i * 4, endian);
  3971. }
  3972. return words32;
  3973. }
  3974. function byteAt(str, index) {
  3975. return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
  3976. }
  3977. function wordAt(str, index, endian) {
  3978. let word = 0;
  3979. if (endian === Endian.Big) {
  3980. for (let i = 0; i < 4; i++) {
  3981. word += byteAt(str, index + i) << (24 - 8 * i);
  3982. }
  3983. }
  3984. else {
  3985. for (let i = 0; i < 4; i++) {
  3986. word += byteAt(str, index + i) << 8 * i;
  3987. }
  3988. }
  3989. return word;
  3990. }
  3991. function words32ToByteString(words32) {
  3992. return words32.reduce((str, word) => str + word32ToByteString(word), '');
  3993. }
  3994. function word32ToByteString(word) {
  3995. let str = '';
  3996. for (let i = 0; i < 4; i++) {
  3997. str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
  3998. }
  3999. return str;
  4000. }
  4001. function byteStringToHexString(str) {
  4002. let hex = '';
  4003. for (let i = 0; i < str.length; i++) {
  4004. const b = byteAt(str, i);
  4005. hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
  4006. }
  4007. return hex.toLowerCase();
  4008. }
  4009. // based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b)
  4010. function byteStringToDecString(str) {
  4011. let decimal = '';
  4012. let toThePower = '1';
  4013. for (let i = str.length - 1; i >= 0; i--) {
  4014. decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
  4015. toThePower = numberTimesBigInt(256, toThePower);
  4016. }
  4017. return decimal.split('').reverse().join('');
  4018. }
  4019. // x and y decimal, lowest significant digit first
  4020. function addBigInt(x, y) {
  4021. let sum = '';
  4022. const len = Math.max(x.length, y.length);
  4023. for (let i = 0, carry = 0; i < len || carry; i++) {
  4024. const tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
  4025. if (tmpSum >= 10) {
  4026. carry = 1;
  4027. sum += tmpSum - 10;
  4028. }
  4029. else {
  4030. carry = 0;
  4031. sum += tmpSum;
  4032. }
  4033. }
  4034. return sum;
  4035. }
  4036. function numberTimesBigInt(num, b) {
  4037. let product = '';
  4038. let bToThePower = b;
  4039. for (; num !== 0; num = num >>> 1) {
  4040. if (num & 1)
  4041. product = addBigInt(product, bToThePower);
  4042. bToThePower = addBigInt(bToThePower, bToThePower);
  4043. }
  4044. return product;
  4045. }
  4046. /**
  4047. * @license
  4048. * Copyright Google Inc. All Rights Reserved.
  4049. *
  4050. * Use of this source code is governed by an MIT-style license that can be
  4051. * found in the LICENSE file at https://angular.io/license
  4052. */
  4053. class Serializer {
  4054. // Creates a name mapper, see `PlaceholderMapper`
  4055. // Returning `null` means that no name mapping is used.
  4056. createNameMapper(message) { return null; }
  4057. }
  4058. /**
  4059. * A simple mapper that take a function to transform an internal name to a public name
  4060. */
  4061. class SimplePlaceholderMapper extends RecurseVisitor {
  4062. // create a mapping from the message
  4063. constructor(message, mapName) {
  4064. super();
  4065. this.mapName = mapName;
  4066. this.internalToPublic = {};
  4067. this.publicToNextId = {};
  4068. this.publicToInternal = {};
  4069. message.nodes.forEach(node => node.visit(this));
  4070. }
  4071. toPublicName(internalName) {
  4072. return this.internalToPublic.hasOwnProperty(internalName) ?
  4073. this.internalToPublic[internalName] :
  4074. null;
  4075. }
  4076. toInternalName(publicName) {
  4077. return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
  4078. null;
  4079. }
  4080. visitText(text, context) { return null; }
  4081. visitTagPlaceholder(ph, context) {
  4082. this.visitPlaceholderName(ph.startName);
  4083. super.visitTagPlaceholder(ph, context);
  4084. this.visitPlaceholderName(ph.closeName);
  4085. }
  4086. visitPlaceholder(ph, context) { this.visitPlaceholderName(ph.name); }
  4087. visitIcuPlaceholder(ph, context) {
  4088. this.visitPlaceholderName(ph.name);
  4089. }
  4090. // XMB placeholders could only contains A-Z, 0-9 and _
  4091. visitPlaceholderName(internalName) {
  4092. if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
  4093. return;
  4094. }
  4095. let publicName = this.mapName(internalName);
  4096. if (this.publicToInternal.hasOwnProperty(publicName)) {
  4097. // Create a new XMB when it has already been used
  4098. const nextId = this.publicToNextId[publicName];
  4099. this.publicToNextId[publicName] = nextId + 1;
  4100. publicName = `${publicName}_${nextId}`;
  4101. }
  4102. else {
  4103. this.publicToNextId[publicName] = 1;
  4104. }
  4105. this.internalToPublic[internalName] = publicName;
  4106. this.publicToInternal[publicName] = internalName;
  4107. }
  4108. }
  4109. /**
  4110. * @license
  4111. * Copyright Google Inc. All Rights Reserved.
  4112. *
  4113. * Use of this source code is governed by an MIT-style license that can be
  4114. * found in the LICENSE file at https://angular.io/license
  4115. */
  4116. class _Visitor {
  4117. visitTag(tag) {
  4118. const strAttrs = this._serializeAttributes(tag.attrs);
  4119. if (tag.children.length == 0) {
  4120. return `<${tag.name}${strAttrs}/>`;
  4121. }
  4122. const strChildren = tag.children.map(node => node.visit(this));
  4123. return `<${tag.name}${strAttrs}>${strChildren.join('')}</${tag.name}>`;
  4124. }
  4125. visitText(text) { return text.value; }
  4126. visitDeclaration(decl) {
  4127. return `<?xml${this._serializeAttributes(decl.attrs)} ?>`;
  4128. }
  4129. _serializeAttributes(attrs) {
  4130. const strAttrs = Object.keys(attrs).map((name) => `${name}="${attrs[name]}"`).join(' ');
  4131. return strAttrs.length > 0 ? ' ' + strAttrs : '';
  4132. }
  4133. visitDoctype(doctype) {
  4134. return `<!DOCTYPE ${doctype.rootTag} [\n${doctype.dtd}\n]>`;
  4135. }
  4136. }
  4137. const _visitor = new _Visitor();
  4138. function serialize(nodes) {
  4139. return nodes.map((node) => node.visit(_visitor)).join('');
  4140. }
  4141. class Declaration {
  4142. constructor(unescapedAttrs) {
  4143. this.attrs = {};
  4144. Object.keys(unescapedAttrs).forEach((k) => {
  4145. this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4146. });
  4147. }
  4148. visit(visitor) { return visitor.visitDeclaration(this); }
  4149. }
  4150. class Doctype {
  4151. constructor(rootTag, dtd) {
  4152. this.rootTag = rootTag;
  4153. this.dtd = dtd;
  4154. }
  4155. visit(visitor) { return visitor.visitDoctype(this); }
  4156. }
  4157. class Tag {
  4158. constructor(name, unescapedAttrs = {}, children = []) {
  4159. this.name = name;
  4160. this.children = children;
  4161. this.attrs = {};
  4162. Object.keys(unescapedAttrs).forEach((k) => {
  4163. this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4164. });
  4165. }
  4166. visit(visitor) { return visitor.visitTag(this); }
  4167. }
  4168. class Text$2 {
  4169. constructor(unescapedValue) { this.value = escapeXml(unescapedValue); }
  4170. visit(visitor) { return visitor.visitText(this); }
  4171. }
  4172. class CR extends Text$2 {
  4173. constructor(ws = 0) { super(`\n${new Array(ws + 1).join(' ')}`); }
  4174. }
  4175. const _ESCAPED_CHARS = [
  4176. [/&/g, '&amp;'],
  4177. [/"/g, '&quot;'],
  4178. [/'/g, '&apos;'],
  4179. [/</g, '&lt;'],
  4180. [/>/g, '&gt;'],
  4181. ];
  4182. // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
  4183. function escapeXml(text) {
  4184. return _ESCAPED_CHARS.reduce((text, entry) => text.replace(entry[0], entry[1]), text);
  4185. }
  4186. /**
  4187. * @license
  4188. * Copyright Google Inc. All Rights Reserved.
  4189. *
  4190. * Use of this source code is governed by an MIT-style license that can be
  4191. * found in the LICENSE file at https://angular.io/license
  4192. */
  4193. const _MESSAGES_TAG = 'messagebundle';
  4194. const _MESSAGE_TAG = 'msg';
  4195. const _PLACEHOLDER_TAG = 'ph';
  4196. const _EXAMPLE_TAG = 'ex';
  4197. const _SOURCE_TAG = 'source';
  4198. const _DOCTYPE = `<!ELEMENT messagebundle (msg)*>
  4199. <!ATTLIST messagebundle class CDATA #IMPLIED>
  4200. <!ELEMENT msg (#PCDATA|ph|source)*>
  4201. <!ATTLIST msg id CDATA #IMPLIED>
  4202. <!ATTLIST msg seq CDATA #IMPLIED>
  4203. <!ATTLIST msg name CDATA #IMPLIED>
  4204. <!ATTLIST msg desc CDATA #IMPLIED>
  4205. <!ATTLIST msg meaning CDATA #IMPLIED>
  4206. <!ATTLIST msg obsolete (obsolete) #IMPLIED>
  4207. <!ATTLIST msg xml:space (default|preserve) "default">
  4208. <!ATTLIST msg is_hidden CDATA #IMPLIED>
  4209. <!ELEMENT source (#PCDATA)>
  4210. <!ELEMENT ph (#PCDATA|ex)*>
  4211. <!ATTLIST ph name CDATA #REQUIRED>
  4212. <!ELEMENT ex (#PCDATA)>`;
  4213. class Xmb extends Serializer {
  4214. write(messages, locale) {
  4215. const exampleVisitor = new ExampleVisitor();
  4216. const visitor = new _Visitor$1();
  4217. let rootNode = new Tag(_MESSAGES_TAG);
  4218. messages.forEach(message => {
  4219. const attrs = { id: message.id };
  4220. if (message.description) {
  4221. attrs['desc'] = message.description;
  4222. }
  4223. if (message.meaning) {
  4224. attrs['meaning'] = message.meaning;
  4225. }
  4226. let sourceTags = [];
  4227. message.sources.forEach((source) => {
  4228. sourceTags.push(new Tag(_SOURCE_TAG, {}, [
  4229. new Text$2(`${source.filePath}:${source.startLine}${source.endLine !== source.startLine ? ',' + source.endLine : ''}`)
  4230. ]));
  4231. });
  4232. rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, [...sourceTags, ...visitor.serialize(message.nodes)]));
  4233. });
  4234. rootNode.children.push(new CR());
  4235. return serialize([
  4236. new Declaration({ version: '1.0', encoding: 'UTF-8' }),
  4237. new CR(),
  4238. new Doctype(_MESSAGES_TAG, _DOCTYPE),
  4239. new CR(),
  4240. exampleVisitor.addDefaultExamples(rootNode),
  4241. new CR(),
  4242. ]);
  4243. }
  4244. load(content, url) {
  4245. throw new Error('Unsupported');
  4246. }
  4247. digest(message) { return digest$1(message); }
  4248. createNameMapper(message) {
  4249. return new SimplePlaceholderMapper(message, toPublicName);
  4250. }
  4251. }
  4252. class _Visitor$1 {
  4253. visitText(text, context) { return [new Text$2(text.value)]; }
  4254. visitContainer(container, context) {
  4255. const nodes = [];
  4256. container.children.forEach((node) => nodes.push(...node.visit(this)));
  4257. return nodes;
  4258. }
  4259. visitIcu(icu, context) {
  4260. const nodes = [new Text$2(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
  4261. Object.keys(icu.cases).forEach((c) => {
  4262. nodes.push(new Text$2(`${c} {`), ...icu.cases[c].visit(this), new Text$2(`} `));
  4263. });
  4264. nodes.push(new Text$2(`}`));
  4265. return nodes;
  4266. }
  4267. visitTagPlaceholder(ph, context) {
  4268. const startTagAsText = new Text$2(`<${ph.tag}>`);
  4269. const startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
  4270. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4271. const startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
  4272. if (ph.isVoid) {
  4273. // void tags have no children nor closing tags
  4274. return [startTagPh];
  4275. }
  4276. const closeTagAsText = new Text$2(`</${ph.tag}>`);
  4277. const closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
  4278. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4279. const closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
  4280. return [startTagPh, ...this.serialize(ph.children), closeTagPh];
  4281. }
  4282. visitPlaceholder(ph, context) {
  4283. const interpolationAsText = new Text$2(`{{${ph.value}}}`);
  4284. // Example tag needs to be not-empty for TC.
  4285. const exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
  4286. return [
  4287. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4288. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
  4289. ];
  4290. }
  4291. visitIcuPlaceholder(ph, context) {
  4292. const icuExpression = ph.value.expression;
  4293. const icuType = ph.value.type;
  4294. const icuCases = Object.keys(ph.value.cases).map((value) => value + ' {...}').join(' ');
  4295. const icuAsText = new Text$2(`{${icuExpression}, ${icuType}, ${icuCases}}`);
  4296. const exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
  4297. return [
  4298. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4299. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
  4300. ];
  4301. }
  4302. serialize(nodes) {
  4303. return [].concat(...nodes.map(node => node.visit(this)));
  4304. }
  4305. }
  4306. function digest$1(message) {
  4307. return decimalDigest(message);
  4308. }
  4309. // TC requires at least one non-empty example on placeholders
  4310. class ExampleVisitor {
  4311. addDefaultExamples(node) {
  4312. node.visit(this);
  4313. return node;
  4314. }
  4315. visitTag(tag) {
  4316. if (tag.name === _PLACEHOLDER_TAG) {
  4317. if (!tag.children || tag.children.length == 0) {
  4318. const exText = new Text$2(tag.attrs['name'] || '...');
  4319. tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
  4320. }
  4321. }
  4322. else if (tag.children) {
  4323. tag.children.forEach(node => node.visit(this));
  4324. }
  4325. }
  4326. visitText(text) { }
  4327. visitDeclaration(decl) { }
  4328. visitDoctype(doctype) { }
  4329. }
  4330. // XMB/XTB placeholders can only contain A-Z, 0-9 and _
  4331. function toPublicName(internalName) {
  4332. return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
  4333. }
  4334. /**
  4335. * @license
  4336. * Copyright Google Inc. All Rights Reserved.
  4337. *
  4338. * Use of this source code is governed by an MIT-style license that can be
  4339. * found in the LICENSE file at https://angular.io/license
  4340. */
  4341. function mapLiteral(obj, quoted = false) {
  4342. return literalMap(Object.keys(obj).map(key => ({
  4343. key,
  4344. quoted,
  4345. value: obj[key],
  4346. })));
  4347. }
  4348. /**
  4349. * @license
  4350. * Copyright Google Inc. All Rights Reserved.
  4351. *
  4352. * Use of this source code is governed by an MIT-style license that can be
  4353. * found in the LICENSE file at https://angular.io/license
  4354. */
  4355. /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
  4356. const CLOSURE_TRANSLATION_PREFIX = 'MSG_';
  4357. /* Prefix for non-`goog.getMsg` i18n-related vars */
  4358. const TRANSLATION_PREFIX = 'I18N_';
  4359. /** Closure uses `goog.getMsg(message)` to lookup translations */
  4360. const GOOG_GET_MSG = 'goog.getMsg';
  4361. /** Name of the global variable that is used to determine if we use Closure translations or not */
  4362. const NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
  4363. /** I18n separators for metadata **/
  4364. const I18N_MEANING_SEPARATOR = '|';
  4365. const I18N_ID_SEPARATOR = '@@';
  4366. /** Name of the i18n attributes **/
  4367. const I18N_ATTR = 'i18n';
  4368. const I18N_ATTR_PREFIX = 'i18n-';
  4369. /** Prefix of var expressions used in ICUs */
  4370. const I18N_ICU_VAR_PREFIX = 'VAR_';
  4371. /** Prefix of ICU expressions for post processing */
  4372. const I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
  4373. /** Placeholder wrapper for i18n expressions **/
  4374. const I18N_PLACEHOLDER_SYMBOL = '�';
  4375. function i18nTranslationToDeclStmt(variable$1, closureVar, message, meta, params) {
  4376. const statements = [];
  4377. // var I18N_X;
  4378. statements.push(new DeclareVarStmt(variable$1.name, undefined, INFERRED_TYPE, null, variable$1.sourceSpan));
  4379. const args = [literal(message)];
  4380. if (params && Object.keys(params).length) {
  4381. args.push(mapLiteral(params, true));
  4382. }
  4383. // Closure JSDoc comments
  4384. const docStatements = i18nMetaToDocStmt(meta);
  4385. const thenStatements = docStatements ? [docStatements] : [];
  4386. const googFnCall = variable(GOOG_GET_MSG).callFn(args);
  4387. // const MSG_... = goog.getMsg(..);
  4388. thenStatements.push(closureVar.set(googFnCall).toConstDecl());
  4389. // I18N_X = MSG_...;
  4390. thenStatements.push(new ExpressionStatement(variable$1.set(closureVar)));
  4391. const localizeFnCall = importExpr(Identifiers$1.i18nLocalize).callFn(args);
  4392. // I18N_X = i18nLocalize(...);
  4393. const elseStatements = [new ExpressionStatement(variable$1.set(localizeFnCall))];
  4394. // if(ngI18nClosureMode) { ... } else { ... }
  4395. statements.push(ifStmt(variable(NG_I18N_CLOSURE_MODE), thenStatements, elseStatements));
  4396. return statements;
  4397. }
  4398. // Converts i18n meta information for a message (id, description, meaning)
  4399. // to a JsDoc statement formatted as expected by the Closure compiler.
  4400. function i18nMetaToDocStmt(meta) {
  4401. const tags = [];
  4402. if (meta.description) {
  4403. tags.push({ tagName: "desc" /* Desc */, text: meta.description });
  4404. }
  4405. if (meta.meaning) {
  4406. tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
  4407. }
  4408. return tags.length == 0 ? null : new JSDocCommentStmt(tags);
  4409. }
  4410. function isI18nAttribute(name) {
  4411. return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
  4412. }
  4413. function isI18nRootNode(meta) {
  4414. return meta instanceof Message;
  4415. }
  4416. function isSingleI18nIcu(meta) {
  4417. return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
  4418. }
  4419. function hasI18nAttrs(element) {
  4420. return element.attrs.some((attr) => isI18nAttribute(attr.name));
  4421. }
  4422. function metaFromI18nMessage(message, id = null) {
  4423. return {
  4424. id: typeof id === 'string' ? id : message.id || '',
  4425. meaning: message.meaning || '',
  4426. description: message.description || ''
  4427. };
  4428. }
  4429. function icuFromI18nMessage(message) {
  4430. return message.nodes[0];
  4431. }
  4432. function wrapI18nPlaceholder(content, contextId = 0) {
  4433. const blockId = contextId > 0 ? `:${contextId}` : '';
  4434. return `${I18N_PLACEHOLDER_SYMBOL}${content}${blockId}${I18N_PLACEHOLDER_SYMBOL}`;
  4435. }
  4436. function assembleI18nBoundString(strings, bindingStartIndex = 0, contextId = 0) {
  4437. if (!strings.length)
  4438. return '';
  4439. let acc = '';
  4440. const lastIdx = strings.length - 1;
  4441. for (let i = 0; i < lastIdx; i++) {
  4442. acc += `${strings[i]}${wrapI18nPlaceholder(bindingStartIndex + i, contextId)}`;
  4443. }
  4444. acc += strings[lastIdx];
  4445. return acc;
  4446. }
  4447. function getSeqNumberGenerator(startsAt = 0) {
  4448. let current = startsAt;
  4449. return () => current++;
  4450. }
  4451. function placeholdersToParams(placeholders) {
  4452. const params = {};
  4453. placeholders.forEach((values, key) => {
  4454. params[key] = literal(values.length > 1 ? `[${values.join('|')}]` : values[0]);
  4455. });
  4456. return params;
  4457. }
  4458. function updatePlaceholderMap(map, name, ...values) {
  4459. const current = map.get(name) || [];
  4460. current.push(...values);
  4461. map.set(name, current);
  4462. }
  4463. function assembleBoundTextPlaceholders(meta, bindingStartIndex = 0, contextId = 0) {
  4464. const startIdx = bindingStartIndex;
  4465. const placeholders = new Map();
  4466. const node = meta instanceof Message ? meta.nodes.find(node => node instanceof Container) : meta;
  4467. if (node) {
  4468. node
  4469. .children.filter((child) => child instanceof Placeholder)
  4470. .forEach((child, idx) => {
  4471. const content = wrapI18nPlaceholder(startIdx + idx, contextId);
  4472. updatePlaceholderMap(placeholders, child.name, content);
  4473. });
  4474. }
  4475. return placeholders;
  4476. }
  4477. function findIndex(items, callback) {
  4478. for (let i = 0; i < items.length; i++) {
  4479. if (callback(items[i])) {
  4480. return i;
  4481. }
  4482. }
  4483. return -1;
  4484. }
  4485. /**
  4486. * Parses i18n metas like:
  4487. * - "@@id",
  4488. * - "description[@@id]",
  4489. * - "meaning|description[@@id]"
  4490. * and returns an object with parsed output.
  4491. *
  4492. * @param meta String that represents i18n meta
  4493. * @returns Object with id, meaning and description fields
  4494. */
  4495. function parseI18nMeta(meta) {
  4496. let id;
  4497. let meaning;
  4498. let description;
  4499. if (meta) {
  4500. const idIndex = meta.indexOf(I18N_ID_SEPARATOR);
  4501. const descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
  4502. let meaningAndDesc;
  4503. [meaningAndDesc, id] =
  4504. (idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''];
  4505. [meaning, description] = (descIndex > -1) ?
  4506. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  4507. ['', meaningAndDesc];
  4508. }
  4509. return { id, meaning, description };
  4510. }
  4511. /**
  4512. * Converts internal placeholder names to public-facing format
  4513. * (for example to use in goog.getMsg call).
  4514. * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
  4515. *
  4516. * @param name The placeholder name that should be formatted
  4517. * @returns Formatted placeholder name
  4518. */
  4519. function formatI18nPlaceholderName(name) {
  4520. const chunks = toPublicName(name).split('_');
  4521. if (chunks.length === 1) {
  4522. // if no "_" found - just lowercase the value
  4523. return name.toLowerCase();
  4524. }
  4525. let postfix;
  4526. // eject last element if it's a number
  4527. if (/^\d+$/.test(chunks[chunks.length - 1])) {
  4528. postfix = chunks.pop();
  4529. }
  4530. let raw = chunks.shift().toLowerCase();
  4531. if (chunks.length) {
  4532. raw += chunks.map(c => c.charAt(0).toUpperCase() + c.slice(1).toLowerCase()).join('');
  4533. }
  4534. return postfix ? `${raw}_${postfix}` : raw;
  4535. }
  4536. /**
  4537. * Generates a prefix for translation const name.
  4538. *
  4539. * @param extra Additional local prefix that should be injected into translation var name
  4540. * @returns Complete translation const prefix
  4541. */
  4542. function getTranslationConstPrefix(extra) {
  4543. return `${CLOSURE_TRANSLATION_PREFIX}${extra}`.toUpperCase();
  4544. }
  4545. /**
  4546. * Generates translation declaration statements.
  4547. *
  4548. * @param variable Translation value reference
  4549. * @param closureVar Variable for Closure `goog.getMsg` calls
  4550. * @param message Text message to be translated
  4551. * @param meta Object that contains meta information (id, meaning and description)
  4552. * @param params Object with placeholders key-value pairs
  4553. * @param transformFn Optional transformation (post processing) function reference
  4554. * @returns Array of Statements that represent a given translation
  4555. */
  4556. function getTranslationDeclStmts(variable, closureVar, message, meta, params = {}, transformFn) {
  4557. const statements = [];
  4558. statements.push(...i18nTranslationToDeclStmt(variable, closureVar, message, meta, params));
  4559. if (transformFn) {
  4560. statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
  4561. }
  4562. return statements;
  4563. }
  4564. /**
  4565. * @license
  4566. * Copyright Google Inc. All Rights Reserved.
  4567. *
  4568. * Use of this source code is governed by an MIT-style license that can be
  4569. * found in the LICENSE file at https://angular.io/license
  4570. */
  4571. /**
  4572. * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
  4573. * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
  4574. * bot work in some cases when object keys are mangled by minifier.
  4575. *
  4576. * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
  4577. * inputs that contain potentially unsafe chars.
  4578. */
  4579. const UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
  4580. /** Name of the temporary to use during data binding */
  4581. const TEMPORARY_NAME = '_t';
  4582. /** Name of the context parameter passed into a template function */
  4583. const CONTEXT_NAME = 'ctx';
  4584. /** Name of the RenderFlag passed into a template function */
  4585. const RENDER_FLAGS = 'rf';
  4586. /** The prefix reference variables */
  4587. const REFERENCE_PREFIX = '_r';
  4588. /** The name of the implicit context reference */
  4589. const IMPLICIT_REFERENCE = '$implicit';
  4590. /** Non bindable attribute name **/
  4591. const NON_BINDABLE_ATTR = 'ngNonBindable';
  4592. /**
  4593. * Creates an allocator for a temporary variable.
  4594. *
  4595. * A variable declaration is added to the statements the first time the allocator is invoked.
  4596. */
  4597. function temporaryAllocator(statements, name) {
  4598. let temp = null;
  4599. return () => {
  4600. if (!temp) {
  4601. statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
  4602. temp = variable(name);
  4603. }
  4604. return temp;
  4605. };
  4606. }
  4607. function unsupported(feature) {
  4608. if (this) {
  4609. throw new Error(`Builder ${this.constructor.name} doesn't support ${feature} yet`);
  4610. }
  4611. throw new Error(`Feature ${feature} is not supported yet`);
  4612. }
  4613. function invalid$1(arg) {
  4614. throw new Error(`Invalid state: Visitor ${this.constructor.name} doesn't handle ${arg.constructor.name}`);
  4615. }
  4616. function asLiteral(value) {
  4617. if (Array.isArray(value)) {
  4618. return literalArr(value.map(asLiteral));
  4619. }
  4620. return literal(value, INFERRED_TYPE);
  4621. }
  4622. function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
  4623. if (Object.getOwnPropertyNames(keys).length > 0) {
  4624. return mapToExpression(keys, keepDeclared);
  4625. }
  4626. return null;
  4627. }
  4628. function mapToExpression(map, keepDeclared) {
  4629. return literalMap(Object.getOwnPropertyNames(map).map(key => {
  4630. // canonical syntax: `dirProp: publicProp`
  4631. // if there is no `:`, use dirProp = elProp
  4632. const value = map[key];
  4633. let declaredName;
  4634. let publicName;
  4635. let minifiedName;
  4636. if (Array.isArray(value)) {
  4637. [publicName, declaredName] = value;
  4638. }
  4639. else {
  4640. [declaredName, publicName] = splitAtColon(key, [key, value]);
  4641. }
  4642. minifiedName = declaredName;
  4643. return {
  4644. key: minifiedName,
  4645. // put quotes around keys that contain potentially unsafe characters
  4646. quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
  4647. value: (keepDeclared && publicName !== declaredName) ?
  4648. literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
  4649. asLiteral(publicName)
  4650. };
  4651. }));
  4652. }
  4653. /**
  4654. * Remove trailing null nodes as they are implied.
  4655. */
  4656. function trimTrailingNulls(parameters) {
  4657. while (isNull(parameters[parameters.length - 1])) {
  4658. parameters.pop();
  4659. }
  4660. return parameters;
  4661. }
  4662. function getQueryPredicate(query, constantPool) {
  4663. if (Array.isArray(query.predicate)) {
  4664. let predicate = [];
  4665. query.predicate.forEach((selector) => {
  4666. // Each item in predicates array may contain strings with comma-separated refs
  4667. // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
  4668. // as separate array entities
  4669. const selectors = selector.split(',').map(token => literal(token.trim()));
  4670. predicate.push(...selectors);
  4671. });
  4672. return constantPool.getConstLiteral(literalArr(predicate), true);
  4673. }
  4674. else {
  4675. return query.predicate;
  4676. }
  4677. }
  4678. class DefinitionMap {
  4679. constructor() {
  4680. this.values = [];
  4681. }
  4682. set(key, value) {
  4683. if (value) {
  4684. this.values.push({ key, value, quoted: false });
  4685. }
  4686. }
  4687. toLiteralMap() { return literalMap(this.values); }
  4688. }
  4689. /**
  4690. * Extract a map of properties to values for a given element or template node, which can be used
  4691. * by the directive matching machinery.
  4692. *
  4693. * @param elOrTpl the element or template in question
  4694. * @return an object set up for directive matching. For attributes on the element/template, this
  4695. * object maps a property name to its (static) value. For any bindings, this map simply maps the
  4696. * property name to an empty string.
  4697. */
  4698. function getAttrsForDirectiveMatching(elOrTpl) {
  4699. const attributesMap = {};
  4700. if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
  4701. elOrTpl.templateAttrs.forEach(a => attributesMap[a.name] = '');
  4702. }
  4703. else {
  4704. elOrTpl.attributes.forEach(a => {
  4705. if (!isI18nAttribute(a.name)) {
  4706. attributesMap[a.name] = a.value;
  4707. }
  4708. });
  4709. elOrTpl.inputs.forEach(i => { attributesMap[i.name] = ''; });
  4710. elOrTpl.outputs.forEach(o => { attributesMap[o.name] = ''; });
  4711. }
  4712. return attributesMap;
  4713. }
  4714. /**
  4715. * @license
  4716. * Copyright Google Inc. All Rights Reserved.
  4717. *
  4718. * Use of this source code is governed by an MIT-style license that can be
  4719. * found in the LICENSE file at https://angular.io/license
  4720. */
  4721. var R3FactoryDelegateType;
  4722. (function (R3FactoryDelegateType) {
  4723. R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
  4724. R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
  4725. R3FactoryDelegateType[R3FactoryDelegateType["Factory"] = 2] = "Factory";
  4726. })(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
  4727. /**
  4728. * Resolved type of a dependency.
  4729. *
  4730. * Occasionally, dependencies will have special significance which is known statically. In that
  4731. * case the `R3ResolvedDependencyType` informs the factory generator that a particular dependency
  4732. * should be generated specially (usually by calling a special injection function instead of the
  4733. * standard one).
  4734. */
  4735. var R3ResolvedDependencyType;
  4736. (function (R3ResolvedDependencyType) {
  4737. /**
  4738. * A normal token dependency.
  4739. */
  4740. R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
  4741. /**
  4742. * The dependency is for an attribute.
  4743. *
  4744. * The token expression is a string representing the attribute name.
  4745. */
  4746. R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
  4747. })(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
  4748. /**
  4749. * Construct a factory function expression for the given `R3FactoryMetadata`.
  4750. */
  4751. function compileFactoryFunction(meta) {
  4752. const t = variable('t');
  4753. const statements = [];
  4754. // The type to instantiate via constructor invocation. If there is no delegated factory, meaning
  4755. // this type is always created by constructor invocation, then this is the type-to-create
  4756. // parameter provided by the user (t) if specified, or the current type if not. If there is a
  4757. // delegated factory (which is used to create the current type) then this is only the type-to-
  4758. // create parameter (t).
  4759. const typeForCtor = !isDelegatedMetadata(meta) ? new BinaryOperatorExpr(BinaryOperator.Or, t, meta.type) : t;
  4760. let ctorExpr = null;
  4761. if (meta.deps !== null) {
  4762. // There is a constructor (either explicitly or implicitly defined).
  4763. if (meta.deps !== 'invalid') {
  4764. ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn));
  4765. }
  4766. }
  4767. else {
  4768. const baseFactory = variable(`ɵ${meta.name}_BaseFactory`);
  4769. const getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory);
  4770. const baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.type])).toDeclStmt(INFERRED_TYPE, [
  4771. StmtModifier.Exported, StmtModifier.Final
  4772. ]);
  4773. statements.push(baseFactoryStmt);
  4774. // There is no constructor, use the base class' factory to construct typeForCtor.
  4775. ctorExpr = baseFactory.callFn([typeForCtor]);
  4776. }
  4777. const ctorExprFinal = ctorExpr;
  4778. const body = [];
  4779. let retExpr = null;
  4780. function makeConditionalFactory(nonCtorExpr) {
  4781. const r = variable('r');
  4782. body.push(r.set(NULL_EXPR).toDeclStmt());
  4783. let ctorStmt = null;
  4784. if (ctorExprFinal !== null) {
  4785. ctorStmt = r.set(ctorExprFinal).toStmt();
  4786. }
  4787. else {
  4788. ctorStmt = makeErrorStmt(meta.name);
  4789. }
  4790. body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
  4791. return r;
  4792. }
  4793. if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) {
  4794. const delegateFactory = variable(`ɵ${meta.name}_BaseFactory`);
  4795. const getFactoryOf = importExpr(Identifiers$1.getFactoryOf);
  4796. if (meta.delegate.isEquivalent(meta.type)) {
  4797. throw new Error(`Illegal state: compiling factory that delegates to itself`);
  4798. }
  4799. const delegateFactoryStmt = delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt(INFERRED_TYPE, [
  4800. StmtModifier.Exported, StmtModifier.Final
  4801. ]);
  4802. statements.push(delegateFactoryStmt);
  4803. retExpr = makeConditionalFactory(delegateFactory.callFn([]));
  4804. }
  4805. else if (isDelegatedMetadata(meta)) {
  4806. // This type is created with a delegated factory. If a type parameter is not specified, call
  4807. // the factory instead.
  4808. const delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn);
  4809. // Either call `new delegate(...)` or `delegate(...)` depending on meta.useNewForDelegate.
  4810. const factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
  4811. InstantiateExpr :
  4812. InvokeFunctionExpr)(meta.delegate, delegateArgs);
  4813. retExpr = makeConditionalFactory(factoryExpr);
  4814. }
  4815. else if (isExpressionFactoryMetadata(meta)) {
  4816. // TODO(alxhub): decide whether to lower the value here or in the caller
  4817. retExpr = makeConditionalFactory(meta.expression);
  4818. }
  4819. else {
  4820. retExpr = ctorExpr;
  4821. }
  4822. if (retExpr !== null) {
  4823. body.push(new ReturnStatement(retExpr));
  4824. }
  4825. else {
  4826. body.push(makeErrorStmt(meta.name));
  4827. }
  4828. return {
  4829. factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, `${meta.name}_Factory`),
  4830. statements,
  4831. };
  4832. }
  4833. function injectDependencies(deps, injectFn) {
  4834. return deps.map(dep => compileInjectDependency(dep, injectFn));
  4835. }
  4836. function compileInjectDependency(dep, injectFn) {
  4837. // Interpret the dependency according to its resolved type.
  4838. switch (dep.resolved) {
  4839. case R3ResolvedDependencyType.Token: {
  4840. // Build up the injection flags according to the metadata.
  4841. const flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
  4842. (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
  4843. (dep.optional ? 8 /* Optional */ : 0);
  4844. // Build up the arguments to the injectFn call.
  4845. const injectArgs = [dep.token];
  4846. // If this dependency is optional or otherwise has non-default flags, then additional
  4847. // parameters describing how to inject the dependency must be passed to the inject function
  4848. // that's being used.
  4849. if (flags !== 0 /* Default */ || dep.optional) {
  4850. injectArgs.push(literal(flags));
  4851. }
  4852. return importExpr(injectFn).callFn(injectArgs);
  4853. }
  4854. case R3ResolvedDependencyType.Attribute:
  4855. // In the case of attributes, the attribute name in question is given as the token.
  4856. return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]);
  4857. default:
  4858. return unsupported(`Unknown R3ResolvedDependencyType: ${R3ResolvedDependencyType[dep.resolved]}`);
  4859. }
  4860. }
  4861. /**
  4862. * A helper function useful for extracting `R3DependencyMetadata` from a Render2
  4863. * `CompileTypeMetadata` instance.
  4864. */
  4865. function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {
  4866. // Use the `CompileReflector` to look up references to some well-known Angular types. These will
  4867. // be compared with the token to statically determine whether the token has significance to
  4868. // Angular, and set the correct `R3ResolvedDependencyType` as a result.
  4869. const injectorRef = reflector.resolveExternalReference(Identifiers.Injector);
  4870. // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.
  4871. const deps = [];
  4872. for (let dependency of type.diDeps) {
  4873. if (dependency.token) {
  4874. const tokenRef = tokenReference(dependency.token);
  4875. let resolved = dependency.isAttribute ?
  4876. R3ResolvedDependencyType.Attribute :
  4877. R3ResolvedDependencyType.Token;
  4878. // In the case of most dependencies, the token will be a reference to a type. Sometimes,
  4879. // however, it can be a string, in the case of older Angular code or @Attribute injection.
  4880. const token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);
  4881. // Construct the dependency.
  4882. deps.push({
  4883. token,
  4884. resolved,
  4885. host: !!dependency.isHost,
  4886. optional: !!dependency.isOptional,
  4887. self: !!dependency.isSelf,
  4888. skipSelf: !!dependency.isSkipSelf,
  4889. });
  4890. }
  4891. else {
  4892. unsupported('dependency without a token');
  4893. }
  4894. }
  4895. return deps;
  4896. }
  4897. function makeErrorStmt(name) {
  4898. return new ThrowStmt(new InstantiateExpr(new ReadVarExpr('Error'), [
  4899. literal(`${name} has a constructor which is not compatible with Dependency Injection. It should probably not be @Injectable().`)
  4900. ]));
  4901. }
  4902. function isDelegatedMetadata(meta) {
  4903. return meta.delegateType !== undefined;
  4904. }
  4905. function isExpressionFactoryMetadata(meta) {
  4906. return meta.expression !== undefined;
  4907. }
  4908. /**
  4909. * @license
  4910. * Copyright Google Inc. All Rights Reserved.
  4911. *
  4912. * Use of this source code is governed by an MIT-style license that can be
  4913. * found in the LICENSE file at https://angular.io/license
  4914. */
  4915. /**
  4916. * Convert an object map with `Expression` values into a `LiteralMapExpr`.
  4917. */
  4918. function mapToMapExpression(map) {
  4919. const result = Object.keys(map).map(key => ({ key, value: map[key], quoted: false }));
  4920. return literalMap(result);
  4921. }
  4922. /**
  4923. * Convert metadata into an `Expression` in the given `OutputContext`.
  4924. *
  4925. * This operation will handle arrays, references to symbols, or literal `null` or `undefined`.
  4926. */
  4927. function convertMetaToOutput(meta, ctx) {
  4928. if (Array.isArray(meta)) {
  4929. return literalArr(meta.map(entry => convertMetaToOutput(entry, ctx)));
  4930. }
  4931. if (meta instanceof StaticSymbol) {
  4932. return ctx.importExpr(meta);
  4933. }
  4934. if (meta == null) {
  4935. return literal(meta);
  4936. }
  4937. throw new Error(`Internal error: Unsupported or unknown metadata: ${meta}`);
  4938. }
  4939. function typeWithParameters(type, numParams) {
  4940. let params = null;
  4941. if (numParams > 0) {
  4942. params = [];
  4943. for (let i = 0; i < numParams; i++) {
  4944. params.push(DYNAMIC_TYPE);
  4945. }
  4946. }
  4947. return expressionType(type, null, params);
  4948. }
  4949. const ANIMATE_SYMBOL_PREFIX = '@';
  4950. function prepareSyntheticPropertyName(name) {
  4951. return `${ANIMATE_SYMBOL_PREFIX}${name}`;
  4952. }
  4953. function prepareSyntheticListenerName(name, phase) {
  4954. return `${ANIMATE_SYMBOL_PREFIX}${name}.${phase}`;
  4955. }
  4956. function prepareSyntheticListenerFunctionName(name, phase) {
  4957. return `animation_${name}_${phase}`;
  4958. }
  4959. /**
  4960. * @license
  4961. * Copyright Google Inc. All Rights Reserved.
  4962. *
  4963. * Use of this source code is governed by an MIT-style license that can be
  4964. * found in the LICENSE file at https://angular.io/license
  4965. */
  4966. function compileInjectable(meta) {
  4967. let result = null;
  4968. const factoryMeta = {
  4969. name: meta.name,
  4970. type: meta.type,
  4971. deps: meta.ctorDeps,
  4972. injectFn: Identifiers.inject,
  4973. };
  4974. if (meta.useClass !== undefined) {
  4975. // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
  4976. // used to instantiate the class with dependencies injected, or deps are not specified and
  4977. // the factory of the class is used to instantiate it.
  4978. //
  4979. // A special case exists for useClass: Type where Type is the injectable type itself and no
  4980. // deps are specified, in which case 'useClass' is effectively ignored.
  4981. const useClassOnSelf = meta.useClass.isEquivalent(meta.type);
  4982. let deps = undefined;
  4983. if (meta.userDeps !== undefined) {
  4984. deps = meta.userDeps;
  4985. }
  4986. if (deps !== undefined) {
  4987. // factory: () => new meta.useClass(...deps)
  4988. result = compileFactoryFunction(Object.assign({}, factoryMeta, { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
  4989. }
  4990. else if (useClassOnSelf) {
  4991. result = compileFactoryFunction(factoryMeta);
  4992. }
  4993. else {
  4994. result = compileFactoryFunction(Object.assign({}, factoryMeta, { delegate: meta.useClass, delegateType: R3FactoryDelegateType.Factory }));
  4995. }
  4996. }
  4997. else if (meta.useFactory !== undefined) {
  4998. result = compileFactoryFunction(Object.assign({}, factoryMeta, { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function }));
  4999. }
  5000. else if (meta.useValue !== undefined) {
  5001. // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
  5002. // client code because meta.useValue is an Expression which will be defined even if the actual
  5003. // value is undefined.
  5004. result = compileFactoryFunction(Object.assign({}, factoryMeta, { expression: meta.useValue }));
  5005. }
  5006. else if (meta.useExisting !== undefined) {
  5007. // useExisting is an `inject` call on the existing token.
  5008. result = compileFactoryFunction(Object.assign({}, factoryMeta, { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) }));
  5009. }
  5010. else {
  5011. result = compileFactoryFunction(factoryMeta);
  5012. }
  5013. const token = meta.type;
  5014. const providedIn = meta.providedIn;
  5015. const expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression({ token, factory: result.factory, providedIn })]);
  5016. const type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type, meta.typeArgumentCount)]));
  5017. return {
  5018. expression,
  5019. type,
  5020. statements: result.statements,
  5021. };
  5022. }
  5023. /**
  5024. * @license
  5025. * Copyright Google Inc. All Rights Reserved.
  5026. *
  5027. * Use of this source code is governed by an MIT-style license that can be
  5028. * found in the LICENSE file at https://angular.io/license
  5029. */
  5030. function assertArrayOfStrings(identifier, value) {
  5031. if (value == null) {
  5032. return;
  5033. }
  5034. if (!Array.isArray(value)) {
  5035. throw new Error(`Expected '${identifier}' to be an array of strings.`);
  5036. }
  5037. for (let i = 0; i < value.length; i += 1) {
  5038. if (typeof value[i] !== 'string') {
  5039. throw new Error(`Expected '${identifier}' to be an array of strings.`);
  5040. }
  5041. }
  5042. }
  5043. const UNUSABLE_INTERPOLATION_REGEXPS = [
  5044. /^\s*$/,
  5045. /[<>]/,
  5046. /^[{}]$/,
  5047. /&(#|[a-z])/i,
  5048. /^\/\//,
  5049. ];
  5050. function assertInterpolationSymbols(identifier, value) {
  5051. if (value != null && !(Array.isArray(value) && value.length == 2)) {
  5052. throw new Error(`Expected '${identifier}' to be an array, [start, end].`);
  5053. }
  5054. else if (value != null) {
  5055. const start = value[0];
  5056. const end = value[1];
  5057. // Check for unusable interpolation symbols
  5058. UNUSABLE_INTERPOLATION_REGEXPS.forEach(regexp => {
  5059. if (regexp.test(start) || regexp.test(end)) {
  5060. throw new Error(`['${start}', '${end}'] contains unusable interpolation symbol.`);
  5061. }
  5062. });
  5063. }
  5064. }
  5065. /**
  5066. * @license
  5067. * Copyright Google Inc. All Rights Reserved.
  5068. *
  5069. * Use of this source code is governed by an MIT-style license that can be
  5070. * found in the LICENSE file at https://angular.io/license
  5071. */
  5072. class InterpolationConfig {
  5073. constructor(start, end) {
  5074. this.start = start;
  5075. this.end = end;
  5076. }
  5077. static fromArray(markers) {
  5078. if (!markers) {
  5079. return DEFAULT_INTERPOLATION_CONFIG;
  5080. }
  5081. assertInterpolationSymbols('interpolation', markers);
  5082. return new InterpolationConfig(markers[0], markers[1]);
  5083. }
  5084. }
  5085. const DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
  5086. /**
  5087. * @license
  5088. * Copyright Google Inc. All Rights Reserved.
  5089. *
  5090. * Use of this source code is governed by an MIT-style license that can be
  5091. * found in the LICENSE file at https://angular.io/license
  5092. */
  5093. // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  5094. const VERSION = 3;
  5095. const JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
  5096. class SourceMapGenerator {
  5097. constructor(file = null) {
  5098. this.file = file;
  5099. this.sourcesContent = new Map();
  5100. this.lines = [];
  5101. this.lastCol0 = 0;
  5102. this.hasMappings = false;
  5103. }
  5104. // The content is `null` when the content is expected to be loaded using the URL
  5105. addSource(url, content = null) {
  5106. if (!this.sourcesContent.has(url)) {
  5107. this.sourcesContent.set(url, content);
  5108. }
  5109. return this;
  5110. }
  5111. addLine() {
  5112. this.lines.push([]);
  5113. this.lastCol0 = 0;
  5114. return this;
  5115. }
  5116. addMapping(col0, sourceUrl, sourceLine0, sourceCol0) {
  5117. if (!this.currentLine) {
  5118. throw new Error(`A line must be added before mappings can be added`);
  5119. }
  5120. if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
  5121. throw new Error(`Unknown source file "${sourceUrl}"`);
  5122. }
  5123. if (col0 == null) {
  5124. throw new Error(`The column in the generated code must be provided`);
  5125. }
  5126. if (col0 < this.lastCol0) {
  5127. throw new Error(`Mapping should be added in output order`);
  5128. }
  5129. if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
  5130. throw new Error(`The source location must be provided when a source url is provided`);
  5131. }
  5132. this.hasMappings = true;
  5133. this.lastCol0 = col0;
  5134. this.currentLine.push({ col0, sourceUrl, sourceLine0, sourceCol0 });
  5135. return this;
  5136. }
  5137. get currentLine() { return this.lines.slice(-1)[0]; }
  5138. toJSON() {
  5139. if (!this.hasMappings) {
  5140. return null;
  5141. }
  5142. const sourcesIndex = new Map();
  5143. const sources = [];
  5144. const sourcesContent = [];
  5145. Array.from(this.sourcesContent.keys()).forEach((url, i) => {
  5146. sourcesIndex.set(url, i);
  5147. sources.push(url);
  5148. sourcesContent.push(this.sourcesContent.get(url) || null);
  5149. });
  5150. let mappings = '';
  5151. let lastCol0 = 0;
  5152. let lastSourceIndex = 0;
  5153. let lastSourceLine0 = 0;
  5154. let lastSourceCol0 = 0;
  5155. this.lines.forEach(segments => {
  5156. lastCol0 = 0;
  5157. mappings += segments
  5158. .map(segment => {
  5159. // zero-based starting column of the line in the generated code
  5160. let segAsStr = toBase64VLQ(segment.col0 - lastCol0);
  5161. lastCol0 = segment.col0;
  5162. if (segment.sourceUrl != null) {
  5163. // zero-based index into the “sources” list
  5164. segAsStr +=
  5165. toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
  5166. lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
  5167. // the zero-based starting line in the original source
  5168. segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
  5169. lastSourceLine0 = segment.sourceLine0;
  5170. // the zero-based starting column in the original source
  5171. segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
  5172. lastSourceCol0 = segment.sourceCol0;
  5173. }
  5174. return segAsStr;
  5175. })
  5176. .join(',');
  5177. mappings += ';';
  5178. });
  5179. mappings = mappings.slice(0, -1);
  5180. return {
  5181. 'file': this.file || '',
  5182. 'version': VERSION,
  5183. 'sourceRoot': '',
  5184. 'sources': sources,
  5185. 'sourcesContent': sourcesContent,
  5186. 'mappings': mappings,
  5187. };
  5188. }
  5189. toJsComment() {
  5190. return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
  5191. '';
  5192. }
  5193. }
  5194. function toBase64String(value) {
  5195. let b64 = '';
  5196. value = utf8Encode(value);
  5197. for (let i = 0; i < value.length;) {
  5198. const i1 = value.charCodeAt(i++);
  5199. const i2 = value.charCodeAt(i++);
  5200. const i3 = value.charCodeAt(i++);
  5201. b64 += toBase64Digit(i1 >> 2);
  5202. b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
  5203. b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
  5204. b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
  5205. }
  5206. return b64;
  5207. }
  5208. function toBase64VLQ(value) {
  5209. value = value < 0 ? ((-value) << 1) + 1 : value << 1;
  5210. let out = '';
  5211. do {
  5212. let digit = value & 31;
  5213. value = value >> 5;
  5214. if (value > 0) {
  5215. digit = digit | 32;
  5216. }
  5217. out += toBase64Digit(digit);
  5218. } while (value > 0);
  5219. return out;
  5220. }
  5221. const B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5222. function toBase64Digit(value) {
  5223. if (value < 0 || value >= 64) {
  5224. throw new Error(`Can only encode value in the range [0, 63]`);
  5225. }
  5226. return B64_DIGITS[value];
  5227. }
  5228. /**
  5229. * @license
  5230. * Copyright Google Inc. All Rights Reserved.
  5231. *
  5232. * Use of this source code is governed by an MIT-style license that can be
  5233. * found in the LICENSE file at https://angular.io/license
  5234. */
  5235. const _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
  5236. const _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
  5237. const _INDENT_WITH = ' ';
  5238. const CATCH_ERROR_VAR$1 = variable('error', null, null);
  5239. const CATCH_STACK_VAR$1 = variable('stack', null, null);
  5240. class _EmittedLine {
  5241. constructor(indent) {
  5242. this.indent = indent;
  5243. this.partsLength = 0;
  5244. this.parts = [];
  5245. this.srcSpans = [];
  5246. }
  5247. }
  5248. class EmitterVisitorContext {
  5249. constructor(_indent) {
  5250. this._indent = _indent;
  5251. this._classes = [];
  5252. this._preambleLineCount = 0;
  5253. this._lines = [new _EmittedLine(_indent)];
  5254. }
  5255. static createRoot() { return new EmitterVisitorContext(0); }
  5256. get _currentLine() { return this._lines[this._lines.length - 1]; }
  5257. println(from, lastPart = '') {
  5258. this.print(from || null, lastPart, true);
  5259. }
  5260. lineIsEmpty() { return this._currentLine.parts.length === 0; }
  5261. lineLength() {
  5262. return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
  5263. }
  5264. print(from, part, newLine = false) {
  5265. if (part.length > 0) {
  5266. this._currentLine.parts.push(part);
  5267. this._currentLine.partsLength += part.length;
  5268. this._currentLine.srcSpans.push(from && from.sourceSpan || null);
  5269. }
  5270. if (newLine) {
  5271. this._lines.push(new _EmittedLine(this._indent));
  5272. }
  5273. }
  5274. removeEmptyLastLine() {
  5275. if (this.lineIsEmpty()) {
  5276. this._lines.pop();
  5277. }
  5278. }
  5279. incIndent() {
  5280. this._indent++;
  5281. if (this.lineIsEmpty()) {
  5282. this._currentLine.indent = this._indent;
  5283. }
  5284. }
  5285. decIndent() {
  5286. this._indent--;
  5287. if (this.lineIsEmpty()) {
  5288. this._currentLine.indent = this._indent;
  5289. }
  5290. }
  5291. pushClass(clazz) { this._classes.push(clazz); }
  5292. popClass() { return this._classes.pop(); }
  5293. get currentClass() {
  5294. return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
  5295. }
  5296. toSource() {
  5297. return this.sourceLines
  5298. .map(l => l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : '')
  5299. .join('\n');
  5300. }
  5301. toSourceMapGenerator(genFilePath, startsAtLine = 0) {
  5302. const map = new SourceMapGenerator(genFilePath);
  5303. let firstOffsetMapped = false;
  5304. const mapFirstOffsetIfNeeded = () => {
  5305. if (!firstOffsetMapped) {
  5306. // Add a single space so that tools won't try to load the file from disk.
  5307. // Note: We are using virtual urls like `ng:///`, so we have to
  5308. // provide a content here.
  5309. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
  5310. firstOffsetMapped = true;
  5311. }
  5312. };
  5313. for (let i = 0; i < startsAtLine; i++) {
  5314. map.addLine();
  5315. mapFirstOffsetIfNeeded();
  5316. }
  5317. this.sourceLines.forEach((line, lineIdx) => {
  5318. map.addLine();
  5319. const spans = line.srcSpans;
  5320. const parts = line.parts;
  5321. let col0 = line.indent * _INDENT_WITH.length;
  5322. let spanIdx = 0;
  5323. // skip leading parts without source spans
  5324. while (spanIdx < spans.length && !spans[spanIdx]) {
  5325. col0 += parts[spanIdx].length;
  5326. spanIdx++;
  5327. }
  5328. if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
  5329. firstOffsetMapped = true;
  5330. }
  5331. else {
  5332. mapFirstOffsetIfNeeded();
  5333. }
  5334. while (spanIdx < spans.length) {
  5335. const span = spans[spanIdx];
  5336. const source = span.start.file;
  5337. const sourceLine = span.start.line;
  5338. const sourceCol = span.start.col;
  5339. map.addSource(source.url, source.content)
  5340. .addMapping(col0, source.url, sourceLine, sourceCol);
  5341. col0 += parts[spanIdx].length;
  5342. spanIdx++;
  5343. // assign parts without span or the same span to the previous segment
  5344. while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
  5345. col0 += parts[spanIdx].length;
  5346. spanIdx++;
  5347. }
  5348. }
  5349. });
  5350. return map;
  5351. }
  5352. setPreambleLineCount(count) { return this._preambleLineCount = count; }
  5353. spanOf(line, column) {
  5354. const emittedLine = this._lines[line - this._preambleLineCount];
  5355. if (emittedLine) {
  5356. let columnsLeft = column - _createIndent(emittedLine.indent).length;
  5357. for (let partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
  5358. const part = emittedLine.parts[partIndex];
  5359. if (part.length > columnsLeft) {
  5360. return emittedLine.srcSpans[partIndex];
  5361. }
  5362. columnsLeft -= part.length;
  5363. }
  5364. }
  5365. return null;
  5366. }
  5367. get sourceLines() {
  5368. if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
  5369. return this._lines.slice(0, -1);
  5370. }
  5371. return this._lines;
  5372. }
  5373. }
  5374. class AbstractEmitterVisitor {
  5375. constructor(_escapeDollarInStrings) {
  5376. this._escapeDollarInStrings = _escapeDollarInStrings;
  5377. }
  5378. visitExpressionStmt(stmt, ctx) {
  5379. stmt.expr.visitExpression(this, ctx);
  5380. ctx.println(stmt, ';');
  5381. return null;
  5382. }
  5383. visitReturnStmt(stmt, ctx) {
  5384. ctx.print(stmt, `return `);
  5385. stmt.value.visitExpression(this, ctx);
  5386. ctx.println(stmt, ';');
  5387. return null;
  5388. }
  5389. visitIfStmt(stmt, ctx) {
  5390. ctx.print(stmt, `if (`);
  5391. stmt.condition.visitExpression(this, ctx);
  5392. ctx.print(stmt, `) {`);
  5393. const hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
  5394. if (stmt.trueCase.length <= 1 && !hasElseCase) {
  5395. ctx.print(stmt, ` `);
  5396. this.visitAllStatements(stmt.trueCase, ctx);
  5397. ctx.removeEmptyLastLine();
  5398. ctx.print(stmt, ` `);
  5399. }
  5400. else {
  5401. ctx.println();
  5402. ctx.incIndent();
  5403. this.visitAllStatements(stmt.trueCase, ctx);
  5404. ctx.decIndent();
  5405. if (hasElseCase) {
  5406. ctx.println(stmt, `} else {`);
  5407. ctx.incIndent();
  5408. this.visitAllStatements(stmt.falseCase, ctx);
  5409. ctx.decIndent();
  5410. }
  5411. }
  5412. ctx.println(stmt, `}`);
  5413. return null;
  5414. }
  5415. visitThrowStmt(stmt, ctx) {
  5416. ctx.print(stmt, `throw `);
  5417. stmt.error.visitExpression(this, ctx);
  5418. ctx.println(stmt, `;`);
  5419. return null;
  5420. }
  5421. visitCommentStmt(stmt, ctx) {
  5422. if (stmt.multiline) {
  5423. ctx.println(stmt, `/* ${stmt.comment} */`);
  5424. }
  5425. else {
  5426. stmt.comment.split('\n').forEach((line) => { ctx.println(stmt, `// ${line}`); });
  5427. }
  5428. return null;
  5429. }
  5430. visitJSDocCommentStmt(stmt, ctx) {
  5431. ctx.println(stmt, `/*${stmt.toString()}*/`);
  5432. return null;
  5433. }
  5434. visitWriteVarExpr(expr, ctx) {
  5435. const lineWasEmpty = ctx.lineIsEmpty();
  5436. if (!lineWasEmpty) {
  5437. ctx.print(expr, '(');
  5438. }
  5439. ctx.print(expr, `${expr.name} = `);
  5440. expr.value.visitExpression(this, ctx);
  5441. if (!lineWasEmpty) {
  5442. ctx.print(expr, ')');
  5443. }
  5444. return null;
  5445. }
  5446. visitWriteKeyExpr(expr, ctx) {
  5447. const lineWasEmpty = ctx.lineIsEmpty();
  5448. if (!lineWasEmpty) {
  5449. ctx.print(expr, '(');
  5450. }
  5451. expr.receiver.visitExpression(this, ctx);
  5452. ctx.print(expr, `[`);
  5453. expr.index.visitExpression(this, ctx);
  5454. ctx.print(expr, `] = `);
  5455. expr.value.visitExpression(this, ctx);
  5456. if (!lineWasEmpty) {
  5457. ctx.print(expr, ')');
  5458. }
  5459. return null;
  5460. }
  5461. visitWritePropExpr(expr, ctx) {
  5462. const lineWasEmpty = ctx.lineIsEmpty();
  5463. if (!lineWasEmpty) {
  5464. ctx.print(expr, '(');
  5465. }
  5466. expr.receiver.visitExpression(this, ctx);
  5467. ctx.print(expr, `.${expr.name} = `);
  5468. expr.value.visitExpression(this, ctx);
  5469. if (!lineWasEmpty) {
  5470. ctx.print(expr, ')');
  5471. }
  5472. return null;
  5473. }
  5474. visitInvokeMethodExpr(expr, ctx) {
  5475. expr.receiver.visitExpression(this, ctx);
  5476. let name = expr.name;
  5477. if (expr.builtin != null) {
  5478. name = this.getBuiltinMethodName(expr.builtin);
  5479. if (name == null) {
  5480. // some builtins just mean to skip the call.
  5481. return null;
  5482. }
  5483. }
  5484. ctx.print(expr, `.${name}(`);
  5485. this.visitAllExpressions(expr.args, ctx, `,`);
  5486. ctx.print(expr, `)`);
  5487. return null;
  5488. }
  5489. visitInvokeFunctionExpr(expr, ctx) {
  5490. expr.fn.visitExpression(this, ctx);
  5491. ctx.print(expr, `(`);
  5492. this.visitAllExpressions(expr.args, ctx, ',');
  5493. ctx.print(expr, `)`);
  5494. return null;
  5495. }
  5496. visitWrappedNodeExpr(ast, ctx) {
  5497. throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
  5498. }
  5499. visitTypeofExpr(expr, ctx) {
  5500. ctx.print(expr, 'typeof ');
  5501. expr.expr.visitExpression(this, ctx);
  5502. }
  5503. visitReadVarExpr(ast, ctx) {
  5504. let varName = ast.name;
  5505. if (ast.builtin != null) {
  5506. switch (ast.builtin) {
  5507. case BuiltinVar.Super:
  5508. varName = 'super';
  5509. break;
  5510. case BuiltinVar.This:
  5511. varName = 'this';
  5512. break;
  5513. case BuiltinVar.CatchError:
  5514. varName = CATCH_ERROR_VAR$1.name;
  5515. break;
  5516. case BuiltinVar.CatchStack:
  5517. varName = CATCH_STACK_VAR$1.name;
  5518. break;
  5519. default:
  5520. throw new Error(`Unknown builtin variable ${ast.builtin}`);
  5521. }
  5522. }
  5523. ctx.print(ast, varName);
  5524. return null;
  5525. }
  5526. visitInstantiateExpr(ast, ctx) {
  5527. ctx.print(ast, `new `);
  5528. ast.classExpr.visitExpression(this, ctx);
  5529. ctx.print(ast, `(`);
  5530. this.visitAllExpressions(ast.args, ctx, ',');
  5531. ctx.print(ast, `)`);
  5532. return null;
  5533. }
  5534. visitLiteralExpr(ast, ctx) {
  5535. const value = ast.value;
  5536. if (typeof value === 'string') {
  5537. ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
  5538. }
  5539. else {
  5540. ctx.print(ast, `${value}`);
  5541. }
  5542. return null;
  5543. }
  5544. visitConditionalExpr(ast, ctx) {
  5545. ctx.print(ast, `(`);
  5546. ast.condition.visitExpression(this, ctx);
  5547. ctx.print(ast, '? ');
  5548. ast.trueCase.visitExpression(this, ctx);
  5549. ctx.print(ast, ': ');
  5550. ast.falseCase.visitExpression(this, ctx);
  5551. ctx.print(ast, `)`);
  5552. return null;
  5553. }
  5554. visitNotExpr(ast, ctx) {
  5555. ctx.print(ast, '!');
  5556. ast.condition.visitExpression(this, ctx);
  5557. return null;
  5558. }
  5559. visitAssertNotNullExpr(ast, ctx) {
  5560. ast.condition.visitExpression(this, ctx);
  5561. return null;
  5562. }
  5563. visitBinaryOperatorExpr(ast, ctx) {
  5564. let opStr;
  5565. switch (ast.operator) {
  5566. case BinaryOperator.Equals:
  5567. opStr = '==';
  5568. break;
  5569. case BinaryOperator.Identical:
  5570. opStr = '===';
  5571. break;
  5572. case BinaryOperator.NotEquals:
  5573. opStr = '!=';
  5574. break;
  5575. case BinaryOperator.NotIdentical:
  5576. opStr = '!==';
  5577. break;
  5578. case BinaryOperator.And:
  5579. opStr = '&&';
  5580. break;
  5581. case BinaryOperator.BitwiseAnd:
  5582. opStr = '&';
  5583. break;
  5584. case BinaryOperator.Or:
  5585. opStr = '||';
  5586. break;
  5587. case BinaryOperator.Plus:
  5588. opStr = '+';
  5589. break;
  5590. case BinaryOperator.Minus:
  5591. opStr = '-';
  5592. break;
  5593. case BinaryOperator.Divide:
  5594. opStr = '/';
  5595. break;
  5596. case BinaryOperator.Multiply:
  5597. opStr = '*';
  5598. break;
  5599. case BinaryOperator.Modulo:
  5600. opStr = '%';
  5601. break;
  5602. case BinaryOperator.Lower:
  5603. opStr = '<';
  5604. break;
  5605. case BinaryOperator.LowerEquals:
  5606. opStr = '<=';
  5607. break;
  5608. case BinaryOperator.Bigger:
  5609. opStr = '>';
  5610. break;
  5611. case BinaryOperator.BiggerEquals:
  5612. opStr = '>=';
  5613. break;
  5614. default:
  5615. throw new Error(`Unknown operator ${ast.operator}`);
  5616. }
  5617. if (ast.parens)
  5618. ctx.print(ast, `(`);
  5619. ast.lhs.visitExpression(this, ctx);
  5620. ctx.print(ast, ` ${opStr} `);
  5621. ast.rhs.visitExpression(this, ctx);
  5622. if (ast.parens)
  5623. ctx.print(ast, `)`);
  5624. return null;
  5625. }
  5626. visitReadPropExpr(ast, ctx) {
  5627. ast.receiver.visitExpression(this, ctx);
  5628. ctx.print(ast, `.`);
  5629. ctx.print(ast, ast.name);
  5630. return null;
  5631. }
  5632. visitReadKeyExpr(ast, ctx) {
  5633. ast.receiver.visitExpression(this, ctx);
  5634. ctx.print(ast, `[`);
  5635. ast.index.visitExpression(this, ctx);
  5636. ctx.print(ast, `]`);
  5637. return null;
  5638. }
  5639. visitLiteralArrayExpr(ast, ctx) {
  5640. ctx.print(ast, `[`);
  5641. this.visitAllExpressions(ast.entries, ctx, ',');
  5642. ctx.print(ast, `]`);
  5643. return null;
  5644. }
  5645. visitLiteralMapExpr(ast, ctx) {
  5646. ctx.print(ast, `{`);
  5647. this.visitAllObjects(entry => {
  5648. ctx.print(ast, `${escapeIdentifier(entry.key, this._escapeDollarInStrings, entry.quoted)}:`);
  5649. entry.value.visitExpression(this, ctx);
  5650. }, ast.entries, ctx, ',');
  5651. ctx.print(ast, `}`);
  5652. return null;
  5653. }
  5654. visitCommaExpr(ast, ctx) {
  5655. ctx.print(ast, '(');
  5656. this.visitAllExpressions(ast.parts, ctx, ',');
  5657. ctx.print(ast, ')');
  5658. return null;
  5659. }
  5660. visitAllExpressions(expressions, ctx, separator) {
  5661. this.visitAllObjects(expr => expr.visitExpression(this, ctx), expressions, ctx, separator);
  5662. }
  5663. visitAllObjects(handler, expressions, ctx, separator) {
  5664. let incrementedIndent = false;
  5665. for (let i = 0; i < expressions.length; i++) {
  5666. if (i > 0) {
  5667. if (ctx.lineLength() > 80) {
  5668. ctx.print(null, separator, true);
  5669. if (!incrementedIndent) {
  5670. // continuation are marked with double indent.
  5671. ctx.incIndent();
  5672. ctx.incIndent();
  5673. incrementedIndent = true;
  5674. }
  5675. }
  5676. else {
  5677. ctx.print(null, separator, false);
  5678. }
  5679. }
  5680. handler(expressions[i]);
  5681. }
  5682. if (incrementedIndent) {
  5683. // continuation are marked with double indent.
  5684. ctx.decIndent();
  5685. ctx.decIndent();
  5686. }
  5687. }
  5688. visitAllStatements(statements, ctx) {
  5689. statements.forEach((stmt) => stmt.visitStatement(this, ctx));
  5690. }
  5691. }
  5692. function escapeIdentifier(input, escapeDollar, alwaysQuote = true) {
  5693. if (input == null) {
  5694. return null;
  5695. }
  5696. const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match) => {
  5697. if (match[0] == '$') {
  5698. return escapeDollar ? '\\$' : '$';
  5699. }
  5700. else if (match[0] == '\n') {
  5701. return '\\n';
  5702. }
  5703. else if (match[0] == '\r') {
  5704. return '\\r';
  5705. }
  5706. else {
  5707. return `\\${match[0]}`;
  5708. }
  5709. });
  5710. const requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
  5711. return requiresQuotes ? `'${body}'` : body;
  5712. }
  5713. function _createIndent(count) {
  5714. let res = '';
  5715. for (let i = 0; i < count; i++) {
  5716. res += _INDENT_WITH;
  5717. }
  5718. return res;
  5719. }
  5720. /**
  5721. * @license
  5722. * Copyright Google Inc. All Rights Reserved.
  5723. *
  5724. * Use of this source code is governed by an MIT-style license that can be
  5725. * found in the LICENSE file at https://angular.io/license
  5726. */
  5727. class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
  5728. constructor() { super(false); }
  5729. visitDeclareClassStmt(stmt, ctx) {
  5730. ctx.pushClass(stmt);
  5731. this._visitClassConstructor(stmt, ctx);
  5732. if (stmt.parent != null) {
  5733. ctx.print(stmt, `${stmt.name}.prototype = Object.create(`);
  5734. stmt.parent.visitExpression(this, ctx);
  5735. ctx.println(stmt, `.prototype);`);
  5736. }
  5737. stmt.getters.forEach((getter) => this._visitClassGetter(stmt, getter, ctx));
  5738. stmt.methods.forEach((method) => this._visitClassMethod(stmt, method, ctx));
  5739. ctx.popClass();
  5740. return null;
  5741. }
  5742. _visitClassConstructor(stmt, ctx) {
  5743. ctx.print(stmt, `function ${stmt.name}(`);
  5744. if (stmt.constructorMethod != null) {
  5745. this._visitParams(stmt.constructorMethod.params, ctx);
  5746. }
  5747. ctx.println(stmt, `) {`);
  5748. ctx.incIndent();
  5749. if (stmt.constructorMethod != null) {
  5750. if (stmt.constructorMethod.body.length > 0) {
  5751. ctx.println(stmt, `var self = this;`);
  5752. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  5753. }
  5754. }
  5755. ctx.decIndent();
  5756. ctx.println(stmt, `}`);
  5757. }
  5758. _visitClassGetter(stmt, getter, ctx) {
  5759. ctx.println(stmt, `Object.defineProperty(${stmt.name}.prototype, '${getter.name}', { get: function() {`);
  5760. ctx.incIndent();
  5761. if (getter.body.length > 0) {
  5762. ctx.println(stmt, `var self = this;`);
  5763. this.visitAllStatements(getter.body, ctx);
  5764. }
  5765. ctx.decIndent();
  5766. ctx.println(stmt, `}});`);
  5767. }
  5768. _visitClassMethod(stmt, method, ctx) {
  5769. ctx.print(stmt, `${stmt.name}.prototype.${method.name} = function(`);
  5770. this._visitParams(method.params, ctx);
  5771. ctx.println(stmt, `) {`);
  5772. ctx.incIndent();
  5773. if (method.body.length > 0) {
  5774. ctx.println(stmt, `var self = this;`);
  5775. this.visitAllStatements(method.body, ctx);
  5776. }
  5777. ctx.decIndent();
  5778. ctx.println(stmt, `};`);
  5779. }
  5780. visitWrappedNodeExpr(ast, ctx) {
  5781. throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
  5782. }
  5783. visitReadVarExpr(ast, ctx) {
  5784. if (ast.builtin === BuiltinVar.This) {
  5785. ctx.print(ast, 'self');
  5786. }
  5787. else if (ast.builtin === BuiltinVar.Super) {
  5788. throw new Error(`'super' needs to be handled at a parent ast node, not at the variable level!`);
  5789. }
  5790. else {
  5791. super.visitReadVarExpr(ast, ctx);
  5792. }
  5793. return null;
  5794. }
  5795. visitDeclareVarStmt(stmt, ctx) {
  5796. ctx.print(stmt, `var ${stmt.name}`);
  5797. if (stmt.value) {
  5798. ctx.print(stmt, ' = ');
  5799. stmt.value.visitExpression(this, ctx);
  5800. }
  5801. ctx.println(stmt, `;`);
  5802. return null;
  5803. }
  5804. visitCastExpr(ast, ctx) {
  5805. ast.value.visitExpression(this, ctx);
  5806. return null;
  5807. }
  5808. visitInvokeFunctionExpr(expr, ctx) {
  5809. const fnExpr = expr.fn;
  5810. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
  5811. ctx.currentClass.parent.visitExpression(this, ctx);
  5812. ctx.print(expr, `.call(this`);
  5813. if (expr.args.length > 0) {
  5814. ctx.print(expr, `, `);
  5815. this.visitAllExpressions(expr.args, ctx, ',');
  5816. }
  5817. ctx.print(expr, `)`);
  5818. }
  5819. else {
  5820. super.visitInvokeFunctionExpr(expr, ctx);
  5821. }
  5822. return null;
  5823. }
  5824. visitFunctionExpr(ast, ctx) {
  5825. ctx.print(ast, `function${ast.name ? ' ' + ast.name : ''}(`);
  5826. this._visitParams(ast.params, ctx);
  5827. ctx.println(ast, `) {`);
  5828. ctx.incIndent();
  5829. this.visitAllStatements(ast.statements, ctx);
  5830. ctx.decIndent();
  5831. ctx.print(ast, `}`);
  5832. return null;
  5833. }
  5834. visitDeclareFunctionStmt(stmt, ctx) {
  5835. ctx.print(stmt, `function ${stmt.name}(`);
  5836. this._visitParams(stmt.params, ctx);
  5837. ctx.println(stmt, `) {`);
  5838. ctx.incIndent();
  5839. this.visitAllStatements(stmt.statements, ctx);
  5840. ctx.decIndent();
  5841. ctx.println(stmt, `}`);
  5842. return null;
  5843. }
  5844. visitTryCatchStmt(stmt, ctx) {
  5845. ctx.println(stmt, `try {`);
  5846. ctx.incIndent();
  5847. this.visitAllStatements(stmt.bodyStmts, ctx);
  5848. ctx.decIndent();
  5849. ctx.println(stmt, `} catch (${CATCH_ERROR_VAR$1.name}) {`);
  5850. ctx.incIndent();
  5851. const catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
  5852. StmtModifier.Final
  5853. ])].concat(stmt.catchStmts);
  5854. this.visitAllStatements(catchStmts, ctx);
  5855. ctx.decIndent();
  5856. ctx.println(stmt, `}`);
  5857. return null;
  5858. }
  5859. _visitParams(params, ctx) {
  5860. this.visitAllObjects(param => ctx.print(null, param.name), params, ctx, ',');
  5861. }
  5862. getBuiltinMethodName(method) {
  5863. let name;
  5864. switch (method) {
  5865. case BuiltinMethod.ConcatArray:
  5866. name = 'concat';
  5867. break;
  5868. case BuiltinMethod.SubscribeObservable:
  5869. name = 'subscribe';
  5870. break;
  5871. case BuiltinMethod.Bind:
  5872. name = 'bind';
  5873. break;
  5874. default:
  5875. throw new Error(`Unknown builtin method: ${method}`);
  5876. }
  5877. return name;
  5878. }
  5879. }
  5880. /**
  5881. * @license
  5882. * Copyright Google Inc. All Rights Reserved.
  5883. *
  5884. * Use of this source code is governed by an MIT-style license that can be
  5885. * found in the LICENSE file at https://angular.io/license
  5886. */
  5887. /**
  5888. * A helper class to manage the evaluation of JIT generated code.
  5889. */
  5890. class JitEvaluator {
  5891. /**
  5892. *
  5893. * @param sourceUrl The URL of the generated code.
  5894. * @param statements An array of Angular statement AST nodes to be evaluated.
  5895. * @param reflector A helper used when converting the statements to executable code.
  5896. * @param createSourceMaps If true then create a source-map for the generated code and include it
  5897. * inline as a source-map comment.
  5898. * @returns A map of all the variables in the generated code.
  5899. */
  5900. evaluateStatements(sourceUrl, statements, reflector, createSourceMaps) {
  5901. const converter = new JitEmitterVisitor(reflector);
  5902. const ctx = EmitterVisitorContext.createRoot();
  5903. // Ensure generated code is in strict mode
  5904. if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
  5905. statements = [
  5906. literal('use strict').toStmt(),
  5907. ...statements,
  5908. ];
  5909. }
  5910. converter.visitAllStatements(statements, ctx);
  5911. converter.createReturnStmt(ctx);
  5912. return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
  5913. }
  5914. /**
  5915. * Evaluate a piece of JIT generated code.
  5916. * @param sourceUrl The URL of this generated code.
  5917. * @param ctx A context object that contains an AST of the code to be evaluated.
  5918. * @param vars A map containing the names and values of variables that the evaluated code might
  5919. * reference.
  5920. * @param createSourceMap If true then create a source-map for the generated code and include it
  5921. * inline as a source-map comment.
  5922. * @returns The result of evaluating the code.
  5923. */
  5924. evaluateCode(sourceUrl, ctx, vars, createSourceMap) {
  5925. let fnBody = `"use strict";${ctx.toSource()}\n//# sourceURL=${sourceUrl}`;
  5926. const fnArgNames = [];
  5927. const fnArgValues = [];
  5928. for (const argName in vars) {
  5929. fnArgValues.push(vars[argName]);
  5930. fnArgNames.push(argName);
  5931. }
  5932. if (createSourceMap) {
  5933. // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
  5934. // E.g. ```
  5935. // function anonymous(a,b,c
  5936. // /**/) { ... }```
  5937. // We don't want to hard code this fact, so we auto detect it via an empty function first.
  5938. const emptyFn = new Function(...fnArgNames.concat('return null;')).toString();
  5939. const headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
  5940. fnBody += `\n${ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment()}`;
  5941. }
  5942. const fn = new Function(...fnArgNames.concat(fnBody));
  5943. return this.executeFunction(fn, fnArgValues);
  5944. }
  5945. /**
  5946. * Execute a JIT generated function by calling it.
  5947. *
  5948. * This method can be overridden in tests to capture the functions that are generated
  5949. * by this `JitEvaluator` class.
  5950. *
  5951. * @param fn A function to execute.
  5952. * @param args The arguments to pass to the function being executed.
  5953. * @returns The return value of the executed function.
  5954. */
  5955. executeFunction(fn, args) { return fn(...args); }
  5956. }
  5957. /**
  5958. * An Angular AST visitor that converts AST nodes into executable JavaScript code.
  5959. */
  5960. class JitEmitterVisitor extends AbstractJsEmitterVisitor {
  5961. constructor(reflector) {
  5962. super();
  5963. this.reflector = reflector;
  5964. this._evalArgNames = [];
  5965. this._evalArgValues = [];
  5966. this._evalExportedVars = [];
  5967. }
  5968. createReturnStmt(ctx) {
  5969. const stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(resultVar => new LiteralMapEntry(resultVar, variable(resultVar), false))));
  5970. stmt.visitStatement(this, ctx);
  5971. }
  5972. getArgs() {
  5973. const result = {};
  5974. for (let i = 0; i < this._evalArgNames.length; i++) {
  5975. result[this._evalArgNames[i]] = this._evalArgValues[i];
  5976. }
  5977. return result;
  5978. }
  5979. visitExternalExpr(ast, ctx) {
  5980. this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
  5981. return null;
  5982. }
  5983. visitWrappedNodeExpr(ast, ctx) {
  5984. this._emitReferenceToExternal(ast, ast.node, ctx);
  5985. return null;
  5986. }
  5987. visitDeclareVarStmt(stmt, ctx) {
  5988. if (stmt.hasModifier(StmtModifier.Exported)) {
  5989. this._evalExportedVars.push(stmt.name);
  5990. }
  5991. return super.visitDeclareVarStmt(stmt, ctx);
  5992. }
  5993. visitDeclareFunctionStmt(stmt, ctx) {
  5994. if (stmt.hasModifier(StmtModifier.Exported)) {
  5995. this._evalExportedVars.push(stmt.name);
  5996. }
  5997. return super.visitDeclareFunctionStmt(stmt, ctx);
  5998. }
  5999. visitDeclareClassStmt(stmt, ctx) {
  6000. if (stmt.hasModifier(StmtModifier.Exported)) {
  6001. this._evalExportedVars.push(stmt.name);
  6002. }
  6003. return super.visitDeclareClassStmt(stmt, ctx);
  6004. }
  6005. _emitReferenceToExternal(ast, value, ctx) {
  6006. let id = this._evalArgValues.indexOf(value);
  6007. if (id === -1) {
  6008. id = this._evalArgValues.length;
  6009. this._evalArgValues.push(value);
  6010. const name = identifierName({ reference: value }) || 'val';
  6011. this._evalArgNames.push(`jit_${name}_${id}`);
  6012. }
  6013. ctx.print(ast, this._evalArgNames[id]);
  6014. }
  6015. }
  6016. function isUseStrictStatement(statement) {
  6017. return statement.isEquivalent(literal('use strict').toStmt());
  6018. }
  6019. /**
  6020. * @license
  6021. * Copyright Google Inc. All Rights Reserved.
  6022. *
  6023. * Use of this source code is governed by an MIT-style license that can be
  6024. * found in the LICENSE file at https://angular.io/license
  6025. */
  6026. /**
  6027. * Implementation of `CompileReflector` which resolves references to @angular/core
  6028. * symbols at runtime, according to a consumer-provided mapping.
  6029. *
  6030. * Only supports `resolveExternalReference`, all other methods throw.
  6031. */
  6032. class R3JitReflector {
  6033. constructor(context) {
  6034. this.context = context;
  6035. }
  6036. resolveExternalReference(ref) {
  6037. // This reflector only handles @angular/core imports.
  6038. if (ref.moduleName !== '@angular/core') {
  6039. throw new Error(`Cannot resolve external reference to ${ref.moduleName}, only references to @angular/core are supported.`);
  6040. }
  6041. if (!this.context.hasOwnProperty(ref.name)) {
  6042. throw new Error(`No value provided for @angular/core symbol '${ref.name}'.`);
  6043. }
  6044. return this.context[ref.name];
  6045. }
  6046. parameters(typeOrFunc) { throw new Error('Not implemented.'); }
  6047. annotations(typeOrFunc) { throw new Error('Not implemented.'); }
  6048. shallowAnnotations(typeOrFunc) { throw new Error('Not implemented.'); }
  6049. tryAnnotations(typeOrFunc) { throw new Error('Not implemented.'); }
  6050. propMetadata(typeOrFunc) { throw new Error('Not implemented.'); }
  6051. hasLifecycleHook(type, lcProperty) { throw new Error('Not implemented.'); }
  6052. guards(typeOrFunc) { throw new Error('Not implemented.'); }
  6053. componentModuleUrl(type, cmpMetadata) { throw new Error('Not implemented.'); }
  6054. }
  6055. /**
  6056. * @license
  6057. * Copyright Google Inc. All Rights Reserved.
  6058. *
  6059. * Use of this source code is governed by an MIT-style license that can be
  6060. * found in the LICENSE file at https://angular.io/license
  6061. */
  6062. /**
  6063. * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
  6064. */
  6065. function compileNgModule(meta) {
  6066. const { type: moduleType, bootstrap, declarations, imports, exports, schemas, containsForwardDecls, emitInline, id } = meta;
  6067. const additionalStatements = [];
  6068. const definitionMap = {
  6069. type: moduleType
  6070. };
  6071. // Only generate the keys in the metadata if the arrays have values.
  6072. if (bootstrap.length) {
  6073. definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
  6074. }
  6075. // If requested to emit scope information inline, pass the declarations, imports and exports to
  6076. // the `ɵɵdefineNgModule` call. The JIT compilation uses this.
  6077. if (emitInline) {
  6078. if (declarations.length) {
  6079. definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
  6080. }
  6081. if (imports.length) {
  6082. definitionMap.imports = refsToArray(imports, containsForwardDecls);
  6083. }
  6084. if (exports.length) {
  6085. definitionMap.exports = refsToArray(exports, containsForwardDecls);
  6086. }
  6087. }
  6088. // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
  6089. // prevent tree-shaking of the declarations, imports and exports references.
  6090. else {
  6091. const setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
  6092. if (setNgModuleScopeCall !== null) {
  6093. additionalStatements.push(setNgModuleScopeCall);
  6094. }
  6095. }
  6096. if (schemas && schemas.length) {
  6097. definitionMap.schemas = literalArr(schemas.map(ref => ref.value));
  6098. }
  6099. if (id) {
  6100. definitionMap.id = id;
  6101. }
  6102. const expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
  6103. const type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [
  6104. new ExpressionType(moduleType), tupleTypeOf(declarations), tupleTypeOf(imports),
  6105. tupleTypeOf(exports)
  6106. ]));
  6107. return { expression, type, additionalStatements };
  6108. }
  6109. /**
  6110. * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
  6111. * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
  6112. * such that the references to declarations, imports and exports may be elided causing these
  6113. * symbols to become tree-shakeable.
  6114. */
  6115. function generateSetNgModuleScopeCall(meta) {
  6116. const { type: moduleType, declarations, imports, exports, containsForwardDecls } = meta;
  6117. const scopeMap = {};
  6118. if (declarations.length) {
  6119. scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
  6120. }
  6121. if (imports.length) {
  6122. scopeMap.imports = refsToArray(imports, containsForwardDecls);
  6123. }
  6124. if (exports.length) {
  6125. scopeMap.exports = refsToArray(exports, containsForwardDecls);
  6126. }
  6127. if (Object.keys(scopeMap).length === 0) {
  6128. return null;
  6129. }
  6130. const fnCall = new InvokeFunctionExpr(
  6131. /* fn */ importExpr(Identifiers$1.setNgModuleScope),
  6132. /* args */ [moduleType, mapToMapExpression(scopeMap)],
  6133. /* type */ undefined,
  6134. /* sourceSpan */ undefined,
  6135. /* pure */ true);
  6136. return fnCall.toStmt();
  6137. }
  6138. function compileInjector(meta) {
  6139. const result = compileFactoryFunction({
  6140. name: meta.name,
  6141. type: meta.type,
  6142. deps: meta.deps,
  6143. injectFn: Identifiers$1.inject,
  6144. });
  6145. const definitionMap = {
  6146. factory: result.factory,
  6147. };
  6148. if (meta.providers !== null) {
  6149. definitionMap.providers = meta.providers;
  6150. }
  6151. if (meta.imports.length > 0) {
  6152. definitionMap.imports = literalArr(meta.imports);
  6153. }
  6154. const expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]);
  6155. const type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type)]));
  6156. return { expression, type, statements: result.statements };
  6157. }
  6158. // TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations.
  6159. function compileNgModuleFromRender2(ctx, ngModule, injectableCompiler) {
  6160. const className = identifierName(ngModule.type);
  6161. const rawImports = ngModule.rawImports ? [ngModule.rawImports] : [];
  6162. const rawExports = ngModule.rawExports ? [ngModule.rawExports] : [];
  6163. const injectorDefArg = mapLiteral({
  6164. 'factory': injectableCompiler.factoryFor({ type: ngModule.type, symbol: ngModule.type.reference }, ctx),
  6165. 'providers': convertMetaToOutput(ngModule.rawProviders, ctx),
  6166. 'imports': convertMetaToOutput([...rawImports, ...rawExports], ctx),
  6167. });
  6168. const injectorDef = importExpr(Identifiers$1.defineInjector).callFn([injectorDefArg]);
  6169. ctx.statements.push(new ClassStmt(
  6170. /* name */ className,
  6171. /* parent */ null,
  6172. /* fields */ [new ClassField(
  6173. /* name */ 'ngInjectorDef',
  6174. /* type */ INFERRED_TYPE,
  6175. /* modifiers */ [StmtModifier.Static],
  6176. /* initializer */ injectorDef)],
  6177. /* getters */ [],
  6178. /* constructorMethod */ new ClassMethod(null, [], []),
  6179. /* methods */ []));
  6180. }
  6181. function tupleTypeOf(exp) {
  6182. const types = exp.map(ref => typeofExpr(ref.type));
  6183. return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
  6184. }
  6185. function refsToArray(refs, shouldForwardDeclare) {
  6186. const values = literalArr(refs.map(ref => ref.value));
  6187. return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
  6188. }
  6189. /**
  6190. * @license
  6191. * Copyright Google Inc. All Rights Reserved.
  6192. *
  6193. * Use of this source code is governed by an MIT-style license that can be
  6194. * found in the LICENSE file at https://angular.io/license
  6195. */
  6196. function compilePipeFromMetadata(metadata) {
  6197. const definitionMapValues = [];
  6198. // e.g. `name: 'myPipe'`
  6199. definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
  6200. // e.g. `type: MyPipe`
  6201. definitionMapValues.push({ key: 'type', value: metadata.type, quoted: false });
  6202. const templateFactory = compileFactoryFunction({
  6203. name: metadata.name,
  6204. type: metadata.type,
  6205. deps: metadata.deps,
  6206. injectFn: Identifiers$1.directiveInject,
  6207. });
  6208. definitionMapValues.push({ key: 'factory', value: templateFactory.factory, quoted: false });
  6209. // e.g. `pure: true`
  6210. definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
  6211. const expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]);
  6212. const type = new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [
  6213. typeWithParameters(metadata.type, metadata.typeArgumentCount),
  6214. new ExpressionType(new LiteralExpr(metadata.pipeName)),
  6215. ]));
  6216. return { expression, type, statements: templateFactory.statements };
  6217. }
  6218. /**
  6219. * Write a pipe definition to the output context.
  6220. */
  6221. function compilePipeFromRender2(outputCtx, pipe, reflector) {
  6222. const name = identifierName(pipe.type);
  6223. if (!name) {
  6224. return error(`Cannot resolve the name of ${pipe.type}`);
  6225. }
  6226. const metadata = {
  6227. name,
  6228. pipeName: pipe.name,
  6229. type: outputCtx.importExpr(pipe.type.reference),
  6230. typeArgumentCount: 0,
  6231. deps: dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector),
  6232. pure: pipe.pure,
  6233. };
  6234. const res = compilePipeFromMetadata(metadata);
  6235. const definitionField = outputCtx.constantPool.propertyNameOf(3 /* Pipe */);
  6236. outputCtx.statements.push(new ClassStmt(
  6237. /* name */ name,
  6238. /* parent */ null,
  6239. /* fields */ [new ClassField(
  6240. /* name */ definitionField,
  6241. /* type */ INFERRED_TYPE,
  6242. /* modifiers */ [StmtModifier.Static],
  6243. /* initializer */ res.expression)],
  6244. /* getters */ [],
  6245. /* constructorMethod */ new ClassMethod(null, [], []),
  6246. /* methods */ []));
  6247. }
  6248. /**
  6249. * @license
  6250. * Copyright Google Inc. All Rights Reserved.
  6251. *
  6252. * Use of this source code is governed by an MIT-style license that can be
  6253. * found in the LICENSE file at https://angular.io/license
  6254. */
  6255. class ParserError {
  6256. constructor(message, input, errLocation, ctxLocation) {
  6257. this.input = input;
  6258. this.errLocation = errLocation;
  6259. this.ctxLocation = ctxLocation;
  6260. this.message = `Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`;
  6261. }
  6262. }
  6263. class ParseSpan {
  6264. constructor(start, end) {
  6265. this.start = start;
  6266. this.end = end;
  6267. }
  6268. }
  6269. class AST {
  6270. constructor(span) {
  6271. this.span = span;
  6272. }
  6273. visit(visitor, context = null) { return null; }
  6274. toString() { return 'AST'; }
  6275. }
  6276. /**
  6277. * Represents a quoted expression of the form:
  6278. *
  6279. * quote = prefix `:` uninterpretedExpression
  6280. * prefix = identifier
  6281. * uninterpretedExpression = arbitrary string
  6282. *
  6283. * A quoted expression is meant to be pre-processed by an AST transformer that
  6284. * converts it into another AST that no longer contains quoted expressions.
  6285. * It is meant to allow third-party developers to extend Angular template
  6286. * expression language. The `uninterpretedExpression` part of the quote is
  6287. * therefore not interpreted by the Angular's own expression parser.
  6288. */
  6289. class Quote extends AST {
  6290. constructor(span, prefix, uninterpretedExpression, location) {
  6291. super(span);
  6292. this.prefix = prefix;
  6293. this.uninterpretedExpression = uninterpretedExpression;
  6294. this.location = location;
  6295. }
  6296. visit(visitor, context = null) { return visitor.visitQuote(this, context); }
  6297. toString() { return 'Quote'; }
  6298. }
  6299. class EmptyExpr extends AST {
  6300. visit(visitor, context = null) {
  6301. // do nothing
  6302. }
  6303. }
  6304. class ImplicitReceiver extends AST {
  6305. visit(visitor, context = null) {
  6306. return visitor.visitImplicitReceiver(this, context);
  6307. }
  6308. }
  6309. /**
  6310. * Multiple expressions separated by a semicolon.
  6311. */
  6312. class Chain extends AST {
  6313. constructor(span, expressions) {
  6314. super(span);
  6315. this.expressions = expressions;
  6316. }
  6317. visit(visitor, context = null) { return visitor.visitChain(this, context); }
  6318. }
  6319. class Conditional extends AST {
  6320. constructor(span, condition, trueExp, falseExp) {
  6321. super(span);
  6322. this.condition = condition;
  6323. this.trueExp = trueExp;
  6324. this.falseExp = falseExp;
  6325. }
  6326. visit(visitor, context = null) {
  6327. return visitor.visitConditional(this, context);
  6328. }
  6329. }
  6330. class PropertyRead extends AST {
  6331. constructor(span, receiver, name) {
  6332. super(span);
  6333. this.receiver = receiver;
  6334. this.name = name;
  6335. }
  6336. visit(visitor, context = null) {
  6337. return visitor.visitPropertyRead(this, context);
  6338. }
  6339. }
  6340. class PropertyWrite extends AST {
  6341. constructor(span, receiver, name, value) {
  6342. super(span);
  6343. this.receiver = receiver;
  6344. this.name = name;
  6345. this.value = value;
  6346. }
  6347. visit(visitor, context = null) {
  6348. return visitor.visitPropertyWrite(this, context);
  6349. }
  6350. }
  6351. class SafePropertyRead extends AST {
  6352. constructor(span, receiver, name) {
  6353. super(span);
  6354. this.receiver = receiver;
  6355. this.name = name;
  6356. }
  6357. visit(visitor, context = null) {
  6358. return visitor.visitSafePropertyRead(this, context);
  6359. }
  6360. }
  6361. class KeyedRead extends AST {
  6362. constructor(span, obj, key) {
  6363. super(span);
  6364. this.obj = obj;
  6365. this.key = key;
  6366. }
  6367. visit(visitor, context = null) {
  6368. return visitor.visitKeyedRead(this, context);
  6369. }
  6370. }
  6371. class KeyedWrite extends AST {
  6372. constructor(span, obj, key, value) {
  6373. super(span);
  6374. this.obj = obj;
  6375. this.key = key;
  6376. this.value = value;
  6377. }
  6378. visit(visitor, context = null) {
  6379. return visitor.visitKeyedWrite(this, context);
  6380. }
  6381. }
  6382. class BindingPipe extends AST {
  6383. constructor(span, exp, name, args) {
  6384. super(span);
  6385. this.exp = exp;
  6386. this.name = name;
  6387. this.args = args;
  6388. }
  6389. visit(visitor, context = null) { return visitor.visitPipe(this, context); }
  6390. }
  6391. class LiteralPrimitive extends AST {
  6392. constructor(span, value) {
  6393. super(span);
  6394. this.value = value;
  6395. }
  6396. visit(visitor, context = null) {
  6397. return visitor.visitLiteralPrimitive(this, context);
  6398. }
  6399. }
  6400. class LiteralArray extends AST {
  6401. constructor(span, expressions) {
  6402. super(span);
  6403. this.expressions = expressions;
  6404. }
  6405. visit(visitor, context = null) {
  6406. return visitor.visitLiteralArray(this, context);
  6407. }
  6408. }
  6409. class LiteralMap extends AST {
  6410. constructor(span, keys, values) {
  6411. super(span);
  6412. this.keys = keys;
  6413. this.values = values;
  6414. }
  6415. visit(visitor, context = null) {
  6416. return visitor.visitLiteralMap(this, context);
  6417. }
  6418. }
  6419. class Interpolation extends AST {
  6420. constructor(span, strings, expressions) {
  6421. super(span);
  6422. this.strings = strings;
  6423. this.expressions = expressions;
  6424. }
  6425. visit(visitor, context = null) {
  6426. return visitor.visitInterpolation(this, context);
  6427. }
  6428. }
  6429. class Binary extends AST {
  6430. constructor(span, operation, left, right) {
  6431. super(span);
  6432. this.operation = operation;
  6433. this.left = left;
  6434. this.right = right;
  6435. }
  6436. visit(visitor, context = null) {
  6437. return visitor.visitBinary(this, context);
  6438. }
  6439. }
  6440. class PrefixNot extends AST {
  6441. constructor(span, expression) {
  6442. super(span);
  6443. this.expression = expression;
  6444. }
  6445. visit(visitor, context = null) {
  6446. return visitor.visitPrefixNot(this, context);
  6447. }
  6448. }
  6449. class NonNullAssert extends AST {
  6450. constructor(span, expression) {
  6451. super(span);
  6452. this.expression = expression;
  6453. }
  6454. visit(visitor, context = null) {
  6455. return visitor.visitNonNullAssert(this, context);
  6456. }
  6457. }
  6458. class MethodCall extends AST {
  6459. constructor(span, receiver, name, args) {
  6460. super(span);
  6461. this.receiver = receiver;
  6462. this.name = name;
  6463. this.args = args;
  6464. }
  6465. visit(visitor, context = null) {
  6466. return visitor.visitMethodCall(this, context);
  6467. }
  6468. }
  6469. class SafeMethodCall extends AST {
  6470. constructor(span, receiver, name, args) {
  6471. super(span);
  6472. this.receiver = receiver;
  6473. this.name = name;
  6474. this.args = args;
  6475. }
  6476. visit(visitor, context = null) {
  6477. return visitor.visitSafeMethodCall(this, context);
  6478. }
  6479. }
  6480. class FunctionCall extends AST {
  6481. constructor(span, target, args) {
  6482. super(span);
  6483. this.target = target;
  6484. this.args = args;
  6485. }
  6486. visit(visitor, context = null) {
  6487. return visitor.visitFunctionCall(this, context);
  6488. }
  6489. }
  6490. class ASTWithSource extends AST {
  6491. constructor(ast, source, location, errors) {
  6492. super(new ParseSpan(0, source == null ? 0 : source.length));
  6493. this.ast = ast;
  6494. this.source = source;
  6495. this.location = location;
  6496. this.errors = errors;
  6497. }
  6498. visit(visitor, context = null) { return this.ast.visit(visitor, context); }
  6499. toString() { return `${this.source} in ${this.location}`; }
  6500. }
  6501. class TemplateBinding {
  6502. constructor(span, key, keyIsVar, name, expression) {
  6503. this.span = span;
  6504. this.key = key;
  6505. this.keyIsVar = keyIsVar;
  6506. this.name = name;
  6507. this.expression = expression;
  6508. }
  6509. }
  6510. class NullAstVisitor {
  6511. visitBinary(ast, context) { }
  6512. visitChain(ast, context) { }
  6513. visitConditional(ast, context) { }
  6514. visitFunctionCall(ast, context) { }
  6515. visitImplicitReceiver(ast, context) { }
  6516. visitInterpolation(ast, context) { }
  6517. visitKeyedRead(ast, context) { }
  6518. visitKeyedWrite(ast, context) { }
  6519. visitLiteralArray(ast, context) { }
  6520. visitLiteralMap(ast, context) { }
  6521. visitLiteralPrimitive(ast, context) { }
  6522. visitMethodCall(ast, context) { }
  6523. visitPipe(ast, context) { }
  6524. visitPrefixNot(ast, context) { }
  6525. visitNonNullAssert(ast, context) { }
  6526. visitPropertyRead(ast, context) { }
  6527. visitPropertyWrite(ast, context) { }
  6528. visitQuote(ast, context) { }
  6529. visitSafeMethodCall(ast, context) { }
  6530. visitSafePropertyRead(ast, context) { }
  6531. }
  6532. class RecursiveAstVisitor$1 {
  6533. visitBinary(ast, context) {
  6534. ast.left.visit(this, context);
  6535. ast.right.visit(this, context);
  6536. return null;
  6537. }
  6538. visitChain(ast, context) { return this.visitAll(ast.expressions, context); }
  6539. visitConditional(ast, context) {
  6540. ast.condition.visit(this, context);
  6541. ast.trueExp.visit(this, context);
  6542. ast.falseExp.visit(this, context);
  6543. return null;
  6544. }
  6545. visitPipe(ast, context) {
  6546. ast.exp.visit(this, context);
  6547. this.visitAll(ast.args, context);
  6548. return null;
  6549. }
  6550. visitFunctionCall(ast, context) {
  6551. ast.target.visit(this, context);
  6552. this.visitAll(ast.args, context);
  6553. return null;
  6554. }
  6555. visitImplicitReceiver(ast, context) { return null; }
  6556. visitInterpolation(ast, context) {
  6557. return this.visitAll(ast.expressions, context);
  6558. }
  6559. visitKeyedRead(ast, context) {
  6560. ast.obj.visit(this, context);
  6561. ast.key.visit(this, context);
  6562. return null;
  6563. }
  6564. visitKeyedWrite(ast, context) {
  6565. ast.obj.visit(this, context);
  6566. ast.key.visit(this, context);
  6567. ast.value.visit(this, context);
  6568. return null;
  6569. }
  6570. visitLiteralArray(ast, context) {
  6571. return this.visitAll(ast.expressions, context);
  6572. }
  6573. visitLiteralMap(ast, context) { return this.visitAll(ast.values, context); }
  6574. visitLiteralPrimitive(ast, context) { return null; }
  6575. visitMethodCall(ast, context) {
  6576. ast.receiver.visit(this, context);
  6577. return this.visitAll(ast.args, context);
  6578. }
  6579. visitPrefixNot(ast, context) {
  6580. ast.expression.visit(this, context);
  6581. return null;
  6582. }
  6583. visitNonNullAssert(ast, context) {
  6584. ast.expression.visit(this, context);
  6585. return null;
  6586. }
  6587. visitPropertyRead(ast, context) {
  6588. ast.receiver.visit(this, context);
  6589. return null;
  6590. }
  6591. visitPropertyWrite(ast, context) {
  6592. ast.receiver.visit(this, context);
  6593. ast.value.visit(this, context);
  6594. return null;
  6595. }
  6596. visitSafePropertyRead(ast, context) {
  6597. ast.receiver.visit(this, context);
  6598. return null;
  6599. }
  6600. visitSafeMethodCall(ast, context) {
  6601. ast.receiver.visit(this, context);
  6602. return this.visitAll(ast.args, context);
  6603. }
  6604. visitAll(asts, context) {
  6605. asts.forEach(ast => ast.visit(this, context));
  6606. return null;
  6607. }
  6608. visitQuote(ast, context) { return null; }
  6609. }
  6610. class AstTransformer$1 {
  6611. visitImplicitReceiver(ast, context) { return ast; }
  6612. visitInterpolation(ast, context) {
  6613. return new Interpolation(ast.span, ast.strings, this.visitAll(ast.expressions));
  6614. }
  6615. visitLiteralPrimitive(ast, context) {
  6616. return new LiteralPrimitive(ast.span, ast.value);
  6617. }
  6618. visitPropertyRead(ast, context) {
  6619. return new PropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  6620. }
  6621. visitPropertyWrite(ast, context) {
  6622. return new PropertyWrite(ast.span, ast.receiver.visit(this), ast.name, ast.value.visit(this));
  6623. }
  6624. visitSafePropertyRead(ast, context) {
  6625. return new SafePropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  6626. }
  6627. visitMethodCall(ast, context) {
  6628. return new MethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  6629. }
  6630. visitSafeMethodCall(ast, context) {
  6631. return new SafeMethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  6632. }
  6633. visitFunctionCall(ast, context) {
  6634. return new FunctionCall(ast.span, ast.target.visit(this), this.visitAll(ast.args));
  6635. }
  6636. visitLiteralArray(ast, context) {
  6637. return new LiteralArray(ast.span, this.visitAll(ast.expressions));
  6638. }
  6639. visitLiteralMap(ast, context) {
  6640. return new LiteralMap(ast.span, ast.keys, this.visitAll(ast.values));
  6641. }
  6642. visitBinary(ast, context) {
  6643. return new Binary(ast.span, ast.operation, ast.left.visit(this), ast.right.visit(this));
  6644. }
  6645. visitPrefixNot(ast, context) {
  6646. return new PrefixNot(ast.span, ast.expression.visit(this));
  6647. }
  6648. visitNonNullAssert(ast, context) {
  6649. return new NonNullAssert(ast.span, ast.expression.visit(this));
  6650. }
  6651. visitConditional(ast, context) {
  6652. return new Conditional(ast.span, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
  6653. }
  6654. visitPipe(ast, context) {
  6655. return new BindingPipe(ast.span, ast.exp.visit(this), ast.name, this.visitAll(ast.args));
  6656. }
  6657. visitKeyedRead(ast, context) {
  6658. return new KeyedRead(ast.span, ast.obj.visit(this), ast.key.visit(this));
  6659. }
  6660. visitKeyedWrite(ast, context) {
  6661. return new KeyedWrite(ast.span, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
  6662. }
  6663. visitAll(asts) {
  6664. const res = new Array(asts.length);
  6665. for (let i = 0; i < asts.length; ++i) {
  6666. res[i] = asts[i].visit(this);
  6667. }
  6668. return res;
  6669. }
  6670. visitChain(ast, context) {
  6671. return new Chain(ast.span, this.visitAll(ast.expressions));
  6672. }
  6673. visitQuote(ast, context) {
  6674. return new Quote(ast.span, ast.prefix, ast.uninterpretedExpression, ast.location);
  6675. }
  6676. }
  6677. // A transformer that only creates new nodes if the transformer makes a change or
  6678. // a change is made a child node.
  6679. class AstMemoryEfficientTransformer {
  6680. visitImplicitReceiver(ast, context) { return ast; }
  6681. visitInterpolation(ast, context) {
  6682. const expressions = this.visitAll(ast.expressions);
  6683. if (expressions !== ast.expressions)
  6684. return new Interpolation(ast.span, ast.strings, expressions);
  6685. return ast;
  6686. }
  6687. visitLiteralPrimitive(ast, context) { return ast; }
  6688. visitPropertyRead(ast, context) {
  6689. const receiver = ast.receiver.visit(this);
  6690. if (receiver !== ast.receiver) {
  6691. return new PropertyRead(ast.span, receiver, ast.name);
  6692. }
  6693. return ast;
  6694. }
  6695. visitPropertyWrite(ast, context) {
  6696. const receiver = ast.receiver.visit(this);
  6697. const value = ast.value.visit(this);
  6698. if (receiver !== ast.receiver || value !== ast.value) {
  6699. return new PropertyWrite(ast.span, receiver, ast.name, value);
  6700. }
  6701. return ast;
  6702. }
  6703. visitSafePropertyRead(ast, context) {
  6704. const receiver = ast.receiver.visit(this);
  6705. if (receiver !== ast.receiver) {
  6706. return new SafePropertyRead(ast.span, receiver, ast.name);
  6707. }
  6708. return ast;
  6709. }
  6710. visitMethodCall(ast, context) {
  6711. const receiver = ast.receiver.visit(this);
  6712. const args = this.visitAll(ast.args);
  6713. if (receiver !== ast.receiver || args !== ast.args) {
  6714. return new MethodCall(ast.span, receiver, ast.name, args);
  6715. }
  6716. return ast;
  6717. }
  6718. visitSafeMethodCall(ast, context) {
  6719. const receiver = ast.receiver.visit(this);
  6720. const args = this.visitAll(ast.args);
  6721. if (receiver !== ast.receiver || args !== ast.args) {
  6722. return new SafeMethodCall(ast.span, receiver, ast.name, args);
  6723. }
  6724. return ast;
  6725. }
  6726. visitFunctionCall(ast, context) {
  6727. const target = ast.target && ast.target.visit(this);
  6728. const args = this.visitAll(ast.args);
  6729. if (target !== ast.target || args !== ast.args) {
  6730. return new FunctionCall(ast.span, target, args);
  6731. }
  6732. return ast;
  6733. }
  6734. visitLiteralArray(ast, context) {
  6735. const expressions = this.visitAll(ast.expressions);
  6736. if (expressions !== ast.expressions) {
  6737. return new LiteralArray(ast.span, expressions);
  6738. }
  6739. return ast;
  6740. }
  6741. visitLiteralMap(ast, context) {
  6742. const values = this.visitAll(ast.values);
  6743. if (values !== ast.values) {
  6744. return new LiteralMap(ast.span, ast.keys, values);
  6745. }
  6746. return ast;
  6747. }
  6748. visitBinary(ast, context) {
  6749. const left = ast.left.visit(this);
  6750. const right = ast.right.visit(this);
  6751. if (left !== ast.left || right !== ast.right) {
  6752. return new Binary(ast.span, ast.operation, left, right);
  6753. }
  6754. return ast;
  6755. }
  6756. visitPrefixNot(ast, context) {
  6757. const expression = ast.expression.visit(this);
  6758. if (expression !== ast.expression) {
  6759. return new PrefixNot(ast.span, expression);
  6760. }
  6761. return ast;
  6762. }
  6763. visitNonNullAssert(ast, context) {
  6764. const expression = ast.expression.visit(this);
  6765. if (expression !== ast.expression) {
  6766. return new NonNullAssert(ast.span, expression);
  6767. }
  6768. return ast;
  6769. }
  6770. visitConditional(ast, context) {
  6771. const condition = ast.condition.visit(this);
  6772. const trueExp = ast.trueExp.visit(this);
  6773. const falseExp = ast.falseExp.visit(this);
  6774. if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
  6775. return new Conditional(ast.span, condition, trueExp, falseExp);
  6776. }
  6777. return ast;
  6778. }
  6779. visitPipe(ast, context) {
  6780. const exp = ast.exp.visit(this);
  6781. const args = this.visitAll(ast.args);
  6782. if (exp !== ast.exp || args !== ast.args) {
  6783. return new BindingPipe(ast.span, exp, ast.name, args);
  6784. }
  6785. return ast;
  6786. }
  6787. visitKeyedRead(ast, context) {
  6788. const obj = ast.obj.visit(this);
  6789. const key = ast.key.visit(this);
  6790. if (obj !== ast.obj || key !== ast.key) {
  6791. return new KeyedRead(ast.span, obj, key);
  6792. }
  6793. return ast;
  6794. }
  6795. visitKeyedWrite(ast, context) {
  6796. const obj = ast.obj.visit(this);
  6797. const key = ast.key.visit(this);
  6798. const value = ast.value.visit(this);
  6799. if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
  6800. return new KeyedWrite(ast.span, obj, key, value);
  6801. }
  6802. return ast;
  6803. }
  6804. visitAll(asts) {
  6805. const res = new Array(asts.length);
  6806. let modified = false;
  6807. for (let i = 0; i < asts.length; ++i) {
  6808. const original = asts[i];
  6809. const value = original.visit(this);
  6810. res[i] = value;
  6811. modified = modified || value !== original;
  6812. }
  6813. return modified ? res : asts;
  6814. }
  6815. visitChain(ast, context) {
  6816. const expressions = this.visitAll(ast.expressions);
  6817. if (expressions !== ast.expressions) {
  6818. return new Chain(ast.span, expressions);
  6819. }
  6820. return ast;
  6821. }
  6822. visitQuote(ast, context) { return ast; }
  6823. }
  6824. function visitAstChildren(ast, visitor, context) {
  6825. function visit(ast) {
  6826. visitor.visit && visitor.visit(ast, context) || ast.visit(visitor, context);
  6827. }
  6828. function visitAll(asts) { asts.forEach(visit); }
  6829. ast.visit({
  6830. visitBinary(ast) {
  6831. visit(ast.left);
  6832. visit(ast.right);
  6833. },
  6834. visitChain(ast) { visitAll(ast.expressions); },
  6835. visitConditional(ast) {
  6836. visit(ast.condition);
  6837. visit(ast.trueExp);
  6838. visit(ast.falseExp);
  6839. },
  6840. visitFunctionCall(ast) {
  6841. if (ast.target) {
  6842. visit(ast.target);
  6843. }
  6844. visitAll(ast.args);
  6845. },
  6846. visitImplicitReceiver(ast) { },
  6847. visitInterpolation(ast) { visitAll(ast.expressions); },
  6848. visitKeyedRead(ast) {
  6849. visit(ast.obj);
  6850. visit(ast.key);
  6851. },
  6852. visitKeyedWrite(ast) {
  6853. visit(ast.obj);
  6854. visit(ast.key);
  6855. visit(ast.obj);
  6856. },
  6857. visitLiteralArray(ast) { visitAll(ast.expressions); },
  6858. visitLiteralMap(ast) { },
  6859. visitLiteralPrimitive(ast) { },
  6860. visitMethodCall(ast) {
  6861. visit(ast.receiver);
  6862. visitAll(ast.args);
  6863. },
  6864. visitPipe(ast) {
  6865. visit(ast.exp);
  6866. visitAll(ast.args);
  6867. },
  6868. visitPrefixNot(ast) { visit(ast.expression); },
  6869. visitNonNullAssert(ast) { visit(ast.expression); },
  6870. visitPropertyRead(ast) { visit(ast.receiver); },
  6871. visitPropertyWrite(ast) {
  6872. visit(ast.receiver);
  6873. visit(ast.value);
  6874. },
  6875. visitQuote(ast) { },
  6876. visitSafeMethodCall(ast) {
  6877. visit(ast.receiver);
  6878. visitAll(ast.args);
  6879. },
  6880. visitSafePropertyRead(ast) { visit(ast.receiver); },
  6881. });
  6882. }
  6883. // Bindings
  6884. class ParsedProperty {
  6885. constructor(name, expression, type, sourceSpan) {
  6886. this.name = name;
  6887. this.expression = expression;
  6888. this.type = type;
  6889. this.sourceSpan = sourceSpan;
  6890. this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
  6891. this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
  6892. }
  6893. }
  6894. var ParsedPropertyType;
  6895. (function (ParsedPropertyType) {
  6896. ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
  6897. ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
  6898. ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
  6899. })(ParsedPropertyType || (ParsedPropertyType = {}));
  6900. class ParsedEvent {
  6901. // Regular events have a target
  6902. // Animation events have a phase
  6903. constructor(name, targetOrPhase, type, handler, sourceSpan, handlerSpan) {
  6904. this.name = name;
  6905. this.targetOrPhase = targetOrPhase;
  6906. this.type = type;
  6907. this.handler = handler;
  6908. this.sourceSpan = sourceSpan;
  6909. this.handlerSpan = handlerSpan;
  6910. }
  6911. }
  6912. class ParsedVariable {
  6913. constructor(name, value, sourceSpan) {
  6914. this.name = name;
  6915. this.value = value;
  6916. this.sourceSpan = sourceSpan;
  6917. }
  6918. }
  6919. class BoundElementProperty {
  6920. constructor(name, type, securityContext, value, unit, sourceSpan) {
  6921. this.name = name;
  6922. this.type = type;
  6923. this.securityContext = securityContext;
  6924. this.value = value;
  6925. this.unit = unit;
  6926. this.sourceSpan = sourceSpan;
  6927. }
  6928. }
  6929. /**
  6930. * @license
  6931. * Copyright Google Inc. All Rights Reserved.
  6932. *
  6933. * Use of this source code is governed by an MIT-style license that can be
  6934. * found in the LICENSE file at https://angular.io/license
  6935. */
  6936. class EventHandlerVars {
  6937. }
  6938. EventHandlerVars.event = variable('$event');
  6939. class ConvertActionBindingResult {
  6940. constructor(
  6941. /**
  6942. * Render2 compatible statements,
  6943. */
  6944. stmts,
  6945. /**
  6946. * Variable name used with render2 compatible statements.
  6947. */
  6948. allowDefault) {
  6949. this.stmts = stmts;
  6950. this.allowDefault = allowDefault;
  6951. /**
  6952. * This is bit of a hack. It converts statements which render2 expects to statements which are
  6953. * expected by render3.
  6954. *
  6955. * Example: `<div click="doSomething($event)">` will generate:
  6956. *
  6957. * Render3:
  6958. * ```
  6959. * const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
  6960. * return pd_b;
  6961. * ```
  6962. *
  6963. * but render2 expects:
  6964. * ```
  6965. * return ctx.doSomething($event);
  6966. * ```
  6967. */
  6968. // TODO(misko): remove this hack once we no longer support ViewEngine.
  6969. this.render3Stmts = stmts.map((statement) => {
  6970. if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
  6971. statement.value instanceof BinaryOperatorExpr) {
  6972. const lhs = statement.value.lhs;
  6973. return new ReturnStatement(lhs.value);
  6974. }
  6975. return statement;
  6976. });
  6977. }
  6978. }
  6979. /**
  6980. * Converts the given expression AST into an executable output AST, assuming the expression is
  6981. * used in an action binding (e.g. an event handler).
  6982. */
  6983. function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan) {
  6984. if (!localResolver) {
  6985. localResolver = new DefaultLocalResolver();
  6986. }
  6987. const actionWithoutBuiltins = convertPropertyBindingBuiltins({
  6988. createLiteralArrayConverter: (argCount) => {
  6989. // Note: no caching for literal arrays in actions.
  6990. return (args) => literalArr(args);
  6991. },
  6992. createLiteralMapConverter: (keys) => {
  6993. // Note: no caching for literal maps in actions.
  6994. return (values) => {
  6995. const entries = keys.map((k, i) => ({
  6996. key: k.key,
  6997. value: values[i],
  6998. quoted: k.quoted,
  6999. }));
  7000. return literalMap(entries);
  7001. };
  7002. },
  7003. createPipeConverter: (name) => {
  7004. throw new Error(`Illegal State: Actions are not allowed to contain pipes. Pipe: ${name}`);
  7005. }
  7006. }, action);
  7007. const visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan);
  7008. const actionStmts = [];
  7009. flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
  7010. prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
  7011. if (visitor.usesImplicitReceiver) {
  7012. localResolver.notifyImplicitReceiverUse();
  7013. }
  7014. const lastIndex = actionStmts.length - 1;
  7015. let preventDefaultVar = null;
  7016. if (lastIndex >= 0) {
  7017. const lastStatement = actionStmts[lastIndex];
  7018. const returnExpr = convertStmtIntoExpression(lastStatement);
  7019. if (returnExpr) {
  7020. // Note: We need to cast the result of the method call to dynamic,
  7021. // as it might be a void method!
  7022. preventDefaultVar = createPreventDefaultVar(bindingId);
  7023. actionStmts[lastIndex] =
  7024. preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
  7025. .toDeclStmt(null, [StmtModifier.Final]);
  7026. }
  7027. }
  7028. return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
  7029. }
  7030. function convertPropertyBindingBuiltins(converterFactory, ast) {
  7031. return convertBuiltins(converterFactory, ast);
  7032. }
  7033. class ConvertPropertyBindingResult {
  7034. constructor(stmts, currValExpr) {
  7035. this.stmts = stmts;
  7036. this.currValExpr = currValExpr;
  7037. }
  7038. }
  7039. var BindingForm;
  7040. (function (BindingForm) {
  7041. // The general form of binding expression, supports all expressions.
  7042. BindingForm[BindingForm["General"] = 0] = "General";
  7043. // Try to generate a simple binding (no temporaries or statements)
  7044. // otherwise generate a general binding
  7045. BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
  7046. })(BindingForm || (BindingForm = {}));
  7047. /**
  7048. * Converts the given expression AST into an executable output AST, assuming the expression
  7049. * is used in property binding. The expression has to be preprocessed via
  7050. * `convertPropertyBindingBuiltins`.
  7051. */
  7052. function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
  7053. if (!localResolver) {
  7054. localResolver = new DefaultLocalResolver();
  7055. }
  7056. const currValExpr = createCurrValueExpr(bindingId);
  7057. const visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
  7058. const outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
  7059. const stmts = getStatementsFromVisitor(visitor, bindingId);
  7060. if (visitor.usesImplicitReceiver) {
  7061. localResolver.notifyImplicitReceiverUse();
  7062. }
  7063. if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
  7064. return new ConvertPropertyBindingResult([], outputExpr);
  7065. }
  7066. stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [StmtModifier.Final]));
  7067. return new ConvertPropertyBindingResult(stmts, currValExpr);
  7068. }
  7069. /**
  7070. * Given some expression, such as a binding or interpolation expression, and a context expression to
  7071. * look values up on, visit each facet of the given expression resolving values from the context
  7072. * expression such that a list of arguments can be derived from the found values that can be used as
  7073. * arguments to an external update instruction.
  7074. *
  7075. * @param localResolver The resolver to use to look up expressions by name appropriately
  7076. * @param contextVariableExpression The expression representing the context variable used to create
  7077. * the final argument expressions
  7078. * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
  7079. * be resolved and what arguments list to build.
  7080. * @param bindingId A name prefix used to create temporary variable names if they're needed for the
  7081. * arguments generated
  7082. * @returns An array of expressions that can be passed as arguments to instruction expressions like
  7083. * `o.importExpr(R3.propertyInterpolate).callFn(result)`
  7084. */
  7085. function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
  7086. const visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
  7087. const outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
  7088. if (visitor.usesImplicitReceiver) {
  7089. localResolver.notifyImplicitReceiverUse();
  7090. }
  7091. const stmts = getStatementsFromVisitor(visitor, bindingId);
  7092. // Removing the first argument, because it was a length for ViewEngine, not Ivy.
  7093. let args = outputExpr.args.slice(1);
  7094. if (expressionWithArgumentsToExtract instanceof Interpolation) {
  7095. // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
  7096. // args returned to just the value, because we're going to pass it to a special instruction.
  7097. const strings = expressionWithArgumentsToExtract.strings;
  7098. if (args.length === 3 && strings[0] === '' && strings[1] === '') {
  7099. // Single argument interpolate instructions.
  7100. args = [args[1]];
  7101. }
  7102. else if (args.length >= 19) {
  7103. // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
  7104. // an array of arguments
  7105. args = [literalArr(args)];
  7106. }
  7107. }
  7108. return { stmts, args };
  7109. }
  7110. function getStatementsFromVisitor(visitor, bindingId) {
  7111. const stmts = [];
  7112. for (let i = 0; i < visitor.temporaryCount; i++) {
  7113. stmts.push(temporaryDeclaration(bindingId, i));
  7114. }
  7115. return stmts;
  7116. }
  7117. function convertBuiltins(converterFactory, ast) {
  7118. const visitor = new _BuiltinAstConverter(converterFactory);
  7119. return ast.visit(visitor);
  7120. }
  7121. function temporaryName(bindingId, temporaryNumber) {
  7122. return `tmp_${bindingId}_${temporaryNumber}`;
  7123. }
  7124. function temporaryDeclaration(bindingId, temporaryNumber) {
  7125. return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
  7126. }
  7127. function prependTemporaryDecls(temporaryCount, bindingId, statements) {
  7128. for (let i = temporaryCount - 1; i >= 0; i--) {
  7129. statements.unshift(temporaryDeclaration(bindingId, i));
  7130. }
  7131. }
  7132. var _Mode;
  7133. (function (_Mode) {
  7134. _Mode[_Mode["Statement"] = 0] = "Statement";
  7135. _Mode[_Mode["Expression"] = 1] = "Expression";
  7136. })(_Mode || (_Mode = {}));
  7137. function ensureStatementMode(mode, ast) {
  7138. if (mode !== _Mode.Statement) {
  7139. throw new Error(`Expected a statement, but saw ${ast}`);
  7140. }
  7141. }
  7142. function ensureExpressionMode(mode, ast) {
  7143. if (mode !== _Mode.Expression) {
  7144. throw new Error(`Expected an expression, but saw ${ast}`);
  7145. }
  7146. }
  7147. function convertToStatementIfNeeded(mode, expr) {
  7148. if (mode === _Mode.Statement) {
  7149. return expr.toStmt();
  7150. }
  7151. else {
  7152. return expr;
  7153. }
  7154. }
  7155. class _BuiltinAstConverter extends AstTransformer$1 {
  7156. constructor(_converterFactory) {
  7157. super();
  7158. this._converterFactory = _converterFactory;
  7159. }
  7160. visitPipe(ast, context) {
  7161. const args = [ast.exp, ...ast.args].map(ast => ast.visit(this, context));
  7162. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createPipeConverter(ast.name, args.length));
  7163. }
  7164. visitLiteralArray(ast, context) {
  7165. const args = ast.expressions.map(ast => ast.visit(this, context));
  7166. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
  7167. }
  7168. visitLiteralMap(ast, context) {
  7169. const args = ast.values.map(ast => ast.visit(this, context));
  7170. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
  7171. }
  7172. }
  7173. class _AstToIrVisitor {
  7174. constructor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan) {
  7175. this._localResolver = _localResolver;
  7176. this._implicitReceiver = _implicitReceiver;
  7177. this.bindingId = bindingId;
  7178. this.interpolationFunction = interpolationFunction;
  7179. this.baseSourceSpan = baseSourceSpan;
  7180. this._nodeMap = new Map();
  7181. this._resultMap = new Map();
  7182. this._currentTemporary = 0;
  7183. this.temporaryCount = 0;
  7184. this.usesImplicitReceiver = false;
  7185. }
  7186. visitBinary(ast, mode) {
  7187. let op;
  7188. switch (ast.operation) {
  7189. case '+':
  7190. op = BinaryOperator.Plus;
  7191. break;
  7192. case '-':
  7193. op = BinaryOperator.Minus;
  7194. break;
  7195. case '*':
  7196. op = BinaryOperator.Multiply;
  7197. break;
  7198. case '/':
  7199. op = BinaryOperator.Divide;
  7200. break;
  7201. case '%':
  7202. op = BinaryOperator.Modulo;
  7203. break;
  7204. case '&&':
  7205. op = BinaryOperator.And;
  7206. break;
  7207. case '||':
  7208. op = BinaryOperator.Or;
  7209. break;
  7210. case '==':
  7211. op = BinaryOperator.Equals;
  7212. break;
  7213. case '!=':
  7214. op = BinaryOperator.NotEquals;
  7215. break;
  7216. case '===':
  7217. op = BinaryOperator.Identical;
  7218. break;
  7219. case '!==':
  7220. op = BinaryOperator.NotIdentical;
  7221. break;
  7222. case '<':
  7223. op = BinaryOperator.Lower;
  7224. break;
  7225. case '>':
  7226. op = BinaryOperator.Bigger;
  7227. break;
  7228. case '<=':
  7229. op = BinaryOperator.LowerEquals;
  7230. break;
  7231. case '>=':
  7232. op = BinaryOperator.BiggerEquals;
  7233. break;
  7234. default:
  7235. throw new Error(`Unsupported operation ${ast.operation}`);
  7236. }
  7237. return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
  7238. }
  7239. visitChain(ast, mode) {
  7240. ensureStatementMode(mode, ast);
  7241. return this.visitAll(ast.expressions, mode);
  7242. }
  7243. visitConditional(ast, mode) {
  7244. const value = this._visit(ast.condition, _Mode.Expression);
  7245. return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
  7246. }
  7247. visitPipe(ast, mode) {
  7248. throw new Error(`Illegal state: Pipes should have been converted into functions. Pipe: ${ast.name}`);
  7249. }
  7250. visitFunctionCall(ast, mode) {
  7251. const convertedArgs = this.visitAll(ast.args, _Mode.Expression);
  7252. let fnResult;
  7253. if (ast instanceof BuiltinFunctionCall) {
  7254. fnResult = ast.converter(convertedArgs);
  7255. }
  7256. else {
  7257. fnResult = this._visit(ast.target, _Mode.Expression)
  7258. .callFn(convertedArgs, this.convertSourceSpan(ast.span));
  7259. }
  7260. return convertToStatementIfNeeded(mode, fnResult);
  7261. }
  7262. visitImplicitReceiver(ast, mode) {
  7263. ensureExpressionMode(mode, ast);
  7264. this.usesImplicitReceiver = true;
  7265. return this._implicitReceiver;
  7266. }
  7267. visitInterpolation(ast, mode) {
  7268. ensureExpressionMode(mode, ast);
  7269. const args = [literal(ast.expressions.length)];
  7270. for (let i = 0; i < ast.strings.length - 1; i++) {
  7271. args.push(literal(ast.strings[i]));
  7272. args.push(this._visit(ast.expressions[i], _Mode.Expression));
  7273. }
  7274. args.push(literal(ast.strings[ast.strings.length - 1]));
  7275. if (this.interpolationFunction) {
  7276. return this.interpolationFunction(args);
  7277. }
  7278. return ast.expressions.length <= 9 ?
  7279. importExpr(Identifiers.inlineInterpolate).callFn(args) :
  7280. importExpr(Identifiers.interpolate).callFn([
  7281. args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
  7282. ]);
  7283. }
  7284. visitKeyedRead(ast, mode) {
  7285. const leftMostSafe = this.leftMostSafeNode(ast);
  7286. if (leftMostSafe) {
  7287. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7288. }
  7289. else {
  7290. return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
  7291. }
  7292. }
  7293. visitKeyedWrite(ast, mode) {
  7294. const obj = this._visit(ast.obj, _Mode.Expression);
  7295. const key = this._visit(ast.key, _Mode.Expression);
  7296. const value = this._visit(ast.value, _Mode.Expression);
  7297. return convertToStatementIfNeeded(mode, obj.key(key).set(value));
  7298. }
  7299. visitLiteralArray(ast, mode) {
  7300. throw new Error(`Illegal State: literal arrays should have been converted into functions`);
  7301. }
  7302. visitLiteralMap(ast, mode) {
  7303. throw new Error(`Illegal State: literal maps should have been converted into functions`);
  7304. }
  7305. visitLiteralPrimitive(ast, mode) {
  7306. // For literal values of null, undefined, true, or false allow type interference
  7307. // to infer the type.
  7308. const type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
  7309. INFERRED_TYPE :
  7310. undefined;
  7311. return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
  7312. }
  7313. _getLocal(name) { return this._localResolver.getLocal(name); }
  7314. visitMethodCall(ast, mode) {
  7315. if (ast.receiver instanceof ImplicitReceiver && ast.name == '$any') {
  7316. const args = this.visitAll(ast.args, _Mode.Expression);
  7317. if (args.length != 1) {
  7318. throw new Error(`Invalid call to $any, expected 1 argument but received ${args.length || 'none'}`);
  7319. }
  7320. return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
  7321. }
  7322. const leftMostSafe = this.leftMostSafeNode(ast);
  7323. if (leftMostSafe) {
  7324. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7325. }
  7326. else {
  7327. const args = this.visitAll(ast.args, _Mode.Expression);
  7328. const prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7329. let result = null;
  7330. const receiver = this._visit(ast.receiver, _Mode.Expression);
  7331. if (receiver === this._implicitReceiver) {
  7332. const varExpr = this._getLocal(ast.name);
  7333. if (varExpr) {
  7334. // Restore the previous "usesImplicitReceiver" state since the implicit
  7335. // receiver has been replaced with a resolved local expression.
  7336. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7337. result = varExpr.callFn(args);
  7338. }
  7339. }
  7340. if (result == null) {
  7341. result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
  7342. }
  7343. return convertToStatementIfNeeded(mode, result);
  7344. }
  7345. }
  7346. visitPrefixNot(ast, mode) {
  7347. return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
  7348. }
  7349. visitNonNullAssert(ast, mode) {
  7350. return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
  7351. }
  7352. visitPropertyRead(ast, mode) {
  7353. const leftMostSafe = this.leftMostSafeNode(ast);
  7354. if (leftMostSafe) {
  7355. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7356. }
  7357. else {
  7358. let result = null;
  7359. const prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7360. const receiver = this._visit(ast.receiver, _Mode.Expression);
  7361. if (receiver === this._implicitReceiver) {
  7362. result = this._getLocal(ast.name);
  7363. if (result) {
  7364. // Restore the previous "usesImplicitReceiver" state since the implicit
  7365. // receiver has been replaced with a resolved local expression.
  7366. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7367. }
  7368. }
  7369. if (result == null) {
  7370. result = receiver.prop(ast.name);
  7371. }
  7372. return convertToStatementIfNeeded(mode, result);
  7373. }
  7374. }
  7375. visitPropertyWrite(ast, mode) {
  7376. const receiver = this._visit(ast.receiver, _Mode.Expression);
  7377. const prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7378. let varExpr = null;
  7379. if (receiver === this._implicitReceiver) {
  7380. const localExpr = this._getLocal(ast.name);
  7381. if (localExpr) {
  7382. if (localExpr instanceof ReadPropExpr) {
  7383. // If the local variable is a property read expression, it's a reference
  7384. // to a 'context.property' value and will be used as the target of the
  7385. // write expression.
  7386. varExpr = localExpr;
  7387. // Restore the previous "usesImplicitReceiver" state since the implicit
  7388. // receiver has been replaced with a resolved local expression.
  7389. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7390. }
  7391. else {
  7392. // Otherwise it's an error.
  7393. throw new Error('Cannot assign to a reference or variable!');
  7394. }
  7395. }
  7396. }
  7397. // If no local expression could be produced, use the original receiver's
  7398. // property as the target.
  7399. if (varExpr === null) {
  7400. varExpr = receiver.prop(ast.name);
  7401. }
  7402. return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
  7403. }
  7404. visitSafePropertyRead(ast, mode) {
  7405. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  7406. }
  7407. visitSafeMethodCall(ast, mode) {
  7408. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  7409. }
  7410. visitAll(asts, mode) { return asts.map(ast => this._visit(ast, mode)); }
  7411. visitQuote(ast, mode) {
  7412. throw new Error(`Quotes are not supported for evaluation!
  7413. Statement: ${ast.uninterpretedExpression} located at ${ast.location}`);
  7414. }
  7415. _visit(ast, mode) {
  7416. const result = this._resultMap.get(ast);
  7417. if (result)
  7418. return result;
  7419. return (this._nodeMap.get(ast) || ast).visit(this, mode);
  7420. }
  7421. convertSafeAccess(ast, leftMostSafe, mode) {
  7422. // If the expression contains a safe access node on the left it needs to be converted to
  7423. // an expression that guards the access to the member by checking the receiver for blank. As
  7424. // execution proceeds from left to right, the left most part of the expression must be guarded
  7425. // first but, because member access is left associative, the right side of the expression is at
  7426. // the top of the AST. The desired result requires lifting a copy of the the left part of the
  7427. // expression up to test it for blank before generating the unguarded version.
  7428. // Consider, for example the following expression: a?.b.c?.d.e
  7429. // This results in the ast:
  7430. // .
  7431. // / \
  7432. // ?. e
  7433. // / \
  7434. // . d
  7435. // / \
  7436. // ?. c
  7437. // / \
  7438. // a b
  7439. // The following tree should be generated:
  7440. //
  7441. // /---- ? ----\
  7442. // / | \
  7443. // a /--- ? ---\ null
  7444. // / | \
  7445. // . . null
  7446. // / \ / \
  7447. // . c . e
  7448. // / \ / \
  7449. // a b . d
  7450. // / \
  7451. // . c
  7452. // / \
  7453. // a b
  7454. //
  7455. // Notice that the first guard condition is the left hand of the left most safe access node
  7456. // which comes in as leftMostSafe to this routine.
  7457. let guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
  7458. let temporary = undefined;
  7459. if (this.needsTemporary(leftMostSafe.receiver)) {
  7460. // If the expression has method calls or pipes then we need to save the result into a
  7461. // temporary variable to avoid calling stateful or impure code more than once.
  7462. temporary = this.allocateTemporary();
  7463. // Preserve the result in the temporary variable
  7464. guardedExpression = temporary.set(guardedExpression);
  7465. // Ensure all further references to the guarded expression refer to the temporary instead.
  7466. this._resultMap.set(leftMostSafe.receiver, temporary);
  7467. }
  7468. const condition = guardedExpression.isBlank();
  7469. // Convert the ast to an unguarded access to the receiver's member. The map will substitute
  7470. // leftMostNode with its unguarded version in the call to `this.visit()`.
  7471. if (leftMostSafe instanceof SafeMethodCall) {
  7472. this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
  7473. }
  7474. else {
  7475. this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name));
  7476. }
  7477. // Recursively convert the node now without the guarded member access.
  7478. const access = this._visit(ast, _Mode.Expression);
  7479. // Remove the mapping. This is not strictly required as the converter only traverses each node
  7480. // once but is safer if the conversion is changed to traverse the nodes more than once.
  7481. this._nodeMap.delete(leftMostSafe);
  7482. // If we allocated a temporary, release it.
  7483. if (temporary) {
  7484. this.releaseTemporary(temporary);
  7485. }
  7486. // Produce the conditional
  7487. return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
  7488. }
  7489. // Given a expression of the form a?.b.c?.d.e the the left most safe node is
  7490. // the (a?.b). The . and ?. are left associative thus can be rewritten as:
  7491. // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
  7492. // safe method call as this needs be transform initially to:
  7493. // a == null ? null : a.c.b.c?.d.e
  7494. // then to:
  7495. // a == null ? null : a.b.c == null ? null : a.b.c.d.e
  7496. leftMostSafeNode(ast) {
  7497. const visit = (visitor, ast) => {
  7498. return (this._nodeMap.get(ast) || ast).visit(visitor);
  7499. };
  7500. return ast.visit({
  7501. visitBinary(ast) { return null; },
  7502. visitChain(ast) { return null; },
  7503. visitConditional(ast) { return null; },
  7504. visitFunctionCall(ast) { return null; },
  7505. visitImplicitReceiver(ast) { return null; },
  7506. visitInterpolation(ast) { return null; },
  7507. visitKeyedRead(ast) { return visit(this, ast.obj); },
  7508. visitKeyedWrite(ast) { return null; },
  7509. visitLiteralArray(ast) { return null; },
  7510. visitLiteralMap(ast) { return null; },
  7511. visitLiteralPrimitive(ast) { return null; },
  7512. visitMethodCall(ast) { return visit(this, ast.receiver); },
  7513. visitPipe(ast) { return null; },
  7514. visitPrefixNot(ast) { return null; },
  7515. visitNonNullAssert(ast) { return null; },
  7516. visitPropertyRead(ast) { return visit(this, ast.receiver); },
  7517. visitPropertyWrite(ast) { return null; },
  7518. visitQuote(ast) { return null; },
  7519. visitSafeMethodCall(ast) { return visit(this, ast.receiver) || ast; },
  7520. visitSafePropertyRead(ast) {
  7521. return visit(this, ast.receiver) || ast;
  7522. }
  7523. });
  7524. }
  7525. // Returns true of the AST includes a method or a pipe indicating that, if the
  7526. // expression is used as the target of a safe property or method access then
  7527. // the expression should be stored into a temporary variable.
  7528. needsTemporary(ast) {
  7529. const visit = (visitor, ast) => {
  7530. return ast && (this._nodeMap.get(ast) || ast).visit(visitor);
  7531. };
  7532. const visitSome = (visitor, ast) => {
  7533. return ast.some(ast => visit(visitor, ast));
  7534. };
  7535. return ast.visit({
  7536. visitBinary(ast) { return visit(this, ast.left) || visit(this, ast.right); },
  7537. visitChain(ast) { return false; },
  7538. visitConditional(ast) {
  7539. return visit(this, ast.condition) || visit(this, ast.trueExp) ||
  7540. visit(this, ast.falseExp);
  7541. },
  7542. visitFunctionCall(ast) { return true; },
  7543. visitImplicitReceiver(ast) { return false; },
  7544. visitInterpolation(ast) { return visitSome(this, ast.expressions); },
  7545. visitKeyedRead(ast) { return false; },
  7546. visitKeyedWrite(ast) { return false; },
  7547. visitLiteralArray(ast) { return true; },
  7548. visitLiteralMap(ast) { return true; },
  7549. visitLiteralPrimitive(ast) { return false; },
  7550. visitMethodCall(ast) { return true; },
  7551. visitPipe(ast) { return true; },
  7552. visitPrefixNot(ast) { return visit(this, ast.expression); },
  7553. visitNonNullAssert(ast) { return visit(this, ast.expression); },
  7554. visitPropertyRead(ast) { return false; },
  7555. visitPropertyWrite(ast) { return false; },
  7556. visitQuote(ast) { return false; },
  7557. visitSafeMethodCall(ast) { return true; },
  7558. visitSafePropertyRead(ast) { return false; }
  7559. });
  7560. }
  7561. allocateTemporary() {
  7562. const tempNumber = this._currentTemporary++;
  7563. this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
  7564. return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
  7565. }
  7566. releaseTemporary(temporary) {
  7567. this._currentTemporary--;
  7568. if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
  7569. throw new Error(`Temporary ${temporary.name} released out of order`);
  7570. }
  7571. }
  7572. /**
  7573. * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
  7574. *
  7575. * `ParseSpan` objects are relative to the start of the expression.
  7576. * This method converts these to full `ParseSourceSpan` objects that
  7577. * show where the span is within the overall source file.
  7578. *
  7579. * @param span the relative span to convert.
  7580. * @returns a `ParseSourceSpan` for the the given span or null if no
  7581. * `baseSourceSpan` was provided to this class.
  7582. */
  7583. convertSourceSpan(span) {
  7584. if (this.baseSourceSpan) {
  7585. const start = this.baseSourceSpan.start.moveBy(span.start);
  7586. const end = this.baseSourceSpan.start.moveBy(span.end);
  7587. return new ParseSourceSpan(start, end);
  7588. }
  7589. else {
  7590. return null;
  7591. }
  7592. }
  7593. }
  7594. function flattenStatements(arg, output) {
  7595. if (Array.isArray(arg)) {
  7596. arg.forEach((entry) => flattenStatements(entry, output));
  7597. }
  7598. else {
  7599. output.push(arg);
  7600. }
  7601. }
  7602. class DefaultLocalResolver {
  7603. notifyImplicitReceiverUse() { }
  7604. getLocal(name) {
  7605. if (name === EventHandlerVars.event.name) {
  7606. return EventHandlerVars.event;
  7607. }
  7608. return null;
  7609. }
  7610. }
  7611. function createCurrValueExpr(bindingId) {
  7612. return variable(`currVal_${bindingId}`); // fix syntax highlighting: `
  7613. }
  7614. function createPreventDefaultVar(bindingId) {
  7615. return variable(`pd_${bindingId}`);
  7616. }
  7617. function convertStmtIntoExpression(stmt) {
  7618. if (stmt instanceof ExpressionStatement) {
  7619. return stmt.expr;
  7620. }
  7621. else if (stmt instanceof ReturnStatement) {
  7622. return stmt.value;
  7623. }
  7624. return null;
  7625. }
  7626. class BuiltinFunctionCall extends FunctionCall {
  7627. constructor(span, args, converter) {
  7628. super(span, null, args);
  7629. this.args = args;
  7630. this.converter = converter;
  7631. }
  7632. }
  7633. /**
  7634. * @license
  7635. * Copyright Google Inc. All Rights Reserved.
  7636. *
  7637. * Use of this source code is governed by an MIT-style license that can be
  7638. * found in the LICENSE file at https://angular.io/license
  7639. */
  7640. /**
  7641. * This file is a port of shadowCSS from webcomponents.js to TypeScript.
  7642. *
  7643. * Please make sure to keep to edits in sync with the source file.
  7644. *
  7645. * Source:
  7646. * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
  7647. *
  7648. * The original file level comment is reproduced below
  7649. */
  7650. /*
  7651. This is a limited shim for ShadowDOM css styling.
  7652. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
  7653. The intention here is to support only the styling features which can be
  7654. relatively simply implemented. The goal is to allow users to avoid the
  7655. most obvious pitfalls and do so without compromising performance significantly.
  7656. For ShadowDOM styling that's not covered here, a set of best practices
  7657. can be provided that should allow users to accomplish more complex styling.
  7658. The following is a list of specific ShadowDOM styling features and a brief
  7659. discussion of the approach used to shim.
  7660. Shimmed features:
  7661. * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
  7662. element using the :host rule. To shim this feature, the :host styles are
  7663. reformatted and prefixed with a given scope name and promoted to a
  7664. document level stylesheet.
  7665. For example, given a scope name of .foo, a rule like this:
  7666. :host {
  7667. background: red;
  7668. }
  7669. }
  7670. becomes:
  7671. .foo {
  7672. background: red;
  7673. }
  7674. * encapsulation: Styles defined within ShadowDOM, apply only to
  7675. dom inside the ShadowDOM. Polymer uses one of two techniques to implement
  7676. this feature.
  7677. By default, rules are prefixed with the host element tag name
  7678. as a descendant selector. This ensures styling does not leak out of the 'top'
  7679. of the element's ShadowDOM. For example,
  7680. div {
  7681. font-weight: bold;
  7682. }
  7683. becomes:
  7684. x-foo div {
  7685. font-weight: bold;
  7686. }
  7687. becomes:
  7688. Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
  7689. selectors are scoped by adding an attribute selector suffix to each
  7690. simple selector that contains the host element tag name. Each element
  7691. in the element's ShadowDOM template is also given the scope attribute.
  7692. Thus, these rules match only elements that have the scope attribute.
  7693. For example, given a scope name of x-foo, a rule like this:
  7694. div {
  7695. font-weight: bold;
  7696. }
  7697. becomes:
  7698. div[x-foo] {
  7699. font-weight: bold;
  7700. }
  7701. Note that elements that are dynamically added to a scope must have the scope
  7702. selector added to them manually.
  7703. * upper/lower bound encapsulation: Styles which are defined outside a
  7704. shadowRoot should not cross the ShadowDOM boundary and should not apply
  7705. inside a shadowRoot.
  7706. This styling behavior is not emulated. Some possible ways to do this that
  7707. were rejected due to complexity and/or performance concerns include: (1) reset
  7708. every possible property for every possible selector for a given scope name;
  7709. (2) re-implement css in javascript.
  7710. As an alternative, users should make sure to use selectors
  7711. specific to the scope in which they are working.
  7712. * ::distributed: This behavior is not emulated. It's often not necessary
  7713. to style the contents of a specific insertion point and instead, descendants
  7714. of the host element can be styled selectively. Users can also create an
  7715. extra node around an insertion point and style that node's contents
  7716. via descendent selectors. For example, with a shadowRoot like this:
  7717. <style>
  7718. ::content(div) {
  7719. background: red;
  7720. }
  7721. </style>
  7722. <content></content>
  7723. could become:
  7724. <style>
  7725. / *@polyfill .content-container div * /
  7726. ::content(div) {
  7727. background: red;
  7728. }
  7729. </style>
  7730. <div class="content-container">
  7731. <content></content>
  7732. </div>
  7733. Note the use of @polyfill in the comment above a ShadowDOM specific style
  7734. declaration. This is a directive to the styling shim to use the selector
  7735. in comments in lieu of the next selector when running under polyfill.
  7736. */
  7737. class ShadowCss {
  7738. constructor() {
  7739. this.strictStyling = true;
  7740. }
  7741. /*
  7742. * Shim some cssText with the given selector. Returns cssText that can
  7743. * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
  7744. *
  7745. * When strictStyling is true:
  7746. * - selector is the attribute added to all elements inside the host,
  7747. * - hostSelector is the attribute added to the host itself.
  7748. */
  7749. shimCssText(cssText, selector, hostSelector = '') {
  7750. const commentsWithHash = extractCommentsWithHash(cssText);
  7751. cssText = stripComments(cssText);
  7752. cssText = this._insertDirectives(cssText);
  7753. const scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
  7754. return [scopedCssText, ...commentsWithHash].join('\n');
  7755. }
  7756. _insertDirectives(cssText) {
  7757. cssText = this._insertPolyfillDirectivesInCssText(cssText);
  7758. return this._insertPolyfillRulesInCssText(cssText);
  7759. }
  7760. /*
  7761. * Process styles to convert native ShadowDOM rules that will trip
  7762. * up the css parser; we rely on decorating the stylesheet with inert rules.
  7763. *
  7764. * For example, we convert this rule:
  7765. *
  7766. * polyfill-next-selector { content: ':host menu-item'; }
  7767. * ::content menu-item {
  7768. *
  7769. * to this:
  7770. *
  7771. * scopeName menu-item {
  7772. *
  7773. **/
  7774. _insertPolyfillDirectivesInCssText(cssText) {
  7775. // Difference with webcomponents.js: does not handle comments
  7776. return cssText.replace(_cssContentNextSelectorRe, function (...m) { return m[2] + '{'; });
  7777. }
  7778. /*
  7779. * Process styles to add rules which will only apply under the polyfill
  7780. *
  7781. * For example, we convert this rule:
  7782. *
  7783. * polyfill-rule {
  7784. * content: ':host menu-item';
  7785. * ...
  7786. * }
  7787. *
  7788. * to this:
  7789. *
  7790. * scopeName menu-item {...}
  7791. *
  7792. **/
  7793. _insertPolyfillRulesInCssText(cssText) {
  7794. // Difference with webcomponents.js: does not handle comments
  7795. return cssText.replace(_cssContentRuleRe, (...m) => {
  7796. const rule = m[0].replace(m[1], '').replace(m[2], '');
  7797. return m[4] + rule;
  7798. });
  7799. }
  7800. /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
  7801. *
  7802. * .foo {... }
  7803. *
  7804. * and converts this to
  7805. *
  7806. * scopeName .foo { ... }
  7807. */
  7808. _scopeCssText(cssText, scopeSelector, hostSelector) {
  7809. const unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
  7810. // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
  7811. cssText = this._insertPolyfillHostInCssText(cssText);
  7812. cssText = this._convertColonHost(cssText);
  7813. cssText = this._convertColonHostContext(cssText);
  7814. cssText = this._convertShadowDOMSelectors(cssText);
  7815. if (scopeSelector) {
  7816. cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
  7817. }
  7818. cssText = cssText + '\n' + unscopedRules;
  7819. return cssText.trim();
  7820. }
  7821. /*
  7822. * Process styles to add rules which will only apply under the polyfill
  7823. * and do not process via CSSOM. (CSSOM is destructive to rules on rare
  7824. * occasions, e.g. -webkit-calc on Safari.)
  7825. * For example, we convert this rule:
  7826. *
  7827. * @polyfill-unscoped-rule {
  7828. * content: 'menu-item';
  7829. * ... }
  7830. *
  7831. * to this:
  7832. *
  7833. * menu-item {...}
  7834. *
  7835. **/
  7836. _extractUnscopedRulesFromCssText(cssText) {
  7837. // Difference with webcomponents.js: does not handle comments
  7838. let r = '';
  7839. let m;
  7840. _cssContentUnscopedRuleRe.lastIndex = 0;
  7841. while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
  7842. const rule = m[0].replace(m[2], '').replace(m[1], m[4]);
  7843. r += rule + '\n\n';
  7844. }
  7845. return r;
  7846. }
  7847. /*
  7848. * convert a rule like :host(.foo) > .bar { }
  7849. *
  7850. * to
  7851. *
  7852. * .foo<scopeName> > .bar
  7853. */
  7854. _convertColonHost(cssText) {
  7855. return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
  7856. }
  7857. /*
  7858. * convert a rule like :host-context(.foo) > .bar { }
  7859. *
  7860. * to
  7861. *
  7862. * .foo<scopeName> > .bar, .foo scopeName > .bar { }
  7863. *
  7864. * and
  7865. *
  7866. * :host-context(.foo:host) .bar { ... }
  7867. *
  7868. * to
  7869. *
  7870. * .foo<scopeName> .bar { ... }
  7871. */
  7872. _convertColonHostContext(cssText) {
  7873. return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
  7874. }
  7875. _convertColonRule(cssText, regExp, partReplacer) {
  7876. // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
  7877. return cssText.replace(regExp, function (...m) {
  7878. if (m[2]) {
  7879. const parts = m[2].split(',');
  7880. const r = [];
  7881. for (let i = 0; i < parts.length; i++) {
  7882. const p = parts[i].trim();
  7883. if (!p)
  7884. break;
  7885. r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
  7886. }
  7887. return r.join(',');
  7888. }
  7889. else {
  7890. return _polyfillHostNoCombinator + m[3];
  7891. }
  7892. });
  7893. }
  7894. _colonHostContextPartReplacer(host, part, suffix) {
  7895. if (part.indexOf(_polyfillHost) > -1) {
  7896. return this._colonHostPartReplacer(host, part, suffix);
  7897. }
  7898. else {
  7899. return host + part + suffix + ', ' + part + ' ' + host + suffix;
  7900. }
  7901. }
  7902. _colonHostPartReplacer(host, part, suffix) {
  7903. return host + part.replace(_polyfillHost, '') + suffix;
  7904. }
  7905. /*
  7906. * Convert combinators like ::shadow and pseudo-elements like ::content
  7907. * by replacing with space.
  7908. */
  7909. _convertShadowDOMSelectors(cssText) {
  7910. return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, ' '), cssText);
  7911. }
  7912. // change a selector like 'div' to 'name div'
  7913. _scopeSelectors(cssText, scopeSelector, hostSelector) {
  7914. return processRules(cssText, (rule) => {
  7915. let selector = rule.selector;
  7916. let content = rule.content;
  7917. if (rule.selector[0] != '@') {
  7918. selector =
  7919. this._scopeSelector(rule.selector, scopeSelector, hostSelector, this.strictStyling);
  7920. }
  7921. else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
  7922. rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
  7923. content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
  7924. }
  7925. return new CssRule(selector, content);
  7926. });
  7927. }
  7928. _scopeSelector(selector, scopeSelector, hostSelector, strict) {
  7929. return selector.split(',')
  7930. .map(part => part.trim().split(_shadowDeepSelectors))
  7931. .map((deepParts) => {
  7932. const [shallowPart, ...otherParts] = deepParts;
  7933. const applyScope = (shallowPart) => {
  7934. if (this._selectorNeedsScoping(shallowPart, scopeSelector)) {
  7935. return strict ?
  7936. this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
  7937. this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
  7938. }
  7939. else {
  7940. return shallowPart;
  7941. }
  7942. };
  7943. return [applyScope(shallowPart), ...otherParts].join(' ');
  7944. })
  7945. .join(', ');
  7946. }
  7947. _selectorNeedsScoping(selector, scopeSelector) {
  7948. const re = this._makeScopeMatcher(scopeSelector);
  7949. return !re.test(selector);
  7950. }
  7951. _makeScopeMatcher(scopeSelector) {
  7952. const lre = /\[/g;
  7953. const rre = /\]/g;
  7954. scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
  7955. return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
  7956. }
  7957. _applySelectorScope(selector, scopeSelector, hostSelector) {
  7958. // Difference from webcomponents.js: scopeSelector could not be an array
  7959. return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
  7960. }
  7961. // scope via name and [is=name]
  7962. _applySimpleSelectorScope(selector, scopeSelector, hostSelector) {
  7963. // In Android browser, the lastIndex is not reset when the regex is used in String.replace()
  7964. _polyfillHostRe.lastIndex = 0;
  7965. if (_polyfillHostRe.test(selector)) {
  7966. const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;
  7967. return selector
  7968. .replace(_polyfillHostNoCombinatorRe, (hnc, selector) => {
  7969. return selector.replace(/([^:]*)(:*)(.*)/, (_, before, colon, after) => {
  7970. return before + replaceBy + colon + after;
  7971. });
  7972. })
  7973. .replace(_polyfillHostRe, replaceBy + ' ');
  7974. }
  7975. return scopeSelector + ' ' + selector;
  7976. }
  7977. // return a selector with [name] suffix on each simple selector
  7978. // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
  7979. _applyStrictSelectorScope(selector, scopeSelector, hostSelector) {
  7980. const isRe = /\[is=([^\]]*)\]/g;
  7981. scopeSelector = scopeSelector.replace(isRe, (_, ...parts) => parts[0]);
  7982. const attrName = '[' + scopeSelector + ']';
  7983. const _scopeSelectorPart = (p) => {
  7984. let scopedP = p.trim();
  7985. if (!scopedP) {
  7986. return '';
  7987. }
  7988. if (p.indexOf(_polyfillHostNoCombinator) > -1) {
  7989. scopedP = this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
  7990. }
  7991. else {
  7992. // remove :host since it should be unnecessary
  7993. const t = p.replace(_polyfillHostRe, '');
  7994. if (t.length > 0) {
  7995. const matches = t.match(/([^:]*)(:*)(.*)/);
  7996. if (matches) {
  7997. scopedP = matches[1] + attrName + matches[2] + matches[3];
  7998. }
  7999. }
  8000. }
  8001. return scopedP;
  8002. };
  8003. const safeContent = new SafeSelector(selector);
  8004. selector = safeContent.content();
  8005. let scopedSelector = '';
  8006. let startIndex = 0;
  8007. let res;
  8008. const sep = /( |>|\+|~(?!=))\s*/g;
  8009. // If a selector appears before :host it should not be shimmed as it
  8010. // matches on ancestor elements and not on elements in the host's shadow
  8011. // `:host-context(div)` is transformed to
  8012. // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
  8013. // the `div` is not part of the component in the 2nd selectors and should not be scoped.
  8014. // Historically `component-tag:host` was matching the component so we also want to preserve
  8015. // this behavior to avoid breaking legacy apps (it should not match).
  8016. // The behavior should be:
  8017. // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
  8018. // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
  8019. // `:host-context(tag)`)
  8020. const hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
  8021. // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
  8022. let shouldScope = !hasHost;
  8023. while ((res = sep.exec(selector)) !== null) {
  8024. const separator = res[1];
  8025. const part = selector.slice(startIndex, res.index).trim();
  8026. shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
  8027. const scopedPart = shouldScope ? _scopeSelectorPart(part) : part;
  8028. scopedSelector += `${scopedPart} ${separator} `;
  8029. startIndex = sep.lastIndex;
  8030. }
  8031. const part = selector.substring(startIndex);
  8032. shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
  8033. scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
  8034. // replace the placeholders with their original values
  8035. return safeContent.restore(scopedSelector);
  8036. }
  8037. _insertPolyfillHostInCssText(selector) {
  8038. return selector.replace(_colonHostContextRe, _polyfillHostContext)
  8039. .replace(_colonHostRe, _polyfillHost);
  8040. }
  8041. }
  8042. class SafeSelector {
  8043. constructor(selector) {
  8044. this.placeholders = [];
  8045. this.index = 0;
  8046. // Replaces attribute selectors with placeholders.
  8047. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
  8048. selector = selector.replace(/(\[[^\]]*\])/g, (_, keep) => {
  8049. const replaceBy = `__ph-${this.index}__`;
  8050. this.placeholders.push(keep);
  8051. this.index++;
  8052. return replaceBy;
  8053. });
  8054. // Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
  8055. // WS and "+" would otherwise be interpreted as selector separators.
  8056. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
  8057. const replaceBy = `__ph-${this.index}__`;
  8058. this.placeholders.push(exp);
  8059. this.index++;
  8060. return pseudo + replaceBy;
  8061. });
  8062. }
  8063. restore(content) {
  8064. return content.replace(/__ph-(\d+)__/g, (ph, index) => this.placeholders[+index]);
  8065. }
  8066. content() { return this._content; }
  8067. }
  8068. const _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
  8069. const _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8070. const _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8071. const _polyfillHost = '-shadowcsshost';
  8072. // note: :host-context pre-processed to -shadowcsshostcontext.
  8073. const _polyfillHostContext = '-shadowcsscontext';
  8074. const _parenSuffix = ')(?:\\((' +
  8075. '(?:\\([^)(]*\\)|[^)(]*)+?' +
  8076. ')\\))?([^,{]*)';
  8077. const _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
  8078. const _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
  8079. const _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
  8080. const _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
  8081. const _shadowDOMSelectorsRe = [
  8082. /::shadow/g,
  8083. /::content/g,
  8084. // Deprecated selectors
  8085. /\/shadow-deep\//g,
  8086. /\/shadow\//g,
  8087. ];
  8088. // The deep combinator is deprecated in the CSS spec
  8089. // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
  8090. // see https://github.com/angular/angular/pull/17677
  8091. const _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
  8092. const _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
  8093. const _polyfillHostRe = /-shadowcsshost/gim;
  8094. const _colonHostRe = /:host/gim;
  8095. const _colonHostContextRe = /:host-context/gim;
  8096. const _commentRe = /\/\*\s*[\s\S]*?\*\//g;
  8097. function stripComments(input) {
  8098. return input.replace(_commentRe, '');
  8099. }
  8100. const _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
  8101. function extractCommentsWithHash(input) {
  8102. return input.match(_commentWithHashRe) || [];
  8103. }
  8104. const _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
  8105. const _curlyRe = /([{}])/g;
  8106. const OPEN_CURLY = '{';
  8107. const CLOSE_CURLY = '}';
  8108. const BLOCK_PLACEHOLDER = '%BLOCK%';
  8109. class CssRule {
  8110. constructor(selector, content) {
  8111. this.selector = selector;
  8112. this.content = content;
  8113. }
  8114. }
  8115. function processRules(input, ruleCallback) {
  8116. const inputWithEscapedBlocks = escapeBlocks(input);
  8117. let nextBlockIndex = 0;
  8118. return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function (...m) {
  8119. const selector = m[2];
  8120. let content = '';
  8121. let suffix = m[4];
  8122. let contentPrefix = '';
  8123. if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
  8124. content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
  8125. suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
  8126. contentPrefix = '{';
  8127. }
  8128. const rule = ruleCallback(new CssRule(selector, content));
  8129. return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
  8130. });
  8131. }
  8132. class StringWithEscapedBlocks {
  8133. constructor(escapedString, blocks) {
  8134. this.escapedString = escapedString;
  8135. this.blocks = blocks;
  8136. }
  8137. }
  8138. function escapeBlocks(input) {
  8139. const inputParts = input.split(_curlyRe);
  8140. const resultParts = [];
  8141. const escapedBlocks = [];
  8142. let bracketCount = 0;
  8143. let currentBlockParts = [];
  8144. for (let partIndex = 0; partIndex < inputParts.length; partIndex++) {
  8145. const part = inputParts[partIndex];
  8146. if (part == CLOSE_CURLY) {
  8147. bracketCount--;
  8148. }
  8149. if (bracketCount > 0) {
  8150. currentBlockParts.push(part);
  8151. }
  8152. else {
  8153. if (currentBlockParts.length > 0) {
  8154. escapedBlocks.push(currentBlockParts.join(''));
  8155. resultParts.push(BLOCK_PLACEHOLDER);
  8156. currentBlockParts = [];
  8157. }
  8158. resultParts.push(part);
  8159. }
  8160. if (part == OPEN_CURLY) {
  8161. bracketCount++;
  8162. }
  8163. }
  8164. if (currentBlockParts.length > 0) {
  8165. escapedBlocks.push(currentBlockParts.join(''));
  8166. resultParts.push(BLOCK_PLACEHOLDER);
  8167. }
  8168. return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
  8169. }
  8170. /**
  8171. * @license
  8172. * Copyright Google Inc. All Rights Reserved.
  8173. *
  8174. * Use of this source code is governed by an MIT-style license that can be
  8175. * found in the LICENSE file at https://angular.io/license
  8176. */
  8177. const COMPONENT_VARIABLE = '%COMP%';
  8178. const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
  8179. const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
  8180. class StylesCompileDependency {
  8181. constructor(name, moduleUrl, setValue) {
  8182. this.name = name;
  8183. this.moduleUrl = moduleUrl;
  8184. this.setValue = setValue;
  8185. }
  8186. }
  8187. class CompiledStylesheet {
  8188. constructor(outputCtx, stylesVar, dependencies, isShimmed, meta) {
  8189. this.outputCtx = outputCtx;
  8190. this.stylesVar = stylesVar;
  8191. this.dependencies = dependencies;
  8192. this.isShimmed = isShimmed;
  8193. this.meta = meta;
  8194. }
  8195. }
  8196. class StyleCompiler {
  8197. constructor(_urlResolver) {
  8198. this._urlResolver = _urlResolver;
  8199. this._shadowCss = new ShadowCss();
  8200. }
  8201. compileComponent(outputCtx, comp) {
  8202. const template = comp.template;
  8203. return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({
  8204. styles: template.styles,
  8205. styleUrls: template.styleUrls,
  8206. moduleUrl: identifierModuleUrl(comp.type)
  8207. }), this.needsStyleShim(comp), true);
  8208. }
  8209. compileStyles(outputCtx, comp, stylesheet, shim = this.needsStyleShim(comp)) {
  8210. return this._compileStyles(outputCtx, comp, stylesheet, shim, false);
  8211. }
  8212. needsStyleShim(comp) {
  8213. return comp.template.encapsulation === ViewEncapsulation.Emulated;
  8214. }
  8215. _compileStyles(outputCtx, comp, stylesheet, shim, isComponentStylesheet) {
  8216. const styleExpressions = stylesheet.styles.map(plainStyle => literal(this._shimIfNeeded(plainStyle, shim)));
  8217. const dependencies = [];
  8218. stylesheet.styleUrls.forEach((styleUrl) => {
  8219. const exprIndex = styleExpressions.length;
  8220. // Note: This placeholder will be filled later.
  8221. styleExpressions.push(null);
  8222. dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, (value) => styleExpressions[exprIndex] = outputCtx.importExpr(value)));
  8223. });
  8224. // styles variable contains plain strings and arrays of other styles arrays (recursive),
  8225. // so we set its type to dynamic.
  8226. const stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
  8227. const stmt = variable(stylesVar)
  8228. .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
  8229. .toDeclStmt(null, isComponentStylesheet ? [StmtModifier.Final] : [
  8230. StmtModifier.Final, StmtModifier.Exported
  8231. ]);
  8232. outputCtx.statements.push(stmt);
  8233. return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet);
  8234. }
  8235. _shimIfNeeded(style, shim) {
  8236. return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style;
  8237. }
  8238. }
  8239. function getStylesVarName(component) {
  8240. let result = `styles`;
  8241. if (component) {
  8242. result += `_${identifierName(component.type)}`;
  8243. }
  8244. return result;
  8245. }
  8246. /**
  8247. * @license
  8248. * Copyright Google Inc. All Rights Reserved.
  8249. *
  8250. * Use of this source code is governed by an MIT-style license that can be
  8251. * found in the LICENSE file at https://angular.io/license
  8252. */
  8253. /**
  8254. * A path is an ordered set of elements. Typically a path is to a
  8255. * particular offset in a source file. The head of the list is the top
  8256. * most node. The tail is the node that contains the offset directly.
  8257. *
  8258. * For example, the expression `a + b + c` might have an ast that looks
  8259. * like:
  8260. * +
  8261. * / \
  8262. * a +
  8263. * / \
  8264. * b c
  8265. *
  8266. * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
  8267. * 'c' at 9-10]` and the path the node at offset 1 would be
  8268. * `['+' at 1-10, 'a' at 1-2]`.
  8269. */
  8270. class AstPath {
  8271. constructor(path, position = -1) {
  8272. this.path = path;
  8273. this.position = position;
  8274. }
  8275. get empty() { return !this.path || !this.path.length; }
  8276. get head() { return this.path[0]; }
  8277. get tail() { return this.path[this.path.length - 1]; }
  8278. parentOf(node) {
  8279. return node && this.path[this.path.indexOf(node) - 1];
  8280. }
  8281. childOf(node) { return this.path[this.path.indexOf(node) + 1]; }
  8282. first(ctor) {
  8283. for (let i = this.path.length - 1; i >= 0; i--) {
  8284. let item = this.path[i];
  8285. if (item instanceof ctor)
  8286. return item;
  8287. }
  8288. }
  8289. push(node) { this.path.push(node); }
  8290. pop() { return this.path.pop(); }
  8291. }
  8292. /**
  8293. * @license
  8294. * Copyright Google Inc. All Rights Reserved.
  8295. *
  8296. * Use of this source code is governed by an MIT-style license that can be
  8297. * found in the LICENSE file at https://angular.io/license
  8298. */
  8299. class Text$3 {
  8300. constructor(value, sourceSpan, i18n) {
  8301. this.value = value;
  8302. this.sourceSpan = sourceSpan;
  8303. this.i18n = i18n;
  8304. }
  8305. visit(visitor, context) { return visitor.visitText(this, context); }
  8306. }
  8307. class Expansion {
  8308. constructor(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
  8309. this.switchValue = switchValue;
  8310. this.type = type;
  8311. this.cases = cases;
  8312. this.sourceSpan = sourceSpan;
  8313. this.switchValueSourceSpan = switchValueSourceSpan;
  8314. this.i18n = i18n;
  8315. }
  8316. visit(visitor, context) { return visitor.visitExpansion(this, context); }
  8317. }
  8318. class ExpansionCase {
  8319. constructor(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
  8320. this.value = value;
  8321. this.expression = expression;
  8322. this.sourceSpan = sourceSpan;
  8323. this.valueSourceSpan = valueSourceSpan;
  8324. this.expSourceSpan = expSourceSpan;
  8325. }
  8326. visit(visitor, context) { return visitor.visitExpansionCase(this, context); }
  8327. }
  8328. class Attribute {
  8329. constructor(name, value, sourceSpan, valueSpan, i18n) {
  8330. this.name = name;
  8331. this.value = value;
  8332. this.sourceSpan = sourceSpan;
  8333. this.valueSpan = valueSpan;
  8334. this.i18n = i18n;
  8335. }
  8336. visit(visitor, context) { return visitor.visitAttribute(this, context); }
  8337. }
  8338. class Element$1 {
  8339. constructor(name, attrs, children, sourceSpan, startSourceSpan = null, endSourceSpan = null, i18n) {
  8340. this.name = name;
  8341. this.attrs = attrs;
  8342. this.children = children;
  8343. this.sourceSpan = sourceSpan;
  8344. this.startSourceSpan = startSourceSpan;
  8345. this.endSourceSpan = endSourceSpan;
  8346. this.i18n = i18n;
  8347. }
  8348. visit(visitor, context) { return visitor.visitElement(this, context); }
  8349. }
  8350. class Comment {
  8351. constructor(value, sourceSpan) {
  8352. this.value = value;
  8353. this.sourceSpan = sourceSpan;
  8354. }
  8355. visit(visitor, context) { return visitor.visitComment(this, context); }
  8356. }
  8357. function visitAll$1(visitor, nodes, context = null) {
  8358. const result = [];
  8359. const visit = visitor.visit ?
  8360. (ast) => visitor.visit(ast, context) || ast.visit(visitor, context) :
  8361. (ast) => ast.visit(visitor, context);
  8362. nodes.forEach(ast => {
  8363. const astResult = visit(ast);
  8364. if (astResult) {
  8365. result.push(astResult);
  8366. }
  8367. });
  8368. return result;
  8369. }
  8370. class RecursiveVisitor {
  8371. constructor() { }
  8372. visitElement(ast, context) {
  8373. this.visitChildren(context, visit => {
  8374. visit(ast.attrs);
  8375. visit(ast.children);
  8376. });
  8377. }
  8378. visitAttribute(ast, context) { }
  8379. visitText(ast, context) { }
  8380. visitComment(ast, context) { }
  8381. visitExpansion(ast, context) {
  8382. return this.visitChildren(context, visit => { visit(ast.cases); });
  8383. }
  8384. visitExpansionCase(ast, context) { }
  8385. visitChildren(context, cb) {
  8386. let results = [];
  8387. let t = this;
  8388. function visit(children) {
  8389. if (children)
  8390. results.push(visitAll$1(t, children, context));
  8391. }
  8392. cb(visit);
  8393. return [].concat.apply([], results);
  8394. }
  8395. }
  8396. function spanOf(ast) {
  8397. const start = ast.sourceSpan.start.offset;
  8398. let end = ast.sourceSpan.end.offset;
  8399. if (ast instanceof Element$1) {
  8400. if (ast.endSourceSpan) {
  8401. end = ast.endSourceSpan.end.offset;
  8402. }
  8403. else if (ast.children && ast.children.length) {
  8404. end = spanOf(ast.children[ast.children.length - 1]).end;
  8405. }
  8406. }
  8407. return { start, end };
  8408. }
  8409. function findNode(nodes, position) {
  8410. const path = [];
  8411. const visitor = new class extends RecursiveVisitor {
  8412. visit(ast, context) {
  8413. const span = spanOf(ast);
  8414. if (span.start <= position && position < span.end) {
  8415. path.push(ast);
  8416. }
  8417. else {
  8418. // Returning a value here will result in the children being skipped.
  8419. return true;
  8420. }
  8421. }
  8422. };
  8423. visitAll$1(visitor, nodes);
  8424. return new AstPath(path, position);
  8425. }
  8426. /**
  8427. * @license
  8428. * Copyright Google Inc. All Rights Reserved.
  8429. *
  8430. * Use of this source code is governed by an MIT-style license that can be
  8431. * found in the LICENSE file at https://angular.io/license
  8432. */
  8433. var TokenType;
  8434. (function (TokenType) {
  8435. TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
  8436. TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
  8437. TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
  8438. TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
  8439. TokenType[TokenType["TEXT"] = 4] = "TEXT";
  8440. TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT";
  8441. TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT";
  8442. TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START";
  8443. TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END";
  8444. TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START";
  8445. TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END";
  8446. TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME";
  8447. TokenType[TokenType["ATTR_QUOTE"] = 12] = "ATTR_QUOTE";
  8448. TokenType[TokenType["ATTR_VALUE"] = 13] = "ATTR_VALUE";
  8449. TokenType[TokenType["DOC_TYPE"] = 14] = "DOC_TYPE";
  8450. TokenType[TokenType["EXPANSION_FORM_START"] = 15] = "EXPANSION_FORM_START";
  8451. TokenType[TokenType["EXPANSION_CASE_VALUE"] = 16] = "EXPANSION_CASE_VALUE";
  8452. TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 17] = "EXPANSION_CASE_EXP_START";
  8453. TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 18] = "EXPANSION_CASE_EXP_END";
  8454. TokenType[TokenType["EXPANSION_FORM_END"] = 19] = "EXPANSION_FORM_END";
  8455. TokenType[TokenType["EOF"] = 20] = "EOF";
  8456. })(TokenType || (TokenType = {}));
  8457. class Token {
  8458. constructor(type, parts, sourceSpan) {
  8459. this.type = type;
  8460. this.parts = parts;
  8461. this.sourceSpan = sourceSpan;
  8462. }
  8463. }
  8464. class TokenError extends ParseError {
  8465. constructor(errorMsg, tokenType, span) {
  8466. super(span, errorMsg);
  8467. this.tokenType = tokenType;
  8468. }
  8469. }
  8470. class TokenizeResult {
  8471. constructor(tokens, errors) {
  8472. this.tokens = tokens;
  8473. this.errors = errors;
  8474. }
  8475. }
  8476. function tokenize(source, url, getTagDefinition, options = {}) {
  8477. return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options).tokenize();
  8478. }
  8479. const _CR_OR_CRLF_REGEXP = /\r\n?/g;
  8480. function _unexpectedCharacterErrorMsg(charCode) {
  8481. const char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
  8482. return `Unexpected character "${char}"`;
  8483. }
  8484. function _unknownEntityErrorMsg(entitySrc) {
  8485. return `Unknown entity "${entitySrc}" - use the "&#<decimal>;" or "&#x<hex>;" syntax`;
  8486. }
  8487. class _ControlFlowError {
  8488. constructor(error) {
  8489. this.error = error;
  8490. }
  8491. }
  8492. // See http://www.w3.org/TR/html51/syntax.html#writing
  8493. class _Tokenizer {
  8494. /**
  8495. * @param _file The html source file being tokenized.
  8496. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
  8497. * @param options Configuration of the tokenization.
  8498. */
  8499. constructor(_file, _getTagDefinition, options) {
  8500. this._getTagDefinition = _getTagDefinition;
  8501. this._currentTokenStart = null;
  8502. this._currentTokenType = null;
  8503. this._expansionCaseStack = [];
  8504. this._inInterpolation = false;
  8505. this.tokens = [];
  8506. this.errors = [];
  8507. this._tokenizeIcu = options.tokenizeExpansionForms || false;
  8508. this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  8509. this._leadingTriviaCodePoints =
  8510. options.leadingTriviaChars && options.leadingTriviaChars.map(c => c.codePointAt(0) || 0);
  8511. const range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
  8512. this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
  8513. new PlainCharacterCursor(_file, range);
  8514. try {
  8515. this._cursor.init();
  8516. }
  8517. catch (e) {
  8518. this.handleError(e);
  8519. }
  8520. }
  8521. _processCarriageReturns(content) {
  8522. // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
  8523. // In order to keep the original position in the source, we can not
  8524. // pre-process it.
  8525. // Instead CRs are processed right before instantiating the tokens.
  8526. return content.replace(_CR_OR_CRLF_REGEXP, '\n');
  8527. }
  8528. tokenize() {
  8529. while (this._cursor.peek() !== $EOF) {
  8530. const start = this._cursor.clone();
  8531. try {
  8532. if (this._attemptCharCode($LT)) {
  8533. if (this._attemptCharCode($BANG)) {
  8534. if (this._attemptCharCode($LBRACKET)) {
  8535. this._consumeCdata(start);
  8536. }
  8537. else if (this._attemptCharCode($MINUS)) {
  8538. this._consumeComment(start);
  8539. }
  8540. else {
  8541. this._consumeDocType(start);
  8542. }
  8543. }
  8544. else if (this._attemptCharCode($SLASH)) {
  8545. this._consumeTagClose(start);
  8546. }
  8547. else {
  8548. this._consumeTagOpen(start);
  8549. }
  8550. }
  8551. else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
  8552. this._consumeText();
  8553. }
  8554. }
  8555. catch (e) {
  8556. this.handleError(e);
  8557. }
  8558. }
  8559. this._beginToken(TokenType.EOF);
  8560. this._endToken([]);
  8561. return new TokenizeResult(mergeTextTokens(this.tokens), this.errors);
  8562. }
  8563. /**
  8564. * @returns whether an ICU token has been created
  8565. * @internal
  8566. */
  8567. _tokenizeExpansionForm() {
  8568. if (this.isExpansionFormStart()) {
  8569. this._consumeExpansionFormStart();
  8570. return true;
  8571. }
  8572. if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
  8573. this._consumeExpansionCaseStart();
  8574. return true;
  8575. }
  8576. if (this._cursor.peek() === $RBRACE) {
  8577. if (this._isInExpansionCase()) {
  8578. this._consumeExpansionCaseEnd();
  8579. return true;
  8580. }
  8581. if (this._isInExpansionForm()) {
  8582. this._consumeExpansionFormEnd();
  8583. return true;
  8584. }
  8585. }
  8586. return false;
  8587. }
  8588. _beginToken(type, start = this._cursor.clone()) {
  8589. this._currentTokenStart = start;
  8590. this._currentTokenType = type;
  8591. }
  8592. _endToken(parts, end = this._cursor.clone()) {
  8593. if (this._currentTokenStart === null) {
  8594. throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
  8595. }
  8596. if (this._currentTokenType === null) {
  8597. throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
  8598. }
  8599. const token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
  8600. this.tokens.push(token);
  8601. this._currentTokenStart = null;
  8602. this._currentTokenType = null;
  8603. return token;
  8604. }
  8605. _createError(msg, span) {
  8606. if (this._isInExpansionForm()) {
  8607. msg += ` (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`;
  8608. }
  8609. const error = new TokenError(msg, this._currentTokenType, span);
  8610. this._currentTokenStart = null;
  8611. this._currentTokenType = null;
  8612. return new _ControlFlowError(error);
  8613. }
  8614. handleError(e) {
  8615. if (e instanceof CursorError) {
  8616. e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
  8617. }
  8618. if (e instanceof _ControlFlowError) {
  8619. this.errors.push(e.error);
  8620. }
  8621. else {
  8622. throw e;
  8623. }
  8624. }
  8625. _attemptCharCode(charCode) {
  8626. if (this._cursor.peek() === charCode) {
  8627. this._cursor.advance();
  8628. return true;
  8629. }
  8630. return false;
  8631. }
  8632. _attemptCharCodeCaseInsensitive(charCode) {
  8633. if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
  8634. this._cursor.advance();
  8635. return true;
  8636. }
  8637. return false;
  8638. }
  8639. _requireCharCode(charCode) {
  8640. const location = this._cursor.clone();
  8641. if (!this._attemptCharCode(charCode)) {
  8642. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  8643. }
  8644. }
  8645. _attemptStr(chars) {
  8646. const len = chars.length;
  8647. if (this._cursor.charsLeft() < len) {
  8648. return false;
  8649. }
  8650. const initialPosition = this._cursor.clone();
  8651. for (let i = 0; i < len; i++) {
  8652. if (!this._attemptCharCode(chars.charCodeAt(i))) {
  8653. // If attempting to parse the string fails, we want to reset the parser
  8654. // to where it was before the attempt
  8655. this._cursor = initialPosition;
  8656. return false;
  8657. }
  8658. }
  8659. return true;
  8660. }
  8661. _attemptStrCaseInsensitive(chars) {
  8662. for (let i = 0; i < chars.length; i++) {
  8663. if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
  8664. return false;
  8665. }
  8666. }
  8667. return true;
  8668. }
  8669. _requireStr(chars) {
  8670. const location = this._cursor.clone();
  8671. if (!this._attemptStr(chars)) {
  8672. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  8673. }
  8674. }
  8675. _attemptCharCodeUntilFn(predicate) {
  8676. while (!predicate(this._cursor.peek())) {
  8677. this._cursor.advance();
  8678. }
  8679. }
  8680. _requireCharCodeUntilFn(predicate, len) {
  8681. const start = this._cursor.clone();
  8682. this._attemptCharCodeUntilFn(predicate);
  8683. const end = this._cursor.clone();
  8684. if (end.diff(start) < len) {
  8685. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  8686. }
  8687. }
  8688. _attemptUntilChar(char) {
  8689. while (this._cursor.peek() !== char) {
  8690. this._cursor.advance();
  8691. }
  8692. }
  8693. _readChar(decodeEntities) {
  8694. if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
  8695. return this._decodeEntity();
  8696. }
  8697. else {
  8698. // Don't rely upon reading directly from `_input` as the actual char value
  8699. // may have been generated from an escape sequence.
  8700. const char = String.fromCodePoint(this._cursor.peek());
  8701. this._cursor.advance();
  8702. return char;
  8703. }
  8704. }
  8705. _decodeEntity() {
  8706. const start = this._cursor.clone();
  8707. this._cursor.advance();
  8708. if (this._attemptCharCode($HASH)) {
  8709. const isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
  8710. const codeStart = this._cursor.clone();
  8711. this._attemptCharCodeUntilFn(isDigitEntityEnd);
  8712. if (this._cursor.peek() != $SEMICOLON) {
  8713. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan());
  8714. }
  8715. const strNum = this._cursor.getChars(codeStart);
  8716. this._cursor.advance();
  8717. try {
  8718. const charCode = parseInt(strNum, isHex ? 16 : 10);
  8719. return String.fromCharCode(charCode);
  8720. }
  8721. catch (_a) {
  8722. throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
  8723. }
  8724. }
  8725. else {
  8726. const nameStart = this._cursor.clone();
  8727. this._attemptCharCodeUntilFn(isNamedEntityEnd);
  8728. if (this._cursor.peek() != $SEMICOLON) {
  8729. this._cursor = nameStart;
  8730. return '&';
  8731. }
  8732. const name = this._cursor.getChars(nameStart);
  8733. this._cursor.advance();
  8734. const char = NAMED_ENTITIES[name];
  8735. if (!char) {
  8736. throw this._createError(_unknownEntityErrorMsg(name), this._cursor.getSpan(start));
  8737. }
  8738. return char;
  8739. }
  8740. }
  8741. _consumeRawText(decodeEntities, endMarkerPredicate) {
  8742. this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
  8743. const parts = [];
  8744. while (true) {
  8745. const tagCloseStart = this._cursor.clone();
  8746. const foundEndMarker = endMarkerPredicate();
  8747. this._cursor = tagCloseStart;
  8748. if (foundEndMarker) {
  8749. break;
  8750. }
  8751. parts.push(this._readChar(decodeEntities));
  8752. }
  8753. return this._endToken([this._processCarriageReturns(parts.join(''))]);
  8754. }
  8755. _consumeComment(start) {
  8756. this._beginToken(TokenType.COMMENT_START, start);
  8757. this._requireCharCode($MINUS);
  8758. this._endToken([]);
  8759. this._consumeRawText(false, () => this._attemptStr('-->'));
  8760. this._beginToken(TokenType.COMMENT_END);
  8761. this._requireStr('-->');
  8762. this._endToken([]);
  8763. }
  8764. _consumeCdata(start) {
  8765. this._beginToken(TokenType.CDATA_START, start);
  8766. this._requireStr('CDATA[');
  8767. this._endToken([]);
  8768. this._consumeRawText(false, () => this._attemptStr(']]>'));
  8769. this._beginToken(TokenType.CDATA_END);
  8770. this._requireStr(']]>');
  8771. this._endToken([]);
  8772. }
  8773. _consumeDocType(start) {
  8774. this._beginToken(TokenType.DOC_TYPE, start);
  8775. const contentStart = this._cursor.clone();
  8776. this._attemptUntilChar($GT);
  8777. const content = this._cursor.getChars(contentStart);
  8778. this._cursor.advance();
  8779. this._endToken([content]);
  8780. }
  8781. _consumePrefixAndName() {
  8782. const nameOrPrefixStart = this._cursor.clone();
  8783. let prefix = '';
  8784. while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
  8785. this._cursor.advance();
  8786. }
  8787. let nameStart;
  8788. if (this._cursor.peek() === $COLON) {
  8789. prefix = this._cursor.getChars(nameOrPrefixStart);
  8790. this._cursor.advance();
  8791. nameStart = this._cursor.clone();
  8792. }
  8793. else {
  8794. nameStart = nameOrPrefixStart;
  8795. }
  8796. this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
  8797. const name = this._cursor.getChars(nameStart);
  8798. return [prefix, name];
  8799. }
  8800. _consumeTagOpen(start) {
  8801. let tagName;
  8802. let prefix;
  8803. let openTagToken;
  8804. let tokensBeforeTagOpen = this.tokens.length;
  8805. const innerStart = this._cursor.clone();
  8806. try {
  8807. if (!isAsciiLetter(this._cursor.peek())) {
  8808. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  8809. }
  8810. openTagToken = this._consumeTagOpenStart(start);
  8811. prefix = openTagToken.parts[0];
  8812. tagName = openTagToken.parts[1];
  8813. this._attemptCharCodeUntilFn(isNotWhitespace);
  8814. while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT) {
  8815. this._consumeAttributeName();
  8816. this._attemptCharCodeUntilFn(isNotWhitespace);
  8817. if (this._attemptCharCode($EQ)) {
  8818. this._attemptCharCodeUntilFn(isNotWhitespace);
  8819. this._consumeAttributeValue();
  8820. }
  8821. this._attemptCharCodeUntilFn(isNotWhitespace);
  8822. }
  8823. this._consumeTagOpenEnd();
  8824. }
  8825. catch (e) {
  8826. if (e instanceof _ControlFlowError) {
  8827. // When the start tag is invalid (including invalid "attributes"), assume we want a "<"
  8828. this._cursor = innerStart;
  8829. if (openTagToken) {
  8830. this.tokens.length = tokensBeforeTagOpen;
  8831. }
  8832. // Back to back text tokens are merged at the end
  8833. this._beginToken(TokenType.TEXT, start);
  8834. this._endToken(['<']);
  8835. return;
  8836. }
  8837. throw e;
  8838. }
  8839. const contentTokenType = this._getTagDefinition(tagName).contentType;
  8840. if (contentTokenType === TagContentType.RAW_TEXT) {
  8841. this._consumeRawTextWithTagClose(prefix, tagName, false);
  8842. }
  8843. else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
  8844. this._consumeRawTextWithTagClose(prefix, tagName, true);
  8845. }
  8846. }
  8847. _consumeRawTextWithTagClose(prefix, tagName, decodeEntities) {
  8848. const textToken = this._consumeRawText(decodeEntities, () => {
  8849. if (!this._attemptCharCode($LT))
  8850. return false;
  8851. if (!this._attemptCharCode($SLASH))
  8852. return false;
  8853. this._attemptCharCodeUntilFn(isNotWhitespace);
  8854. if (!this._attemptStrCaseInsensitive(tagName))
  8855. return false;
  8856. this._attemptCharCodeUntilFn(isNotWhitespace);
  8857. return this._attemptCharCode($GT);
  8858. });
  8859. this._beginToken(TokenType.TAG_CLOSE);
  8860. this._requireCharCodeUntilFn(code => code === $GT, 3);
  8861. this._cursor.advance(); // Consume the `>`
  8862. this._endToken([prefix, tagName]);
  8863. }
  8864. _consumeTagOpenStart(start) {
  8865. this._beginToken(TokenType.TAG_OPEN_START, start);
  8866. const parts = this._consumePrefixAndName();
  8867. return this._endToken(parts);
  8868. }
  8869. _consumeAttributeName() {
  8870. const attrNameStart = this._cursor.peek();
  8871. if (attrNameStart === $SQ || attrNameStart === $DQ) {
  8872. throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
  8873. }
  8874. this._beginToken(TokenType.ATTR_NAME);
  8875. const prefixAndName = this._consumePrefixAndName();
  8876. this._endToken(prefixAndName);
  8877. }
  8878. _consumeAttributeValue() {
  8879. let value;
  8880. if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
  8881. this._beginToken(TokenType.ATTR_QUOTE);
  8882. const quoteChar = this._cursor.peek();
  8883. this._cursor.advance();
  8884. this._endToken([String.fromCodePoint(quoteChar)]);
  8885. this._beginToken(TokenType.ATTR_VALUE);
  8886. const parts = [];
  8887. while (this._cursor.peek() !== quoteChar) {
  8888. parts.push(this._readChar(true));
  8889. }
  8890. value = parts.join('');
  8891. this._endToken([this._processCarriageReturns(value)]);
  8892. this._beginToken(TokenType.ATTR_QUOTE);
  8893. this._cursor.advance();
  8894. this._endToken([String.fromCodePoint(quoteChar)]);
  8895. }
  8896. else {
  8897. this._beginToken(TokenType.ATTR_VALUE);
  8898. const valueStart = this._cursor.clone();
  8899. this._requireCharCodeUntilFn(isNameEnd, 1);
  8900. value = this._cursor.getChars(valueStart);
  8901. this._endToken([this._processCarriageReturns(value)]);
  8902. }
  8903. }
  8904. _consumeTagOpenEnd() {
  8905. const tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
  8906. this._beginToken(tokenType);
  8907. this._requireCharCode($GT);
  8908. this._endToken([]);
  8909. }
  8910. _consumeTagClose(start) {
  8911. this._beginToken(TokenType.TAG_CLOSE, start);
  8912. this._attemptCharCodeUntilFn(isNotWhitespace);
  8913. const prefixAndName = this._consumePrefixAndName();
  8914. this._attemptCharCodeUntilFn(isNotWhitespace);
  8915. this._requireCharCode($GT);
  8916. this._endToken(prefixAndName);
  8917. }
  8918. _consumeExpansionFormStart() {
  8919. this._beginToken(TokenType.EXPANSION_FORM_START);
  8920. this._requireCharCode($LBRACE);
  8921. this._endToken([]);
  8922. this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
  8923. this._beginToken(TokenType.RAW_TEXT);
  8924. const condition = this._readUntil($COMMA);
  8925. this._endToken([condition]);
  8926. this._requireCharCode($COMMA);
  8927. this._attemptCharCodeUntilFn(isNotWhitespace);
  8928. this._beginToken(TokenType.RAW_TEXT);
  8929. const type = this._readUntil($COMMA);
  8930. this._endToken([type]);
  8931. this._requireCharCode($COMMA);
  8932. this._attemptCharCodeUntilFn(isNotWhitespace);
  8933. }
  8934. _consumeExpansionCaseStart() {
  8935. this._beginToken(TokenType.EXPANSION_CASE_VALUE);
  8936. const value = this._readUntil($LBRACE).trim();
  8937. this._endToken([value]);
  8938. this._attemptCharCodeUntilFn(isNotWhitespace);
  8939. this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
  8940. this._requireCharCode($LBRACE);
  8941. this._endToken([]);
  8942. this._attemptCharCodeUntilFn(isNotWhitespace);
  8943. this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
  8944. }
  8945. _consumeExpansionCaseEnd() {
  8946. this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
  8947. this._requireCharCode($RBRACE);
  8948. this._endToken([]);
  8949. this._attemptCharCodeUntilFn(isNotWhitespace);
  8950. this._expansionCaseStack.pop();
  8951. }
  8952. _consumeExpansionFormEnd() {
  8953. this._beginToken(TokenType.EXPANSION_FORM_END);
  8954. this._requireCharCode($RBRACE);
  8955. this._endToken([]);
  8956. this._expansionCaseStack.pop();
  8957. }
  8958. _consumeText() {
  8959. const start = this._cursor.clone();
  8960. this._beginToken(TokenType.TEXT, start);
  8961. const parts = [];
  8962. do {
  8963. if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
  8964. parts.push(this._interpolationConfig.start);
  8965. this._inInterpolation = true;
  8966. }
  8967. else if (this._interpolationConfig && this._inInterpolation &&
  8968. this._attemptStr(this._interpolationConfig.end)) {
  8969. parts.push(this._interpolationConfig.end);
  8970. this._inInterpolation = false;
  8971. }
  8972. else {
  8973. parts.push(this._readChar(true));
  8974. }
  8975. } while (!this._isTextEnd());
  8976. this._endToken([this._processCarriageReturns(parts.join(''))]);
  8977. }
  8978. _isTextEnd() {
  8979. if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
  8980. return true;
  8981. }
  8982. if (this._tokenizeIcu && !this._inInterpolation) {
  8983. if (this.isExpansionFormStart()) {
  8984. // start of an expansion form
  8985. return true;
  8986. }
  8987. if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
  8988. // end of and expansion case
  8989. return true;
  8990. }
  8991. }
  8992. return false;
  8993. }
  8994. _readUntil(char) {
  8995. const start = this._cursor.clone();
  8996. this._attemptUntilChar(char);
  8997. return this._cursor.getChars(start);
  8998. }
  8999. _isInExpansionCase() {
  9000. return this._expansionCaseStack.length > 0 &&
  9001. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9002. TokenType.EXPANSION_CASE_EXP_START;
  9003. }
  9004. _isInExpansionForm() {
  9005. return this._expansionCaseStack.length > 0 &&
  9006. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9007. TokenType.EXPANSION_FORM_START;
  9008. }
  9009. isExpansionFormStart() {
  9010. if (this._cursor.peek() !== $LBRACE) {
  9011. return false;
  9012. }
  9013. if (this._interpolationConfig) {
  9014. const start = this._cursor.clone();
  9015. const isInterpolation = this._attemptStr(this._interpolationConfig.start);
  9016. this._cursor = start;
  9017. return !isInterpolation;
  9018. }
  9019. return true;
  9020. }
  9021. }
  9022. function isNotWhitespace(code) {
  9023. return !isWhitespace(code) || code === $EOF;
  9024. }
  9025. function isNameEnd(code) {
  9026. return isWhitespace(code) || code === $GT || code === $SLASH ||
  9027. code === $SQ || code === $DQ || code === $EQ;
  9028. }
  9029. function isPrefixEnd(code) {
  9030. return (code < $a || $z < code) && (code < $A || $Z < code) &&
  9031. (code < $0 || code > $9);
  9032. }
  9033. function isDigitEntityEnd(code) {
  9034. return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
  9035. }
  9036. function isNamedEntityEnd(code) {
  9037. return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
  9038. }
  9039. function isExpansionCaseStart(peek) {
  9040. return peek === $EQ || isAsciiLetter(peek) || isDigit(peek);
  9041. }
  9042. function compareCharCodeCaseInsensitive(code1, code2) {
  9043. return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
  9044. }
  9045. function toUpperCaseCharCode(code) {
  9046. return code >= $a && code <= $z ? code - $a + $A : code;
  9047. }
  9048. function mergeTextTokens(srcTokens) {
  9049. const dstTokens = [];
  9050. let lastDstToken = undefined;
  9051. for (let i = 0; i < srcTokens.length; i++) {
  9052. const token = srcTokens[i];
  9053. if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
  9054. lastDstToken.parts[0] += token.parts[0];
  9055. lastDstToken.sourceSpan.end = token.sourceSpan.end;
  9056. }
  9057. else {
  9058. lastDstToken = token;
  9059. dstTokens.push(lastDstToken);
  9060. }
  9061. }
  9062. return dstTokens;
  9063. }
  9064. class PlainCharacterCursor {
  9065. constructor(fileOrCursor, range) {
  9066. if (fileOrCursor instanceof PlainCharacterCursor) {
  9067. this.file = fileOrCursor.file;
  9068. this.input = fileOrCursor.input;
  9069. this.end = fileOrCursor.end;
  9070. this.state = Object.assign({}, fileOrCursor.state);
  9071. }
  9072. else {
  9073. if (!range) {
  9074. throw new Error('Programming error: the range argument must be provided with a file argument.');
  9075. }
  9076. this.file = fileOrCursor;
  9077. this.input = fileOrCursor.content;
  9078. this.end = range.endPos;
  9079. this.state = {
  9080. peek: -1,
  9081. offset: range.startPos,
  9082. line: range.startLine,
  9083. column: range.startCol,
  9084. };
  9085. }
  9086. }
  9087. clone() { return new PlainCharacterCursor(this); }
  9088. peek() { return this.state.peek; }
  9089. charsLeft() { return this.end - this.state.offset; }
  9090. diff(other) { return this.state.offset - other.state.offset; }
  9091. advance() { this.advanceState(this.state); }
  9092. init() { this.updatePeek(this.state); }
  9093. getSpan(start, leadingTriviaCodePoints) {
  9094. start = start || this;
  9095. if (leadingTriviaCodePoints) {
  9096. start = start.clone();
  9097. while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
  9098. start.advance();
  9099. }
  9100. }
  9101. 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));
  9102. }
  9103. getChars(start) {
  9104. return this.input.substring(start.state.offset, this.state.offset);
  9105. }
  9106. charAt(pos) { return this.input.charCodeAt(pos); }
  9107. advanceState(state) {
  9108. if (state.offset >= this.end) {
  9109. this.state = state;
  9110. throw new CursorError('Unexpected character "EOF"', this);
  9111. }
  9112. const currentChar = this.charAt(state.offset);
  9113. if (currentChar === $LF) {
  9114. state.line++;
  9115. state.column = 0;
  9116. }
  9117. else if (!isNewLine(currentChar)) {
  9118. state.column++;
  9119. }
  9120. state.offset++;
  9121. this.updatePeek(state);
  9122. }
  9123. updatePeek(state) {
  9124. state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
  9125. }
  9126. }
  9127. class EscapedCharacterCursor extends PlainCharacterCursor {
  9128. constructor(fileOrCursor, range) {
  9129. if (fileOrCursor instanceof EscapedCharacterCursor) {
  9130. super(fileOrCursor);
  9131. this.internalState = Object.assign({}, fileOrCursor.internalState);
  9132. }
  9133. else {
  9134. super(fileOrCursor, range);
  9135. this.internalState = this.state;
  9136. }
  9137. }
  9138. advance() {
  9139. this.state = this.internalState;
  9140. super.advance();
  9141. this.processEscapeSequence();
  9142. }
  9143. init() {
  9144. super.init();
  9145. this.processEscapeSequence();
  9146. }
  9147. clone() { return new EscapedCharacterCursor(this); }
  9148. getChars(start) {
  9149. const cursor = start.clone();
  9150. let chars = '';
  9151. while (cursor.internalState.offset < this.internalState.offset) {
  9152. chars += String.fromCodePoint(cursor.peek());
  9153. cursor.advance();
  9154. }
  9155. return chars;
  9156. }
  9157. /**
  9158. * Process the escape sequence that starts at the current position in the text.
  9159. *
  9160. * This method is called to ensure that `peek` has the unescaped value of escape sequences.
  9161. */
  9162. processEscapeSequence() {
  9163. const peek = () => this.internalState.peek;
  9164. if (peek() === $BACKSLASH) {
  9165. // We have hit an escape sequence so we need the internal state to become independent
  9166. // of the external state.
  9167. this.internalState = Object.assign({}, this.state);
  9168. // Move past the backslash
  9169. this.advanceState(this.internalState);
  9170. // First check for standard control char sequences
  9171. if (peek() === $n) {
  9172. this.state.peek = $LF;
  9173. }
  9174. else if (peek() === $r) {
  9175. this.state.peek = $CR;
  9176. }
  9177. else if (peek() === $v) {
  9178. this.state.peek = $VTAB;
  9179. }
  9180. else if (peek() === $t) {
  9181. this.state.peek = $TAB;
  9182. }
  9183. else if (peek() === $b) {
  9184. this.state.peek = $BSPACE;
  9185. }
  9186. else if (peek() === $f) {
  9187. this.state.peek = $FF;
  9188. }
  9189. // Now consider more complex sequences
  9190. else if (peek() === $u) {
  9191. // Unicode code-point sequence
  9192. this.advanceState(this.internalState); // advance past the `u` char
  9193. if (peek() === $LBRACE) {
  9194. // Variable length Unicode, e.g. `\x{123}`
  9195. this.advanceState(this.internalState); // advance past the `{` char
  9196. // Advance past the variable number of hex digits until we hit a `}` char
  9197. const digitStart = this.clone();
  9198. let length = 0;
  9199. while (peek() !== $RBRACE) {
  9200. this.advanceState(this.internalState);
  9201. length++;
  9202. }
  9203. this.state.peek = this.decodeHexDigits(digitStart, length);
  9204. }
  9205. else {
  9206. // Fixed length Unicode, e.g. `\u1234`
  9207. const digitStart = this.clone();
  9208. this.advanceState(this.internalState);
  9209. this.advanceState(this.internalState);
  9210. this.advanceState(this.internalState);
  9211. this.state.peek = this.decodeHexDigits(digitStart, 4);
  9212. }
  9213. }
  9214. else if (peek() === $x) {
  9215. // Hex char code, e.g. `\x2F`
  9216. this.advanceState(this.internalState); // advance past the `x` char
  9217. const digitStart = this.clone();
  9218. this.advanceState(this.internalState);
  9219. this.state.peek = this.decodeHexDigits(digitStart, 2);
  9220. }
  9221. else if (isOctalDigit(peek())) {
  9222. // Octal char code, e.g. `\012`,
  9223. let octal = '';
  9224. let length = 0;
  9225. let previous = this.clone();
  9226. while (isOctalDigit(peek()) && length < 3) {
  9227. previous = this.clone();
  9228. octal += String.fromCodePoint(peek());
  9229. this.advanceState(this.internalState);
  9230. length++;
  9231. }
  9232. this.state.peek = parseInt(octal, 8);
  9233. // Backup one char
  9234. this.internalState = previous.internalState;
  9235. }
  9236. else if (isNewLine(this.internalState.peek)) {
  9237. // Line continuation `\` followed by a new line
  9238. this.advanceState(this.internalState); // advance over the newline
  9239. this.state = this.internalState;
  9240. }
  9241. else {
  9242. // If none of the `if` blocks were executed then we just have an escaped normal character.
  9243. // In that case we just, effectively, skip the backslash from the character.
  9244. this.state.peek = this.internalState.peek;
  9245. }
  9246. }
  9247. }
  9248. decodeHexDigits(start, length) {
  9249. const hex = this.input.substr(start.internalState.offset, length);
  9250. const charCode = parseInt(hex, 16);
  9251. if (!isNaN(charCode)) {
  9252. return charCode;
  9253. }
  9254. else {
  9255. start.state = start.internalState;
  9256. throw new CursorError('Invalid hexadecimal escape sequence', start);
  9257. }
  9258. }
  9259. }
  9260. class CursorError {
  9261. constructor(msg, cursor) {
  9262. this.msg = msg;
  9263. this.cursor = cursor;
  9264. }
  9265. }
  9266. /**
  9267. * @license
  9268. * Copyright Google Inc. All Rights Reserved.
  9269. *
  9270. * Use of this source code is governed by an MIT-style license that can be
  9271. * found in the LICENSE file at https://angular.io/license
  9272. */
  9273. class TreeError extends ParseError {
  9274. constructor(elementName, span, msg) {
  9275. super(span, msg);
  9276. this.elementName = elementName;
  9277. }
  9278. static create(elementName, span, msg) {
  9279. return new TreeError(elementName, span, msg);
  9280. }
  9281. }
  9282. class ParseTreeResult {
  9283. constructor(rootNodes, errors) {
  9284. this.rootNodes = rootNodes;
  9285. this.errors = errors;
  9286. }
  9287. }
  9288. class Parser {
  9289. constructor(getTagDefinition) {
  9290. this.getTagDefinition = getTagDefinition;
  9291. }
  9292. parse(source, url, options) {
  9293. const tokensAndErrors = tokenize(source, url, this.getTagDefinition, options);
  9294. const treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
  9295. return new ParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors));
  9296. }
  9297. }
  9298. class _TreeBuilder {
  9299. constructor(tokens, getTagDefinition) {
  9300. this.tokens = tokens;
  9301. this.getTagDefinition = getTagDefinition;
  9302. this._index = -1;
  9303. this._rootNodes = [];
  9304. this._errors = [];
  9305. this._elementStack = [];
  9306. this._advance();
  9307. }
  9308. build() {
  9309. while (this._peek.type !== TokenType.EOF) {
  9310. if (this._peek.type === TokenType.TAG_OPEN_START) {
  9311. this._consumeStartTag(this._advance());
  9312. }
  9313. else if (this._peek.type === TokenType.TAG_CLOSE) {
  9314. this._consumeEndTag(this._advance());
  9315. }
  9316. else if (this._peek.type === TokenType.CDATA_START) {
  9317. this._closeVoidElement();
  9318. this._consumeCdata(this._advance());
  9319. }
  9320. else if (this._peek.type === TokenType.COMMENT_START) {
  9321. this._closeVoidElement();
  9322. this._consumeComment(this._advance());
  9323. }
  9324. else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
  9325. this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
  9326. this._closeVoidElement();
  9327. this._consumeText(this._advance());
  9328. }
  9329. else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
  9330. this._consumeExpansion(this._advance());
  9331. }
  9332. else {
  9333. // Skip all other tokens...
  9334. this._advance();
  9335. }
  9336. }
  9337. return new ParseTreeResult(this._rootNodes, this._errors);
  9338. }
  9339. _advance() {
  9340. const prev = this._peek;
  9341. if (this._index < this.tokens.length - 1) {
  9342. // Note: there is always an EOF token at the end
  9343. this._index++;
  9344. }
  9345. this._peek = this.tokens[this._index];
  9346. return prev;
  9347. }
  9348. _advanceIf(type) {
  9349. if (this._peek.type === type) {
  9350. return this._advance();
  9351. }
  9352. return null;
  9353. }
  9354. _consumeCdata(startToken) {
  9355. this._consumeText(this._advance());
  9356. this._advanceIf(TokenType.CDATA_END);
  9357. }
  9358. _consumeComment(token) {
  9359. const text = this._advanceIf(TokenType.RAW_TEXT);
  9360. this._advanceIf(TokenType.COMMENT_END);
  9361. const value = text != null ? text.parts[0].trim() : null;
  9362. this._addToParent(new Comment(value, token.sourceSpan));
  9363. }
  9364. _consumeExpansion(token) {
  9365. const switchValue = this._advance();
  9366. const type = this._advance();
  9367. const cases = [];
  9368. // read =
  9369. while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
  9370. const expCase = this._parseExpansionCase();
  9371. if (!expCase)
  9372. return; // error
  9373. cases.push(expCase);
  9374. }
  9375. // read the final }
  9376. if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
  9377. this._errors.push(TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '}'.`));
  9378. return;
  9379. }
  9380. const sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
  9381. this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
  9382. this._advance();
  9383. }
  9384. _parseExpansionCase() {
  9385. const value = this._advance();
  9386. // read {
  9387. if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
  9388. this._errors.push(TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '{'.`));
  9389. return null;
  9390. }
  9391. // read until }
  9392. const start = this._advance();
  9393. const exp = this._collectExpansionExpTokens(start);
  9394. if (!exp)
  9395. return null;
  9396. const end = this._advance();
  9397. exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
  9398. // parse everything in between { and }
  9399. const parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
  9400. if (parsedExp.errors.length > 0) {
  9401. this._errors = this._errors.concat(parsedExp.errors);
  9402. return null;
  9403. }
  9404. const sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
  9405. const expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
  9406. return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
  9407. }
  9408. _collectExpansionExpTokens(start) {
  9409. const exp = [];
  9410. const expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
  9411. while (true) {
  9412. if (this._peek.type === TokenType.EXPANSION_FORM_START ||
  9413. this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
  9414. expansionFormStack.push(this._peek.type);
  9415. }
  9416. if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
  9417. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
  9418. expansionFormStack.pop();
  9419. if (expansionFormStack.length == 0)
  9420. return exp;
  9421. }
  9422. else {
  9423. this._errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
  9424. return null;
  9425. }
  9426. }
  9427. if (this._peek.type === TokenType.EXPANSION_FORM_END) {
  9428. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
  9429. expansionFormStack.pop();
  9430. }
  9431. else {
  9432. this._errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
  9433. return null;
  9434. }
  9435. }
  9436. if (this._peek.type === TokenType.EOF) {
  9437. this._errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
  9438. return null;
  9439. }
  9440. exp.push(this._advance());
  9441. }
  9442. }
  9443. _consumeText(token) {
  9444. let text = token.parts[0];
  9445. if (text.length > 0 && text[0] == '\n') {
  9446. const parent = this._getParentElement();
  9447. if (parent != null && parent.children.length == 0 &&
  9448. this.getTagDefinition(parent.name).ignoreFirstLf) {
  9449. text = text.substring(1);
  9450. }
  9451. }
  9452. if (text.length > 0) {
  9453. this._addToParent(new Text$3(text, token.sourceSpan));
  9454. }
  9455. }
  9456. _closeVoidElement() {
  9457. const el = this._getParentElement();
  9458. if (el && this.getTagDefinition(el.name).isVoid) {
  9459. this._elementStack.pop();
  9460. }
  9461. }
  9462. _consumeStartTag(startTagToken) {
  9463. const prefix = startTagToken.parts[0];
  9464. const name = startTagToken.parts[1];
  9465. const attrs = [];
  9466. while (this._peek.type === TokenType.ATTR_NAME) {
  9467. attrs.push(this._consumeAttr(this._advance()));
  9468. }
  9469. const fullName = this._getElementFullName(prefix, name, this._getParentElement());
  9470. let selfClosing = false;
  9471. // Note: There could have been a tokenizer error
  9472. // so that we don't get a token for the end tag...
  9473. if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
  9474. this._advance();
  9475. selfClosing = true;
  9476. const tagDef = this.getTagDefinition(fullName);
  9477. if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
  9478. this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, `Only void and foreign elements can be self closed "${startTagToken.parts[1]}"`));
  9479. }
  9480. }
  9481. else if (this._peek.type === TokenType.TAG_OPEN_END) {
  9482. this._advance();
  9483. selfClosing = false;
  9484. }
  9485. const end = this._peek.sourceSpan.start;
  9486. const span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
  9487. const el = new Element$1(fullName, attrs, [], span, span, undefined);
  9488. this._pushElement(el);
  9489. if (selfClosing) {
  9490. this._popElement(fullName);
  9491. el.endSourceSpan = span;
  9492. }
  9493. }
  9494. _pushElement(el) {
  9495. const parentEl = this._getParentElement();
  9496. if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
  9497. this._elementStack.pop();
  9498. }
  9499. this._addToParent(el);
  9500. this._elementStack.push(el);
  9501. }
  9502. _consumeEndTag(endTagToken) {
  9503. const fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
  9504. if (this._getParentElement()) {
  9505. this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
  9506. }
  9507. if (this.getTagDefinition(fullName).isVoid) {
  9508. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, `Void elements do not have end tags "${endTagToken.parts[1]}"`));
  9509. }
  9510. else if (!this._popElement(fullName)) {
  9511. const 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`;
  9512. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
  9513. }
  9514. }
  9515. _popElement(fullName) {
  9516. for (let stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
  9517. const el = this._elementStack[stackIndex];
  9518. if (el.name == fullName) {
  9519. this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
  9520. return true;
  9521. }
  9522. if (!this.getTagDefinition(el.name).closedByParent) {
  9523. return false;
  9524. }
  9525. }
  9526. return false;
  9527. }
  9528. _consumeAttr(attrName) {
  9529. const fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
  9530. let end = attrName.sourceSpan.end;
  9531. let value = '';
  9532. let valueSpan = undefined;
  9533. if (this._peek.type === TokenType.ATTR_QUOTE) {
  9534. this._advance();
  9535. }
  9536. if (this._peek.type === TokenType.ATTR_VALUE) {
  9537. const valueToken = this._advance();
  9538. value = valueToken.parts[0];
  9539. end = valueToken.sourceSpan.end;
  9540. valueSpan = valueToken.sourceSpan;
  9541. }
  9542. if (this._peek.type === TokenType.ATTR_QUOTE) {
  9543. const quoteToken = this._advance();
  9544. end = quoteToken.sourceSpan.end;
  9545. }
  9546. return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan);
  9547. }
  9548. _getParentElement() {
  9549. return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
  9550. }
  9551. /**
  9552. * Returns the parent in the DOM and the container.
  9553. *
  9554. * `<ng-container>` elements are skipped as they are not rendered as DOM element.
  9555. */
  9556. _getParentElementSkippingContainers() {
  9557. let container = null;
  9558. for (let i = this._elementStack.length - 1; i >= 0; i--) {
  9559. if (!isNgContainer(this._elementStack[i].name)) {
  9560. return { parent: this._elementStack[i], container };
  9561. }
  9562. container = this._elementStack[i];
  9563. }
  9564. return { parent: null, container };
  9565. }
  9566. _addToParent(node) {
  9567. const parent = this._getParentElement();
  9568. if (parent != null) {
  9569. parent.children.push(node);
  9570. }
  9571. else {
  9572. this._rootNodes.push(node);
  9573. }
  9574. }
  9575. /**
  9576. * Insert a node between the parent and the container.
  9577. * When no container is given, the node is appended as a child of the parent.
  9578. * Also updates the element stack accordingly.
  9579. *
  9580. * @internal
  9581. */
  9582. _insertBeforeContainer(parent, container, node) {
  9583. if (!container) {
  9584. this._addToParent(node);
  9585. this._elementStack.push(node);
  9586. }
  9587. else {
  9588. if (parent) {
  9589. // replace the container with the new node in the children
  9590. const index = parent.children.indexOf(container);
  9591. parent.children[index] = node;
  9592. }
  9593. else {
  9594. this._rootNodes.push(node);
  9595. }
  9596. node.children.push(container);
  9597. this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
  9598. }
  9599. }
  9600. _getElementFullName(prefix, localName, parentElement) {
  9601. if (prefix === '') {
  9602. prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
  9603. if (prefix === '' && parentElement != null) {
  9604. prefix = getNsPrefix(parentElement.name);
  9605. }
  9606. }
  9607. return mergeNsAndName(prefix, localName);
  9608. }
  9609. }
  9610. function lastOnStack(stack, element) {
  9611. return stack.length > 0 && stack[stack.length - 1] === element;
  9612. }
  9613. /**
  9614. * @license
  9615. * Copyright Google Inc. All Rights Reserved.
  9616. *
  9617. * Use of this source code is governed by an MIT-style license that can be
  9618. * found in the LICENSE file at https://angular.io/license
  9619. */
  9620. class HtmlParser extends Parser {
  9621. constructor() { super(getHtmlTagDefinition); }
  9622. parse(source, url, options) {
  9623. return super.parse(source, url, options);
  9624. }
  9625. }
  9626. /**
  9627. * @license
  9628. * Copyright Google Inc. All Rights Reserved.
  9629. *
  9630. * Use of this source code is governed by an MIT-style license that can be
  9631. * found in the LICENSE file at https://angular.io/license
  9632. */
  9633. const PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
  9634. const SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
  9635. // Equivalent to \s with \u00a0 (non-breaking space) excluded.
  9636. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  9637. const WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
  9638. const NO_WS_REGEXP = new RegExp(`[^${WS_CHARS}]`);
  9639. const WS_REPLACE_REGEXP = new RegExp(`[${WS_CHARS}]{2,}`, 'g');
  9640. function hasPreserveWhitespacesAttr(attrs) {
  9641. return attrs.some((attr) => attr.name === PRESERVE_WS_ATTR_NAME);
  9642. }
  9643. /**
  9644. * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
  9645. * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
  9646. * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
  9647. * and later on replaced by a space. We are re-implementing the same idea here.
  9648. */
  9649. function replaceNgsp(value) {
  9650. // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
  9651. return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
  9652. }
  9653. /**
  9654. * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
  9655. * - consider spaces, tabs and new lines as whitespace characters;
  9656. * - drop text nodes consisting of whitespace characters only;
  9657. * - for all other text nodes replace consecutive whitespace characters with one space;
  9658. * - convert &ngsp; pseudo-entity to a single space;
  9659. *
  9660. * Removal and trimming of whitespaces have positive performance impact (less code to generate
  9661. * while compiling templates, faster view creation). At the same time it can be "destructive"
  9662. * in some cases (whitespaces can influence layout). Because of the potential of breaking layout
  9663. * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
  9664. * whitespace removal. The default option for whitespace removal will be revisited in Angular 6
  9665. * and might be changed to "on" by default.
  9666. */
  9667. class WhitespaceVisitor {
  9668. visitElement(element, context) {
  9669. if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
  9670. // don't descent into elements where we need to preserve whitespaces
  9671. // but still visit all attributes to eliminate one used as a market to preserve WS
  9672. return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  9673. }
  9674. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  9675. }
  9676. visitAttribute(attribute, context) {
  9677. return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
  9678. }
  9679. visitText(text, context) {
  9680. const isNotBlank = text.value.match(NO_WS_REGEXP);
  9681. if (isNotBlank) {
  9682. return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
  9683. }
  9684. return null;
  9685. }
  9686. visitComment(comment, context) { return comment; }
  9687. visitExpansion(expansion, context) { return expansion; }
  9688. visitExpansionCase(expansionCase, context) { return expansionCase; }
  9689. }
  9690. function removeWhitespaces(htmlAstWithErrors) {
  9691. return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
  9692. }
  9693. /**
  9694. * @license
  9695. * Copyright Google Inc. All Rights Reserved.
  9696. *
  9697. * Use of this source code is governed by an MIT-style license that can be
  9698. * found in the LICENSE file at https://angular.io/license
  9699. */
  9700. // http://cldr.unicode.org/index/cldr-spec/plural-rules
  9701. const PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
  9702. /**
  9703. * Expands special forms into elements.
  9704. *
  9705. * For example,
  9706. *
  9707. * ```
  9708. * { messages.length, plural,
  9709. * =0 {zero}
  9710. * =1 {one}
  9711. * other {more than one}
  9712. * }
  9713. * ```
  9714. *
  9715. * will be expanded into
  9716. *
  9717. * ```
  9718. * <ng-container [ngPlural]="messages.length">
  9719. * <ng-template ngPluralCase="=0">zero</ng-template>
  9720. * <ng-template ngPluralCase="=1">one</ng-template>
  9721. * <ng-template ngPluralCase="other">more than one</ng-template>
  9722. * </ng-container>
  9723. * ```
  9724. */
  9725. function expandNodes(nodes) {
  9726. const expander = new _Expander();
  9727. return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
  9728. }
  9729. class ExpansionResult {
  9730. constructor(nodes, expanded, errors) {
  9731. this.nodes = nodes;
  9732. this.expanded = expanded;
  9733. this.errors = errors;
  9734. }
  9735. }
  9736. class ExpansionError extends ParseError {
  9737. constructor(span, errorMsg) { super(span, errorMsg); }
  9738. }
  9739. /**
  9740. * Expand expansion forms (plural, select) to directives
  9741. *
  9742. * @internal
  9743. */
  9744. class _Expander {
  9745. constructor() {
  9746. this.isExpanded = false;
  9747. this.errors = [];
  9748. }
  9749. visitElement(element, context) {
  9750. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
  9751. }
  9752. visitAttribute(attribute, context) { return attribute; }
  9753. visitText(text, context) { return text; }
  9754. visitComment(comment, context) { return comment; }
  9755. visitExpansion(icu, context) {
  9756. this.isExpanded = true;
  9757. return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
  9758. _expandDefaultForm(icu, this.errors);
  9759. }
  9760. visitExpansionCase(icuCase, context) {
  9761. throw new Error('Should not be reached');
  9762. }
  9763. }
  9764. // Plural forms are expanded to `NgPlural` and `NgPluralCase`s
  9765. function _expandPluralForm(ast, errors) {
  9766. const children = ast.cases.map(c => {
  9767. if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
  9768. errors.push(new ExpansionError(c.valueSourceSpan, `Plural cases should be "=<number>" or one of ${PLURAL_CASES.join(", ")}`));
  9769. }
  9770. const expansionResult = expandNodes(c.expression);
  9771. errors.push(...expansionResult.errors);
  9772. return new Element$1(`ng-template`, [new Attribute('ngPluralCase', `${c.value}`, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  9773. });
  9774. const switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan);
  9775. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  9776. }
  9777. // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
  9778. function _expandDefaultForm(ast, errors) {
  9779. const children = ast.cases.map(c => {
  9780. const expansionResult = expandNodes(c.expression);
  9781. errors.push(...expansionResult.errors);
  9782. if (c.value === 'other') {
  9783. // other is the default case when no values match
  9784. return new Element$1(`ng-template`, [new Attribute('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  9785. }
  9786. return new Element$1(`ng-template`, [new Attribute('ngSwitchCase', `${c.value}`, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  9787. });
  9788. const switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan);
  9789. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  9790. }
  9791. /**
  9792. * @license
  9793. * Copyright Google Inc. All Rights Reserved.
  9794. *
  9795. * Use of this source code is governed by an MIT-style license that can be
  9796. * found in the LICENSE file at https://angular.io/license
  9797. */
  9798. /**
  9799. * A segment of text within the template.
  9800. */
  9801. class TextAst {
  9802. constructor(value, ngContentIndex, sourceSpan) {
  9803. this.value = value;
  9804. this.ngContentIndex = ngContentIndex;
  9805. this.sourceSpan = sourceSpan;
  9806. }
  9807. visit(visitor, context) { return visitor.visitText(this, context); }
  9808. }
  9809. /**
  9810. * A bound expression within the text of a template.
  9811. */
  9812. class BoundTextAst {
  9813. constructor(value, ngContentIndex, sourceSpan) {
  9814. this.value = value;
  9815. this.ngContentIndex = ngContentIndex;
  9816. this.sourceSpan = sourceSpan;
  9817. }
  9818. visit(visitor, context) {
  9819. return visitor.visitBoundText(this, context);
  9820. }
  9821. }
  9822. /**
  9823. * A plain attribute on an element.
  9824. */
  9825. class AttrAst {
  9826. constructor(name, value, sourceSpan) {
  9827. this.name = name;
  9828. this.value = value;
  9829. this.sourceSpan = sourceSpan;
  9830. }
  9831. visit(visitor, context) { return visitor.visitAttr(this, context); }
  9832. }
  9833. const BoundPropertyMapping = {
  9834. [4 /* Animation */]: 4 /* Animation */,
  9835. [1 /* Attribute */]: 1 /* Attribute */,
  9836. [2 /* Class */]: 2 /* Class */,
  9837. [0 /* Property */]: 0 /* Property */,
  9838. [3 /* Style */]: 3 /* Style */,
  9839. };
  9840. /**
  9841. * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
  9842. * `[@trigger]="stateExp"`)
  9843. */
  9844. class BoundElementPropertyAst {
  9845. constructor(name, type, securityContext, value, unit, sourceSpan) {
  9846. this.name = name;
  9847. this.type = type;
  9848. this.securityContext = securityContext;
  9849. this.value = value;
  9850. this.unit = unit;
  9851. this.sourceSpan = sourceSpan;
  9852. this.isAnimation = this.type === 4 /* Animation */;
  9853. }
  9854. static fromBoundProperty(prop) {
  9855. const type = BoundPropertyMapping[prop.type];
  9856. return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
  9857. }
  9858. visit(visitor, context) {
  9859. return visitor.visitElementProperty(this, context);
  9860. }
  9861. }
  9862. /**
  9863. * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
  9864. * `(@trigger.phase)="callback($event)"`).
  9865. */
  9866. class BoundEventAst {
  9867. constructor(name, target, phase, handler, sourceSpan, handlerSpan) {
  9868. this.name = name;
  9869. this.target = target;
  9870. this.phase = phase;
  9871. this.handler = handler;
  9872. this.sourceSpan = sourceSpan;
  9873. this.handlerSpan = handlerSpan;
  9874. this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
  9875. this.isAnimation = !!this.phase;
  9876. }
  9877. static calcFullName(name, target, phase) {
  9878. if (target) {
  9879. return `${target}:${name}`;
  9880. }
  9881. if (phase) {
  9882. return `@${name}.${phase}`;
  9883. }
  9884. return name;
  9885. }
  9886. static fromParsedEvent(event) {
  9887. const target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  9888. const phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  9889. return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
  9890. }
  9891. visit(visitor, context) {
  9892. return visitor.visitEvent(this, context);
  9893. }
  9894. }
  9895. /**
  9896. * A reference declaration on an element (e.g. `let someName="expression"`).
  9897. */
  9898. class ReferenceAst {
  9899. constructor(name, value, originalValue, sourceSpan) {
  9900. this.name = name;
  9901. this.value = value;
  9902. this.originalValue = originalValue;
  9903. this.sourceSpan = sourceSpan;
  9904. }
  9905. visit(visitor, context) {
  9906. return visitor.visitReference(this, context);
  9907. }
  9908. }
  9909. /**
  9910. * A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
  9911. */
  9912. class VariableAst {
  9913. constructor(name, value, sourceSpan) {
  9914. this.name = name;
  9915. this.value = value;
  9916. this.sourceSpan = sourceSpan;
  9917. }
  9918. static fromParsedVariable(v) {
  9919. return new VariableAst(v.name, v.value, v.sourceSpan);
  9920. }
  9921. visit(visitor, context) {
  9922. return visitor.visitVariable(this, context);
  9923. }
  9924. }
  9925. /**
  9926. * An element declaration in a template.
  9927. */
  9928. class ElementAst {
  9929. constructor(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
  9930. this.name = name;
  9931. this.attrs = attrs;
  9932. this.inputs = inputs;
  9933. this.outputs = outputs;
  9934. this.references = references;
  9935. this.directives = directives;
  9936. this.providers = providers;
  9937. this.hasViewContainer = hasViewContainer;
  9938. this.queryMatches = queryMatches;
  9939. this.children = children;
  9940. this.ngContentIndex = ngContentIndex;
  9941. this.sourceSpan = sourceSpan;
  9942. this.endSourceSpan = endSourceSpan;
  9943. }
  9944. visit(visitor, context) {
  9945. return visitor.visitElement(this, context);
  9946. }
  9947. }
  9948. /**
  9949. * A `<ng-template>` element included in an Angular template.
  9950. */
  9951. class EmbeddedTemplateAst {
  9952. constructor(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
  9953. this.attrs = attrs;
  9954. this.outputs = outputs;
  9955. this.references = references;
  9956. this.variables = variables;
  9957. this.directives = directives;
  9958. this.providers = providers;
  9959. this.hasViewContainer = hasViewContainer;
  9960. this.queryMatches = queryMatches;
  9961. this.children = children;
  9962. this.ngContentIndex = ngContentIndex;
  9963. this.sourceSpan = sourceSpan;
  9964. }
  9965. visit(visitor, context) {
  9966. return visitor.visitEmbeddedTemplate(this, context);
  9967. }
  9968. }
  9969. /**
  9970. * A directive property with a bound value (e.g. `*ngIf="condition").
  9971. */
  9972. class BoundDirectivePropertyAst {
  9973. constructor(directiveName, templateName, value, sourceSpan) {
  9974. this.directiveName = directiveName;
  9975. this.templateName = templateName;
  9976. this.value = value;
  9977. this.sourceSpan = sourceSpan;
  9978. }
  9979. visit(visitor, context) {
  9980. return visitor.visitDirectiveProperty(this, context);
  9981. }
  9982. }
  9983. /**
  9984. * A directive declared on an element.
  9985. */
  9986. class DirectiveAst {
  9987. constructor(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
  9988. this.directive = directive;
  9989. this.inputs = inputs;
  9990. this.hostProperties = hostProperties;
  9991. this.hostEvents = hostEvents;
  9992. this.contentQueryStartId = contentQueryStartId;
  9993. this.sourceSpan = sourceSpan;
  9994. }
  9995. visit(visitor, context) {
  9996. return visitor.visitDirective(this, context);
  9997. }
  9998. }
  9999. /**
  10000. * A provider declared on an element
  10001. */
  10002. class ProviderAst {
  10003. constructor(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
  10004. this.token = token;
  10005. this.multiProvider = multiProvider;
  10006. this.eager = eager;
  10007. this.providers = providers;
  10008. this.providerType = providerType;
  10009. this.lifecycleHooks = lifecycleHooks;
  10010. this.sourceSpan = sourceSpan;
  10011. this.isModule = isModule;
  10012. }
  10013. visit(visitor, context) {
  10014. // No visit method in the visitor for now...
  10015. return null;
  10016. }
  10017. }
  10018. var ProviderAstType;
  10019. (function (ProviderAstType) {
  10020. ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
  10021. ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
  10022. ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
  10023. ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
  10024. ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
  10025. })(ProviderAstType || (ProviderAstType = {}));
  10026. /**
  10027. * Position where content is to be projected (instance of `<ng-content>` in a template).
  10028. */
  10029. class NgContentAst {
  10030. constructor(index, ngContentIndex, sourceSpan) {
  10031. this.index = index;
  10032. this.ngContentIndex = ngContentIndex;
  10033. this.sourceSpan = sourceSpan;
  10034. }
  10035. visit(visitor, context) {
  10036. return visitor.visitNgContent(this, context);
  10037. }
  10038. }
  10039. /**
  10040. * A visitor that accepts each node but doesn't do anything. It is intended to be used
  10041. * as the base class for a visitor that is only interested in a subset of the node types.
  10042. */
  10043. class NullTemplateVisitor {
  10044. visitNgContent(ast, context) { }
  10045. visitEmbeddedTemplate(ast, context) { }
  10046. visitElement(ast, context) { }
  10047. visitReference(ast, context) { }
  10048. visitVariable(ast, context) { }
  10049. visitEvent(ast, context) { }
  10050. visitElementProperty(ast, context) { }
  10051. visitAttr(ast, context) { }
  10052. visitBoundText(ast, context) { }
  10053. visitText(ast, context) { }
  10054. visitDirective(ast, context) { }
  10055. visitDirectiveProperty(ast, context) { }
  10056. }
  10057. /**
  10058. * Base class that can be used to build a visitor that visits each node
  10059. * in an template ast recursively.
  10060. */
  10061. class RecursiveTemplateAstVisitor extends NullTemplateVisitor {
  10062. constructor() { super(); }
  10063. // Nodes with children
  10064. visitEmbeddedTemplate(ast, context) {
  10065. return this.visitChildren(context, visit => {
  10066. visit(ast.attrs);
  10067. visit(ast.references);
  10068. visit(ast.variables);
  10069. visit(ast.directives);
  10070. visit(ast.providers);
  10071. visit(ast.children);
  10072. });
  10073. }
  10074. visitElement(ast, context) {
  10075. return this.visitChildren(context, visit => {
  10076. visit(ast.attrs);
  10077. visit(ast.inputs);
  10078. visit(ast.outputs);
  10079. visit(ast.references);
  10080. visit(ast.directives);
  10081. visit(ast.providers);
  10082. visit(ast.children);
  10083. });
  10084. }
  10085. visitDirective(ast, context) {
  10086. return this.visitChildren(context, visit => {
  10087. visit(ast.inputs);
  10088. visit(ast.hostProperties);
  10089. visit(ast.hostEvents);
  10090. });
  10091. }
  10092. visitChildren(context, cb) {
  10093. let results = [];
  10094. let t = this;
  10095. function visit(children) {
  10096. if (children && children.length)
  10097. results.push(templateVisitAll(t, children, context));
  10098. }
  10099. cb(visit);
  10100. return [].concat.apply([], results);
  10101. }
  10102. }
  10103. /**
  10104. * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
  10105. */
  10106. function templateVisitAll(visitor, asts, context = null) {
  10107. const result = [];
  10108. const visit = visitor.visit ?
  10109. (ast) => visitor.visit(ast, context) || ast.visit(visitor, context) :
  10110. (ast) => ast.visit(visitor, context);
  10111. asts.forEach(ast => {
  10112. const astResult = visit(ast);
  10113. if (astResult) {
  10114. result.push(astResult);
  10115. }
  10116. });
  10117. return result;
  10118. }
  10119. /**
  10120. * @license
  10121. * Copyright Google Inc. All Rights Reserved.
  10122. *
  10123. * Use of this source code is governed by an MIT-style license that can be
  10124. * found in the LICENSE file at https://angular.io/license
  10125. */
  10126. class ProviderError extends ParseError {
  10127. constructor(message, span) { super(span, message); }
  10128. }
  10129. class ProviderViewContext {
  10130. constructor(reflector, component) {
  10131. this.reflector = reflector;
  10132. this.component = component;
  10133. this.errors = [];
  10134. this.viewQueries = _getViewQueries(component);
  10135. this.viewProviders = new Map();
  10136. component.viewProviders.forEach((provider) => {
  10137. if (this.viewProviders.get(tokenReference(provider.token)) == null) {
  10138. this.viewProviders.set(tokenReference(provider.token), true);
  10139. }
  10140. });
  10141. }
  10142. }
  10143. class ProviderElementContext {
  10144. constructor(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
  10145. this.viewContext = viewContext;
  10146. this._parent = _parent;
  10147. this._isViewRoot = _isViewRoot;
  10148. this._directiveAsts = _directiveAsts;
  10149. this._sourceSpan = _sourceSpan;
  10150. this._transformedProviders = new Map();
  10151. this._seenProviders = new Map();
  10152. this._queriedTokens = new Map();
  10153. this.transformedHasViewContainer = false;
  10154. this._attrs = {};
  10155. attrs.forEach((attrAst) => this._attrs[attrAst.name] = attrAst.value);
  10156. const directivesMeta = _directiveAsts.map(directiveAst => directiveAst.directive);
  10157. this._allProviders =
  10158. _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
  10159. this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
  10160. Array.from(this._allProviders.values()).forEach((provider) => {
  10161. this._addQueryReadsTo(provider.token, provider.token, this._queriedTokens);
  10162. });
  10163. if (isTemplate) {
  10164. const templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
  10165. this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
  10166. }
  10167. refs.forEach((refAst) => {
  10168. let defaultQueryValue = refAst.value ||
  10169. createTokenForExternalReference(this.viewContext.reflector, Identifiers.ElementRef);
  10170. this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, this._queriedTokens);
  10171. });
  10172. if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {
  10173. this.transformedHasViewContainer = true;
  10174. }
  10175. // create the providers that we know are eager first
  10176. Array.from(this._allProviders.values()).forEach((provider) => {
  10177. const eager = provider.eager || this._queriedTokens.get(tokenReference(provider.token));
  10178. if (eager) {
  10179. this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
  10180. }
  10181. });
  10182. }
  10183. afterElement() {
  10184. // collect lazy providers
  10185. Array.from(this._allProviders.values()).forEach((provider) => {
  10186. this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
  10187. });
  10188. }
  10189. get transformProviders() {
  10190. // Note: Maps keep their insertion order.
  10191. const lazyProviders = [];
  10192. const eagerProviders = [];
  10193. this._transformedProviders.forEach(provider => {
  10194. if (provider.eager) {
  10195. eagerProviders.push(provider);
  10196. }
  10197. else {
  10198. lazyProviders.push(provider);
  10199. }
  10200. });
  10201. return lazyProviders.concat(eagerProviders);
  10202. }
  10203. get transformedDirectiveAsts() {
  10204. const sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);
  10205. const sortedDirectives = this._directiveAsts.slice();
  10206. sortedDirectives.sort((dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -
  10207. sortedProviderTypes.indexOf(dir2.directive.type));
  10208. return sortedDirectives;
  10209. }
  10210. get queryMatches() {
  10211. const allMatches = [];
  10212. this._queriedTokens.forEach((matches) => { allMatches.push(...matches); });
  10213. return allMatches;
  10214. }
  10215. _addQueryReadsTo(token, defaultValue, queryReadTokens) {
  10216. this._getQueriesFor(token).forEach((query) => {
  10217. const queryValue = query.meta.read || defaultValue;
  10218. const tokenRef = tokenReference(queryValue);
  10219. let queryMatches = queryReadTokens.get(tokenRef);
  10220. if (!queryMatches) {
  10221. queryMatches = [];
  10222. queryReadTokens.set(tokenRef, queryMatches);
  10223. }
  10224. queryMatches.push({ queryId: query.queryId, value: queryValue });
  10225. });
  10226. }
  10227. _getQueriesFor(token) {
  10228. const result = [];
  10229. let currentEl = this;
  10230. let distance = 0;
  10231. let queries;
  10232. while (currentEl !== null) {
  10233. queries = currentEl._contentQueries.get(tokenReference(token));
  10234. if (queries) {
  10235. result.push(...queries.filter((query) => query.meta.descendants || distance <= 1));
  10236. }
  10237. if (currentEl._directiveAsts.length > 0) {
  10238. distance++;
  10239. }
  10240. currentEl = currentEl._parent;
  10241. }
  10242. queries = this.viewContext.viewQueries.get(tokenReference(token));
  10243. if (queries) {
  10244. result.push(...queries);
  10245. }
  10246. return result;
  10247. }
  10248. _getOrCreateLocalProvider(requestingProviderType, token, eager) {
  10249. const resolvedProvider = this._allProviders.get(tokenReference(token));
  10250. if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
  10251. requestingProviderType === ProviderAstType.PublicService) &&
  10252. resolvedProvider.providerType === ProviderAstType.PrivateService) ||
  10253. ((requestingProviderType === ProviderAstType.PrivateService ||
  10254. requestingProviderType === ProviderAstType.PublicService) &&
  10255. resolvedProvider.providerType === ProviderAstType.Builtin)) {
  10256. return null;
  10257. }
  10258. let transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  10259. if (transformedProviderAst) {
  10260. return transformedProviderAst;
  10261. }
  10262. if (this._seenProviders.get(tokenReference(token)) != null) {
  10263. this.viewContext.errors.push(new ProviderError(`Cannot instantiate cyclic dependency! ${tokenName(token)}`, this._sourceSpan));
  10264. return null;
  10265. }
  10266. this._seenProviders.set(tokenReference(token), true);
  10267. const transformedProviders = resolvedProvider.providers.map((provider) => {
  10268. let transformedUseValue = provider.useValue;
  10269. let transformedUseExisting = provider.useExisting;
  10270. let transformedDeps = undefined;
  10271. if (provider.useExisting != null) {
  10272. const existingDiDep = this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
  10273. if (existingDiDep.token != null) {
  10274. transformedUseExisting = existingDiDep.token;
  10275. }
  10276. else {
  10277. transformedUseExisting = null;
  10278. transformedUseValue = existingDiDep.value;
  10279. }
  10280. }
  10281. else if (provider.useFactory) {
  10282. const deps = provider.deps || provider.useFactory.diDeps;
  10283. transformedDeps =
  10284. deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager));
  10285. }
  10286. else if (provider.useClass) {
  10287. const deps = provider.deps || provider.useClass.diDeps;
  10288. transformedDeps =
  10289. deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager));
  10290. }
  10291. return _transformProvider(provider, {
  10292. useExisting: transformedUseExisting,
  10293. useValue: transformedUseValue,
  10294. deps: transformedDeps
  10295. });
  10296. });
  10297. transformedProviderAst =
  10298. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  10299. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  10300. return transformedProviderAst;
  10301. }
  10302. _getLocalDependency(requestingProviderType, dep, eager = false) {
  10303. if (dep.isAttribute) {
  10304. const attrValue = this._attrs[dep.token.value];
  10305. return { isValue: true, value: attrValue == null ? null : attrValue };
  10306. }
  10307. if (dep.token != null) {
  10308. // access builtints
  10309. if ((requestingProviderType === ProviderAstType.Directive ||
  10310. requestingProviderType === ProviderAstType.Component)) {
  10311. if (tokenReference(dep.token) ===
  10312. this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||
  10313. tokenReference(dep.token) ===
  10314. this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||
  10315. tokenReference(dep.token) ===
  10316. this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) ||
  10317. tokenReference(dep.token) ===
  10318. this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  10319. return dep;
  10320. }
  10321. if (tokenReference(dep.token) ===
  10322. this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  10323. this.transformedHasViewContainer = true;
  10324. }
  10325. }
  10326. // access the injector
  10327. if (tokenReference(dep.token) ===
  10328. this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {
  10329. return dep;
  10330. }
  10331. // access providers
  10332. if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
  10333. return dep;
  10334. }
  10335. }
  10336. return null;
  10337. }
  10338. _getDependency(requestingProviderType, dep, eager = false) {
  10339. let currElement = this;
  10340. let currEager = eager;
  10341. let result = null;
  10342. if (!dep.isSkipSelf) {
  10343. result = this._getLocalDependency(requestingProviderType, dep, eager);
  10344. }
  10345. if (dep.isSelf) {
  10346. if (!result && dep.isOptional) {
  10347. result = { isValue: true, value: null };
  10348. }
  10349. }
  10350. else {
  10351. // check parent elements
  10352. while (!result && currElement._parent) {
  10353. const prevElement = currElement;
  10354. currElement = currElement._parent;
  10355. if (prevElement._isViewRoot) {
  10356. currEager = false;
  10357. }
  10358. result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);
  10359. }
  10360. // check @Host restriction
  10361. if (!result) {
  10362. if (!dep.isHost || this.viewContext.component.isHost ||
  10363. this.viewContext.component.type.reference === tokenReference(dep.token) ||
  10364. this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
  10365. result = dep;
  10366. }
  10367. else {
  10368. result = dep.isOptional ? { isValue: true, value: null } : null;
  10369. }
  10370. }
  10371. }
  10372. if (!result) {
  10373. this.viewContext.errors.push(new ProviderError(`No provider for ${tokenName(dep.token)}`, this._sourceSpan));
  10374. }
  10375. return result;
  10376. }
  10377. }
  10378. class NgModuleProviderAnalyzer {
  10379. constructor(reflector, ngModule, extraProviders, sourceSpan) {
  10380. this.reflector = reflector;
  10381. this._transformedProviders = new Map();
  10382. this._seenProviders = new Map();
  10383. this._errors = [];
  10384. this._allProviders = new Map();
  10385. ngModule.transitiveModule.modules.forEach((ngModuleType) => {
  10386. const ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
  10387. _resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, this._errors, this._allProviders, /* isModule */ true);
  10388. });
  10389. _resolveProviders(ngModule.transitiveModule.providers.map(entry => entry.provider).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
  10390. /* isModule */ false);
  10391. }
  10392. parse() {
  10393. Array.from(this._allProviders.values()).forEach((provider) => {
  10394. this._getOrCreateLocalProvider(provider.token, provider.eager);
  10395. });
  10396. if (this._errors.length > 0) {
  10397. const errorString = this._errors.join('\n');
  10398. throw new Error(`Provider parse errors:\n${errorString}`);
  10399. }
  10400. // Note: Maps keep their insertion order.
  10401. const lazyProviders = [];
  10402. const eagerProviders = [];
  10403. this._transformedProviders.forEach(provider => {
  10404. if (provider.eager) {
  10405. eagerProviders.push(provider);
  10406. }
  10407. else {
  10408. lazyProviders.push(provider);
  10409. }
  10410. });
  10411. return lazyProviders.concat(eagerProviders);
  10412. }
  10413. _getOrCreateLocalProvider(token, eager) {
  10414. const resolvedProvider = this._allProviders.get(tokenReference(token));
  10415. if (!resolvedProvider) {
  10416. return null;
  10417. }
  10418. let transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  10419. if (transformedProviderAst) {
  10420. return transformedProviderAst;
  10421. }
  10422. if (this._seenProviders.get(tokenReference(token)) != null) {
  10423. this._errors.push(new ProviderError(`Cannot instantiate cyclic dependency! ${tokenName(token)}`, resolvedProvider.sourceSpan));
  10424. return null;
  10425. }
  10426. this._seenProviders.set(tokenReference(token), true);
  10427. const transformedProviders = resolvedProvider.providers.map((provider) => {
  10428. let transformedUseValue = provider.useValue;
  10429. let transformedUseExisting = provider.useExisting;
  10430. let transformedDeps = undefined;
  10431. if (provider.useExisting != null) {
  10432. const existingDiDep = this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
  10433. if (existingDiDep.token != null) {
  10434. transformedUseExisting = existingDiDep.token;
  10435. }
  10436. else {
  10437. transformedUseExisting = null;
  10438. transformedUseValue = existingDiDep.value;
  10439. }
  10440. }
  10441. else if (provider.useFactory) {
  10442. const deps = provider.deps || provider.useFactory.diDeps;
  10443. transformedDeps =
  10444. deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));
  10445. }
  10446. else if (provider.useClass) {
  10447. const deps = provider.deps || provider.useClass.diDeps;
  10448. transformedDeps =
  10449. deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));
  10450. }
  10451. return _transformProvider(provider, {
  10452. useExisting: transformedUseExisting,
  10453. useValue: transformedUseValue,
  10454. deps: transformedDeps
  10455. });
  10456. });
  10457. transformedProviderAst =
  10458. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  10459. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  10460. return transformedProviderAst;
  10461. }
  10462. _getDependency(dep, eager = false, requestorSourceSpan) {
  10463. if (!dep.isSkipSelf && dep.token != null) {
  10464. // access the injector
  10465. if (tokenReference(dep.token) ===
  10466. this.reflector.resolveExternalReference(Identifiers.Injector) ||
  10467. tokenReference(dep.token) ===
  10468. this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) ;
  10469. else if (this._getOrCreateLocalProvider(dep.token, eager) != null) ;
  10470. }
  10471. return dep;
  10472. }
  10473. }
  10474. function _transformProvider(provider, { useExisting, useValue, deps }) {
  10475. return {
  10476. token: provider.token,
  10477. useClass: provider.useClass,
  10478. useExisting: useExisting,
  10479. useFactory: provider.useFactory,
  10480. useValue: useValue,
  10481. deps: deps,
  10482. multi: provider.multi
  10483. };
  10484. }
  10485. function _transformProviderAst(provider, { eager, providers }) {
  10486. return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
  10487. }
  10488. function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
  10489. const providersByToken = new Map();
  10490. directives.forEach((directive) => {
  10491. const dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
  10492. _resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  10493. });
  10494. // Note: directives need to be able to overwrite providers of a component!
  10495. const directivesWithComponentFirst = directives.filter(dir => dir.isComponent).concat(directives.filter(dir => !dir.isComponent));
  10496. directivesWithComponentFirst.forEach((directive) => {
  10497. _resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  10498. _resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  10499. });
  10500. return providersByToken;
  10501. }
  10502. function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
  10503. providers.forEach((provider) => {
  10504. let resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
  10505. if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
  10506. targetErrors.push(new ProviderError(`Mixing multi and non multi provider is not possible for token ${tokenName(resolvedProvider.token)}`, sourceSpan));
  10507. }
  10508. if (!resolvedProvider) {
  10509. const lifecycleHooks = provider.token.identifier &&
  10510. provider.token.identifier.lifecycleHooks ?
  10511. provider.token.identifier.lifecycleHooks :
  10512. [];
  10513. const isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
  10514. resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
  10515. targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
  10516. }
  10517. else {
  10518. if (!provider.multi) {
  10519. resolvedProvider.providers.length = 0;
  10520. }
  10521. resolvedProvider.providers.push(provider);
  10522. }
  10523. });
  10524. }
  10525. function _getViewQueries(component) {
  10526. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  10527. let viewQueryId = 1;
  10528. const viewQueries = new Map();
  10529. if (component.viewQueries) {
  10530. component.viewQueries.forEach((query) => _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }));
  10531. }
  10532. return viewQueries;
  10533. }
  10534. function _getContentQueries(contentQueryStartId, directives) {
  10535. let contentQueryId = contentQueryStartId;
  10536. const contentQueries = new Map();
  10537. directives.forEach((directive, directiveIndex) => {
  10538. if (directive.queries) {
  10539. directive.queries.forEach((query) => _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }));
  10540. }
  10541. });
  10542. return contentQueries;
  10543. }
  10544. function _addQueryToTokenMap(map, query) {
  10545. query.meta.selectors.forEach((token) => {
  10546. let entry = map.get(tokenReference(token));
  10547. if (!entry) {
  10548. entry = [];
  10549. map.set(tokenReference(token), entry);
  10550. }
  10551. entry.push(query);
  10552. });
  10553. }
  10554. /**
  10555. * @license
  10556. * Copyright Google Inc. All Rights Reserved.
  10557. *
  10558. * Use of this source code is governed by an MIT-style license that can be
  10559. * found in the LICENSE file at https://angular.io/license
  10560. */
  10561. class StyleWithImports {
  10562. constructor(style, styleUrls) {
  10563. this.style = style;
  10564. this.styleUrls = styleUrls;
  10565. }
  10566. }
  10567. function isStyleUrlResolvable(url) {
  10568. if (url == null || url.length === 0 || url[0] == '/')
  10569. return false;
  10570. const schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
  10571. return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
  10572. }
  10573. /**
  10574. * Rewrites stylesheets by resolving and removing the @import urls that
  10575. * are either relative or don't have a `package:` scheme
  10576. */
  10577. function extractStyleUrls(resolver, baseUrl, cssText) {
  10578. const foundUrls = [];
  10579. const modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
  10580. .replace(CSS_IMPORT_REGEXP, (...m) => {
  10581. const url = m[1] || m[2];
  10582. if (!isStyleUrlResolvable(url)) {
  10583. // Do not attempt to resolve non-package absolute URLs with URI
  10584. // scheme
  10585. return m[0];
  10586. }
  10587. foundUrls.push(resolver.resolve(baseUrl, url));
  10588. return '';
  10589. });
  10590. return new StyleWithImports(modifiedCssText, foundUrls);
  10591. }
  10592. const CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
  10593. const CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
  10594. const URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
  10595. /**
  10596. * @license
  10597. * Copyright Google Inc. All Rights Reserved.
  10598. *
  10599. * Use of this source code is governed by an MIT-style license that can be
  10600. * found in the LICENSE file at https://angular.io/license
  10601. */
  10602. const PROPERTY_PARTS_SEPARATOR = '.';
  10603. const ATTRIBUTE_PREFIX = 'attr';
  10604. const CLASS_PREFIX = 'class';
  10605. const STYLE_PREFIX = 'style';
  10606. const ANIMATE_PROP_PREFIX = 'animate-';
  10607. /**
  10608. * Parses bindings in templates and in the directive host area.
  10609. */
  10610. class BindingParser {
  10611. constructor(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
  10612. this._exprParser = _exprParser;
  10613. this._interpolationConfig = _interpolationConfig;
  10614. this._schemaRegistry = _schemaRegistry;
  10615. this.errors = errors;
  10616. this.pipesByName = null;
  10617. this._usedPipes = new Map();
  10618. // When the `pipes` parameter is `null`, do not check for used pipes
  10619. // This is used in IVY when we might not know the available pipes at compile time
  10620. if (pipes) {
  10621. const pipesByName = new Map();
  10622. pipes.forEach(pipe => pipesByName.set(pipe.name, pipe));
  10623. this.pipesByName = pipesByName;
  10624. }
  10625. }
  10626. get interpolationConfig() { return this._interpolationConfig; }
  10627. getUsedPipes() { return Array.from(this._usedPipes.values()); }
  10628. createBoundHostProperties(dirMeta, sourceSpan) {
  10629. if (dirMeta.hostProperties) {
  10630. const boundProps = [];
  10631. Object.keys(dirMeta.hostProperties).forEach(propName => {
  10632. const expression = dirMeta.hostProperties[propName];
  10633. if (typeof expression === 'string') {
  10634. this.parsePropertyBinding(propName, expression, true, sourceSpan, [], boundProps);
  10635. }
  10636. else {
  10637. this._reportError(`Value of the host property binding "${propName}" needs to be a string representing an expression but got "${expression}" (${typeof expression})`, sourceSpan);
  10638. }
  10639. });
  10640. return boundProps;
  10641. }
  10642. return null;
  10643. }
  10644. createDirectiveHostPropertyAsts(dirMeta, elementSelector, sourceSpan) {
  10645. const boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
  10646. return boundProps &&
  10647. boundProps.map((prop) => this.createBoundElementProperty(elementSelector, prop));
  10648. }
  10649. createDirectiveHostEventAsts(dirMeta, sourceSpan) {
  10650. if (dirMeta.hostListeners) {
  10651. const targetEvents = [];
  10652. Object.keys(dirMeta.hostListeners).forEach(propName => {
  10653. const expression = dirMeta.hostListeners[propName];
  10654. if (typeof expression === 'string') {
  10655. // TODO: pass a more accurate handlerSpan for this event.
  10656. this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents);
  10657. }
  10658. else {
  10659. this._reportError(`Value of the host listener "${propName}" needs to be a string representing an expression but got "${expression}" (${typeof expression})`, sourceSpan);
  10660. }
  10661. });
  10662. return targetEvents;
  10663. }
  10664. return null;
  10665. }
  10666. parseInterpolation(value, sourceSpan) {
  10667. const sourceInfo = sourceSpan.start.toString();
  10668. try {
  10669. const ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig);
  10670. if (ast)
  10671. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  10672. this._checkPipes(ast, sourceSpan);
  10673. return ast;
  10674. }
  10675. catch (e) {
  10676. this._reportError(`${e}`, sourceSpan);
  10677. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  10678. }
  10679. }
  10680. // Parse an inline template binding. ie `<tag *tplKey="<tplValue>">`
  10681. parseInlineTemplateBinding(tplKey, tplValue, sourceSpan, targetMatchableAttrs, targetProps, targetVars) {
  10682. const bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan);
  10683. for (let i = 0; i < bindings.length; i++) {
  10684. const binding = bindings[i];
  10685. if (binding.keyIsVar) {
  10686. targetVars.push(new ParsedVariable(binding.key, binding.name, sourceSpan));
  10687. }
  10688. else if (binding.expression) {
  10689. this._parsePropertyAst(binding.key, binding.expression, sourceSpan, targetMatchableAttrs, targetProps);
  10690. }
  10691. else {
  10692. targetMatchableAttrs.push([binding.key, '']);
  10693. this.parseLiteralAttr(binding.key, null, sourceSpan, targetMatchableAttrs, targetProps);
  10694. }
  10695. }
  10696. }
  10697. _parseTemplateBindings(tplKey, tplValue, sourceSpan) {
  10698. const sourceInfo = sourceSpan.start.toString();
  10699. try {
  10700. const bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo);
  10701. this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
  10702. bindingsResult.templateBindings.forEach((binding) => {
  10703. if (binding.expression) {
  10704. this._checkPipes(binding.expression, sourceSpan);
  10705. }
  10706. });
  10707. bindingsResult.warnings.forEach((warning) => { this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); });
  10708. return bindingsResult.templateBindings;
  10709. }
  10710. catch (e) {
  10711. this._reportError(`${e}`, sourceSpan);
  10712. return [];
  10713. }
  10714. }
  10715. parseLiteralAttr(name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  10716. if (isAnimationLabel(name)) {
  10717. name = name.substring(1);
  10718. if (value) {
  10719. this._reportError(`Assigning animation triggers via @prop="exp" attributes with an expression is invalid.` +
  10720. ` Use property bindings (e.g. [@prop]="exp") or use an attribute without a value (e.g. @prop) instead.`, sourceSpan, ParseErrorLevel.ERROR);
  10721. }
  10722. this._parseAnimation(name, value, sourceSpan, targetMatchableAttrs, targetProps);
  10723. }
  10724. else {
  10725. targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), ParsedPropertyType.LITERAL_ATTR, sourceSpan));
  10726. }
  10727. }
  10728. parsePropertyBinding(name, expression, isHost, sourceSpan, targetMatchableAttrs, targetProps) {
  10729. let isAnimationProp = false;
  10730. if (name.startsWith(ANIMATE_PROP_PREFIX)) {
  10731. isAnimationProp = true;
  10732. name = name.substring(ANIMATE_PROP_PREFIX.length);
  10733. }
  10734. else if (isAnimationLabel(name)) {
  10735. isAnimationProp = true;
  10736. name = name.substring(1);
  10737. }
  10738. if (isAnimationProp) {
  10739. this._parseAnimation(name, expression, sourceSpan, targetMatchableAttrs, targetProps);
  10740. }
  10741. else {
  10742. this._parsePropertyAst(name, this._parseBinding(expression, isHost, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps);
  10743. }
  10744. }
  10745. parsePropertyInterpolation(name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  10746. const expr = this.parseInterpolation(value, sourceSpan);
  10747. if (expr) {
  10748. this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
  10749. return true;
  10750. }
  10751. return false;
  10752. }
  10753. _parsePropertyAst(name, ast, sourceSpan, targetMatchableAttrs, targetProps) {
  10754. targetMatchableAttrs.push([name, ast.source]);
  10755. targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.DEFAULT, sourceSpan));
  10756. }
  10757. _parseAnimation(name, expression, sourceSpan, targetMatchableAttrs, targetProps) {
  10758. // This will occur when a @trigger is not paired with an expression.
  10759. // For animations it is valid to not have an expression since */void
  10760. // states will be applied by angular when the element is attached/detached
  10761. const ast = this._parseBinding(expression || 'undefined', false, sourceSpan);
  10762. targetMatchableAttrs.push([name, ast.source]);
  10763. targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan));
  10764. }
  10765. _parseBinding(value, isHostBinding, sourceSpan) {
  10766. const sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
  10767. try {
  10768. const ast = isHostBinding ?
  10769. this._exprParser.parseSimpleBinding(value, sourceInfo, this._interpolationConfig) :
  10770. this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig);
  10771. if (ast)
  10772. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  10773. this._checkPipes(ast, sourceSpan);
  10774. return ast;
  10775. }
  10776. catch (e) {
  10777. this._reportError(`${e}`, sourceSpan);
  10778. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  10779. }
  10780. }
  10781. createBoundElementProperty(elementSelector, boundProp, skipValidation = false, mapPropertyName = true) {
  10782. if (boundProp.isAnimation) {
  10783. return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan);
  10784. }
  10785. let unit = null;
  10786. let bindingType = undefined;
  10787. let boundPropertyName = null;
  10788. const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  10789. let securityContexts = undefined;
  10790. // Check for special cases (prefix style, attr, class)
  10791. if (parts.length > 1) {
  10792. if (parts[0] == ATTRIBUTE_PREFIX) {
  10793. boundPropertyName = parts[1];
  10794. if (!skipValidation) {
  10795. this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
  10796. }
  10797. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
  10798. const nsSeparatorIdx = boundPropertyName.indexOf(':');
  10799. if (nsSeparatorIdx > -1) {
  10800. const ns = boundPropertyName.substring(0, nsSeparatorIdx);
  10801. const name = boundPropertyName.substring(nsSeparatorIdx + 1);
  10802. boundPropertyName = mergeNsAndName(ns, name);
  10803. }
  10804. bindingType = 1 /* Attribute */;
  10805. }
  10806. else if (parts[0] == CLASS_PREFIX) {
  10807. boundPropertyName = parts[1];
  10808. bindingType = 2 /* Class */;
  10809. securityContexts = [SecurityContext.NONE];
  10810. }
  10811. else if (parts[0] == STYLE_PREFIX) {
  10812. unit = parts.length > 2 ? parts[2] : null;
  10813. boundPropertyName = parts[1];
  10814. bindingType = 3 /* Style */;
  10815. securityContexts = [SecurityContext.STYLE];
  10816. }
  10817. }
  10818. // If not a special case, use the full property name
  10819. if (boundPropertyName === null) {
  10820. const mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
  10821. boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
  10822. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
  10823. bindingType = 0 /* Property */;
  10824. if (!skipValidation) {
  10825. this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
  10826. }
  10827. }
  10828. return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan);
  10829. }
  10830. parseEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  10831. if (isAnimationLabel(name)) {
  10832. name = name.substr(1);
  10833. this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents);
  10834. }
  10835. else {
  10836. this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents);
  10837. }
  10838. }
  10839. calcPossibleSecurityContexts(selector, propName, isAttribute) {
  10840. const prop = this._schemaRegistry.getMappedPropName(propName);
  10841. return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
  10842. }
  10843. _parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents) {
  10844. const matches = splitAtPeriod(name, [name, '']);
  10845. const eventName = matches[0];
  10846. const phase = matches[1].toLowerCase();
  10847. if (phase) {
  10848. switch (phase) {
  10849. case 'start':
  10850. case 'done':
  10851. const ast = this._parseAction(expression, handlerSpan);
  10852. targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan));
  10853. break;
  10854. default:
  10855. this._reportError(`The provided animation output phase value "${phase}" for "@${eventName}" is not supported (use start or done)`, sourceSpan);
  10856. break;
  10857. }
  10858. }
  10859. else {
  10860. this._reportError(`The animation trigger output event (@${eventName}) is missing its phase value name (start or done are currently supported)`, sourceSpan);
  10861. }
  10862. }
  10863. _parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  10864. // long format: 'target: eventName'
  10865. const [target, eventName] = splitAtColon(name, [null, name]);
  10866. const ast = this._parseAction(expression, handlerSpan);
  10867. targetMatchableAttrs.push([name, ast.source]);
  10868. targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan));
  10869. // Don't detect directives for event names for now,
  10870. // so don't add the event name to the matchableAttrs
  10871. }
  10872. _parseAction(value, sourceSpan) {
  10873. const sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
  10874. try {
  10875. const ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig);
  10876. if (ast) {
  10877. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  10878. }
  10879. if (!ast || ast.ast instanceof EmptyExpr) {
  10880. this._reportError(`Empty expressions are not allowed`, sourceSpan);
  10881. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  10882. }
  10883. this._checkPipes(ast, sourceSpan);
  10884. return ast;
  10885. }
  10886. catch (e) {
  10887. this._reportError(`${e}`, sourceSpan);
  10888. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  10889. }
  10890. }
  10891. _reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
  10892. this.errors.push(new ParseError(sourceSpan, message, level));
  10893. }
  10894. _reportExpressionParserErrors(errors, sourceSpan) {
  10895. for (const error of errors) {
  10896. this._reportError(error.message, sourceSpan);
  10897. }
  10898. }
  10899. // Make sure all the used pipes are known in `this.pipesByName`
  10900. _checkPipes(ast, sourceSpan) {
  10901. if (ast && this.pipesByName) {
  10902. const collector = new PipeCollector();
  10903. ast.visit(collector);
  10904. collector.pipes.forEach((ast, pipeName) => {
  10905. const pipeMeta = this.pipesByName.get(pipeName);
  10906. if (!pipeMeta) {
  10907. this._reportError(`The pipe '${pipeName}' could not be found`, new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
  10908. }
  10909. else {
  10910. this._usedPipes.set(pipeName, pipeMeta);
  10911. }
  10912. });
  10913. }
  10914. }
  10915. /**
  10916. * @param propName the name of the property / attribute
  10917. * @param sourceSpan
  10918. * @param isAttr true when binding to an attribute
  10919. */
  10920. _validatePropertyOrAttributeName(propName, sourceSpan, isAttr) {
  10921. const report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
  10922. this._schemaRegistry.validateProperty(propName);
  10923. if (report.error) {
  10924. this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR);
  10925. }
  10926. }
  10927. }
  10928. class PipeCollector extends RecursiveAstVisitor$1 {
  10929. constructor() {
  10930. super(...arguments);
  10931. this.pipes = new Map();
  10932. }
  10933. visitPipe(ast, context) {
  10934. this.pipes.set(ast.name, ast);
  10935. ast.exp.visit(this);
  10936. this.visitAll(ast.args, context);
  10937. return null;
  10938. }
  10939. }
  10940. function isAnimationLabel(name) {
  10941. return name[0] == '@';
  10942. }
  10943. function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
  10944. const ctxs = [];
  10945. CssSelector.parse(selector).forEach((selector) => {
  10946. const elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
  10947. const notElementNames = new Set(selector.notSelectors.filter(selector => selector.isElementSelector())
  10948. .map((selector) => selector.element));
  10949. const possibleElementNames = elementNames.filter(elementName => !notElementNames.has(elementName));
  10950. ctxs.push(...possibleElementNames.map(elementName => registry.securityContext(elementName, propName, isAttribute)));
  10951. });
  10952. return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
  10953. }
  10954. /**
  10955. * @license
  10956. * Copyright Google Inc. All Rights Reserved.
  10957. *
  10958. * Use of this source code is governed by an MIT-style license that can be
  10959. * found in the LICENSE file at https://angular.io/license
  10960. */
  10961. const NG_CONTENT_SELECT_ATTR = 'select';
  10962. const LINK_ELEMENT = 'link';
  10963. const LINK_STYLE_REL_ATTR = 'rel';
  10964. const LINK_STYLE_HREF_ATTR = 'href';
  10965. const LINK_STYLE_REL_VALUE = 'stylesheet';
  10966. const STYLE_ELEMENT = 'style';
  10967. const SCRIPT_ELEMENT = 'script';
  10968. const NG_NON_BINDABLE_ATTR = 'ngNonBindable';
  10969. const NG_PROJECT_AS = 'ngProjectAs';
  10970. function preparseElement(ast) {
  10971. let selectAttr = null;
  10972. let hrefAttr = null;
  10973. let relAttr = null;
  10974. let nonBindable = false;
  10975. let projectAs = '';
  10976. ast.attrs.forEach(attr => {
  10977. const lcAttrName = attr.name.toLowerCase();
  10978. if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
  10979. selectAttr = attr.value;
  10980. }
  10981. else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
  10982. hrefAttr = attr.value;
  10983. }
  10984. else if (lcAttrName == LINK_STYLE_REL_ATTR) {
  10985. relAttr = attr.value;
  10986. }
  10987. else if (attr.name == NG_NON_BINDABLE_ATTR) {
  10988. nonBindable = true;
  10989. }
  10990. else if (attr.name == NG_PROJECT_AS) {
  10991. if (attr.value.length > 0) {
  10992. projectAs = attr.value;
  10993. }
  10994. }
  10995. });
  10996. selectAttr = normalizeNgContentSelect(selectAttr);
  10997. const nodeName = ast.name.toLowerCase();
  10998. let type = PreparsedElementType.OTHER;
  10999. if (isNgContent(nodeName)) {
  11000. type = PreparsedElementType.NG_CONTENT;
  11001. }
  11002. else if (nodeName == STYLE_ELEMENT) {
  11003. type = PreparsedElementType.STYLE;
  11004. }
  11005. else if (nodeName == SCRIPT_ELEMENT) {
  11006. type = PreparsedElementType.SCRIPT;
  11007. }
  11008. else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
  11009. type = PreparsedElementType.STYLESHEET;
  11010. }
  11011. return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
  11012. }
  11013. var PreparsedElementType;
  11014. (function (PreparsedElementType) {
  11015. PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
  11016. PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
  11017. PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
  11018. PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
  11019. PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
  11020. })(PreparsedElementType || (PreparsedElementType = {}));
  11021. class PreparsedElement {
  11022. constructor(type, selectAttr, hrefAttr, nonBindable, projectAs) {
  11023. this.type = type;
  11024. this.selectAttr = selectAttr;
  11025. this.hrefAttr = hrefAttr;
  11026. this.nonBindable = nonBindable;
  11027. this.projectAs = projectAs;
  11028. }
  11029. }
  11030. function normalizeNgContentSelect(selectAttr) {
  11031. if (selectAttr === null || selectAttr.length === 0) {
  11032. return '*';
  11033. }
  11034. return selectAttr;
  11035. }
  11036. /**
  11037. * @license
  11038. * Copyright Google Inc. All Rights Reserved.
  11039. *
  11040. * Use of this source code is governed by an MIT-style license that can be
  11041. * found in the LICENSE file at https://angular.io/license
  11042. */
  11043. const BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  11044. // Group 1 = "bind-"
  11045. const KW_BIND_IDX = 1;
  11046. // Group 2 = "let-"
  11047. const KW_LET_IDX = 2;
  11048. // Group 3 = "ref-/#"
  11049. const KW_REF_IDX = 3;
  11050. // Group 4 = "on-"
  11051. const KW_ON_IDX = 4;
  11052. // Group 5 = "bindon-"
  11053. const KW_BINDON_IDX = 5;
  11054. // Group 6 = "@"
  11055. const KW_AT_IDX = 6;
  11056. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  11057. const IDENT_KW_IDX = 7;
  11058. // Group 8 = identifier inside [()]
  11059. const IDENT_BANANA_BOX_IDX = 8;
  11060. // Group 9 = identifier inside []
  11061. const IDENT_PROPERTY_IDX = 9;
  11062. // Group 10 = identifier inside ()
  11063. const IDENT_EVENT_IDX = 10;
  11064. const TEMPLATE_ATTR_PREFIX = '*';
  11065. const CLASS_ATTR = 'class';
  11066. let _TEXT_CSS_SELECTOR;
  11067. function TEXT_CSS_SELECTOR() {
  11068. if (!_TEXT_CSS_SELECTOR) {
  11069. _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
  11070. }
  11071. return _TEXT_CSS_SELECTOR;
  11072. }
  11073. class TemplateParseError extends ParseError {
  11074. constructor(message, span, level) {
  11075. super(span, message, level);
  11076. }
  11077. }
  11078. class TemplateParseResult {
  11079. constructor(templateAst, usedPipes, errors) {
  11080. this.templateAst = templateAst;
  11081. this.usedPipes = usedPipes;
  11082. this.errors = errors;
  11083. }
  11084. }
  11085. class TemplateParser {
  11086. constructor(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
  11087. this._config = _config;
  11088. this._reflector = _reflector;
  11089. this._exprParser = _exprParser;
  11090. this._schemaRegistry = _schemaRegistry;
  11091. this._htmlParser = _htmlParser;
  11092. this._console = _console;
  11093. this.transforms = transforms;
  11094. }
  11095. get expressionParser() { return this._exprParser; }
  11096. parse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11097. const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
  11098. const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING);
  11099. const errors = result.errors.filter(error => error.level === ParseErrorLevel.ERROR);
  11100. if (warnings.length > 0) {
  11101. this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`);
  11102. }
  11103. if (errors.length > 0) {
  11104. const errorString = errors.join('\n');
  11105. throw syntaxError(`Template parse errors:\n${errorString}`, errors);
  11106. }
  11107. return { template: result.templateAst, pipes: result.usedPipes };
  11108. }
  11109. tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11110. let htmlParseResult = typeof template === 'string' ?
  11111. this._htmlParser.parse(template, templateUrl, {
  11112. tokenizeExpansionForms: true,
  11113. interpolationConfig: this.getInterpolationConfig(component)
  11114. }) :
  11115. template;
  11116. if (!preserveWhitespaces) {
  11117. htmlParseResult = removeWhitespaces(htmlParseResult);
  11118. }
  11119. return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
  11120. }
  11121. tryParseHtml(htmlAstWithErrors, component, directives, pipes, schemas) {
  11122. let result;
  11123. const errors = htmlAstWithErrors.errors;
  11124. const usedPipes = [];
  11125. if (htmlAstWithErrors.rootNodes.length > 0) {
  11126. const uniqDirectives = removeSummaryDuplicates(directives);
  11127. const uniqPipes = removeSummaryDuplicates(pipes);
  11128. const providerViewContext = new ProviderViewContext(this._reflector, component);
  11129. let interpolationConfig = undefined;
  11130. if (component.template && component.template.interpolation) {
  11131. interpolationConfig = {
  11132. start: component.template.interpolation[0],
  11133. end: component.template.interpolation[1]
  11134. };
  11135. }
  11136. const bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
  11137. const parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
  11138. result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
  11139. errors.push(...providerViewContext.errors);
  11140. usedPipes.push(...bindingParser.getUsedPipes());
  11141. }
  11142. else {
  11143. result = [];
  11144. }
  11145. this._assertNoReferenceDuplicationOnTemplate(result, errors);
  11146. if (errors.length > 0) {
  11147. return new TemplateParseResult(result, usedPipes, errors);
  11148. }
  11149. if (this.transforms) {
  11150. this.transforms.forEach((transform) => { result = templateVisitAll(transform, result); });
  11151. }
  11152. return new TemplateParseResult(result, usedPipes, errors);
  11153. }
  11154. expandHtml(htmlAstWithErrors, forced = false) {
  11155. const errors = htmlAstWithErrors.errors;
  11156. if (errors.length == 0 || forced) {
  11157. // Transform ICU messages to angular directives
  11158. const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
  11159. errors.push(...expandedHtmlAst.errors);
  11160. htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
  11161. }
  11162. return htmlAstWithErrors;
  11163. }
  11164. getInterpolationConfig(component) {
  11165. if (component.template) {
  11166. return InterpolationConfig.fromArray(component.template.interpolation);
  11167. }
  11168. return undefined;
  11169. }
  11170. /** @internal */
  11171. _assertNoReferenceDuplicationOnTemplate(result, errors) {
  11172. const existingReferences = [];
  11173. result.filter(element => !!element.references)
  11174. .forEach(element => element.references.forEach((reference) => {
  11175. const name = reference.name;
  11176. if (existingReferences.indexOf(name) < 0) {
  11177. existingReferences.push(name);
  11178. }
  11179. else {
  11180. const error = new TemplateParseError(`Reference "#${name}" is defined several times`, reference.sourceSpan, ParseErrorLevel.ERROR);
  11181. errors.push(error);
  11182. }
  11183. }));
  11184. }
  11185. }
  11186. class TemplateParseVisitor {
  11187. constructor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
  11188. this.reflector = reflector;
  11189. this.config = config;
  11190. this.providerViewContext = providerViewContext;
  11191. this._bindingParser = _bindingParser;
  11192. this._schemaRegistry = _schemaRegistry;
  11193. this._schemas = _schemas;
  11194. this._targetErrors = _targetErrors;
  11195. this.selectorMatcher = new SelectorMatcher();
  11196. this.directivesIndex = new Map();
  11197. this.ngContentCount = 0;
  11198. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  11199. this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
  11200. directives.forEach((directive, index) => {
  11201. const selector = CssSelector.parse(directive.selector);
  11202. this.selectorMatcher.addSelectables(selector, directive);
  11203. this.directivesIndex.set(directive, index);
  11204. });
  11205. }
  11206. visitExpansion(expansion, context) { return null; }
  11207. visitExpansionCase(expansionCase, context) { return null; }
  11208. visitText(text, parent) {
  11209. const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  11210. const valueNoNgsp = replaceNgsp(text.value);
  11211. const expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
  11212. return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
  11213. new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
  11214. }
  11215. visitAttribute(attribute, context) {
  11216. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  11217. }
  11218. visitComment(comment, context) { return null; }
  11219. visitElement(element, parent) {
  11220. const queryStartIndex = this.contentQueryStartId;
  11221. const elName = element.name;
  11222. const preparsedElement = preparseElement(element);
  11223. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  11224. preparsedElement.type === PreparsedElementType.STYLE) {
  11225. // Skipping <script> for security reasons
  11226. // Skipping <style> as we already processed them
  11227. // in the StyleCompiler
  11228. return null;
  11229. }
  11230. if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  11231. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  11232. // Skipping stylesheets with either relative urls or package scheme as we already processed
  11233. // them in the StyleCompiler
  11234. return null;
  11235. }
  11236. const matchableAttrs = [];
  11237. const elementOrDirectiveProps = [];
  11238. const elementOrDirectiveRefs = [];
  11239. const elementVars = [];
  11240. const events = [];
  11241. const templateElementOrDirectiveProps = [];
  11242. const templateMatchableAttrs = [];
  11243. const templateElementVars = [];
  11244. let hasInlineTemplates = false;
  11245. const attrs = [];
  11246. const isTemplateElement = isNgTemplate(element.name);
  11247. element.attrs.forEach(attr => {
  11248. const parsedVariables = [];
  11249. const hasBinding = this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
  11250. elementVars.push(...parsedVariables.map(v => VariableAst.fromParsedVariable(v)));
  11251. let templateValue;
  11252. let templateKey;
  11253. const normalizedName = this._normalizeAttributeName(attr.name);
  11254. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
  11255. templateValue = attr.value;
  11256. templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
  11257. }
  11258. const hasTemplateBinding = templateValue != null;
  11259. if (hasTemplateBinding) {
  11260. if (hasInlineTemplates) {
  11261. this._reportError(`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`, attr.sourceSpan);
  11262. }
  11263. hasInlineTemplates = true;
  11264. const parsedVariables = [];
  11265. this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables);
  11266. templateElementVars.push(...parsedVariables.map(v => VariableAst.fromParsedVariable(v)));
  11267. }
  11268. if (!hasBinding && !hasTemplateBinding) {
  11269. // don't include the bindings as attributes as well in the AST
  11270. attrs.push(this.visitAttribute(attr, null));
  11271. matchableAttrs.push([attr.name, attr.value]);
  11272. }
  11273. });
  11274. const elementCssSelector = createElementCssSelector(elName, matchableAttrs);
  11275. const { directives: directiveMetas, matchElement } = this._parseDirectives(this.selectorMatcher, elementCssSelector);
  11276. const references = [];
  11277. const boundDirectivePropNames = new Set();
  11278. const directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
  11279. const elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
  11280. const isViewRoot = parent.isTemplateElement || hasInlineTemplates;
  11281. const providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
  11282. const children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
  11283. providerContext.afterElement();
  11284. // Override the actual selector when the `ngProjectAs` attribute is provided
  11285. const projectionSelector = preparsedElement.projectAs != '' ?
  11286. CssSelector.parse(preparsedElement.projectAs)[0] :
  11287. elementCssSelector;
  11288. const ngContentIndex = parent.findNgContentIndex(projectionSelector);
  11289. let parsedElement;
  11290. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  11291. // `<ng-content>` element
  11292. if (element.children && !element.children.every(_isEmptyTextNode)) {
  11293. this._reportError(`<ng-content> element cannot have content.`, element.sourceSpan);
  11294. }
  11295. parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  11296. }
  11297. else if (isTemplateElement) {
  11298. // `<ng-template>` element
  11299. this._assertAllEventsPublishedByDirectives(directiveAsts, events);
  11300. this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
  11301. parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  11302. }
  11303. else {
  11304. // element other than `<ng-content>` and `<ng-template>`
  11305. this._assertElementExists(matchElement, element);
  11306. this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
  11307. const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
  11308. parsedElement = new ElementAst(elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan, element.endSourceSpan || null);
  11309. }
  11310. if (hasInlineTemplates) {
  11311. // The element as a *-attribute
  11312. const templateQueryStartIndex = this.contentQueryStartId;
  11313. const templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
  11314. const { directives } = this._parseDirectives(this.selectorMatcher, templateSelector);
  11315. const templateBoundDirectivePropNames = new Set();
  11316. const templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
  11317. const templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
  11318. this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
  11319. const templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
  11320. templateProviderContext.afterElement();
  11321. parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
  11322. }
  11323. return parsedElement;
  11324. }
  11325. _parseAttr(isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
  11326. const name = this._normalizeAttributeName(attr.name);
  11327. const value = attr.value;
  11328. const srcSpan = attr.sourceSpan;
  11329. const boundEvents = [];
  11330. const bindParts = name.match(BIND_NAME_REGEXP);
  11331. let hasBinding = false;
  11332. if (bindParts !== null) {
  11333. hasBinding = true;
  11334. if (bindParts[KW_BIND_IDX] != null) {
  11335. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11336. }
  11337. else if (bindParts[KW_LET_IDX]) {
  11338. if (isTemplateElement) {
  11339. const identifier = bindParts[IDENT_KW_IDX];
  11340. this._parseVariable(identifier, value, srcSpan, targetVars);
  11341. }
  11342. else {
  11343. this._reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
  11344. }
  11345. }
  11346. else if (bindParts[KW_REF_IDX]) {
  11347. const identifier = bindParts[IDENT_KW_IDX];
  11348. this._parseReference(identifier, value, srcSpan, targetRefs);
  11349. }
  11350. else if (bindParts[KW_ON_IDX]) {
  11351. this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11352. }
  11353. else if (bindParts[KW_BINDON_IDX]) {
  11354. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11355. this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11356. }
  11357. else if (bindParts[KW_AT_IDX]) {
  11358. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  11359. }
  11360. else if (bindParts[IDENT_BANANA_BOX_IDX]) {
  11361. this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11362. this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11363. }
  11364. else if (bindParts[IDENT_PROPERTY_IDX]) {
  11365. this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  11366. }
  11367. else if (bindParts[IDENT_EVENT_IDX]) {
  11368. this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  11369. }
  11370. }
  11371. else {
  11372. hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, targetMatchableAttrs, targetProps);
  11373. }
  11374. if (!hasBinding) {
  11375. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  11376. }
  11377. targetEvents.push(...boundEvents.map(e => BoundEventAst.fromParsedEvent(e)));
  11378. return hasBinding;
  11379. }
  11380. _normalizeAttributeName(attrName) {
  11381. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  11382. }
  11383. _parseVariable(identifier, value, sourceSpan, targetVars) {
  11384. if (identifier.indexOf('-') > -1) {
  11385. this._reportError(`"-" is not allowed in variable names`, sourceSpan);
  11386. }
  11387. targetVars.push(new VariableAst(identifier, value, sourceSpan));
  11388. }
  11389. _parseReference(identifier, value, sourceSpan, targetRefs) {
  11390. if (identifier.indexOf('-') > -1) {
  11391. this._reportError(`"-" is not allowed in reference names`, sourceSpan);
  11392. }
  11393. targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
  11394. }
  11395. _parseAssignmentEvent(name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
  11396. this._bindingParser.parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
  11397. }
  11398. _parseDirectives(selectorMatcher, elementCssSelector) {
  11399. // Need to sort the directives so that we get consistent results throughout,
  11400. // as selectorMatcher uses Maps inside.
  11401. // Also deduplicate directives as they might match more than one time!
  11402. const directives = new Array(this.directivesIndex.size);
  11403. // Whether any directive selector matches on the element name
  11404. let matchElement = false;
  11405. selectorMatcher.match(elementCssSelector, (selector, directive) => {
  11406. directives[this.directivesIndex.get(directive)] = directive;
  11407. matchElement = matchElement || selector.hasElementSelector();
  11408. });
  11409. return {
  11410. directives: directives.filter(dir => !!dir),
  11411. matchElement,
  11412. };
  11413. }
  11414. _createDirectiveAsts(isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
  11415. const matchedReferences = new Set();
  11416. let component = null;
  11417. const directiveAsts = directives.map((directive) => {
  11418. const sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, `Directive ${identifierName(directive.type)}`);
  11419. if (directive.isComponent) {
  11420. component = directive;
  11421. }
  11422. const directiveProperties = [];
  11423. const boundProperties = this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
  11424. let hostProperties = boundProperties.map(prop => BoundElementPropertyAst.fromBoundProperty(prop));
  11425. // Note: We need to check the host properties here as well,
  11426. // as we don't know the element name in the DirectiveWrapperCompiler yet.
  11427. hostProperties = this._checkPropertiesInSchema(elementName, hostProperties);
  11428. const parsedEvents = this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
  11429. this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
  11430. elementOrDirectiveRefs.forEach((elOrDirRef) => {
  11431. if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
  11432. (elOrDirRef.isReferenceToDirective(directive))) {
  11433. targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
  11434. matchedReferences.add(elOrDirRef.name);
  11435. }
  11436. });
  11437. const hostEvents = parsedEvents.map(e => BoundEventAst.fromParsedEvent(e));
  11438. const contentQueryStartId = this.contentQueryStartId;
  11439. this.contentQueryStartId += directive.queries.length;
  11440. return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
  11441. });
  11442. elementOrDirectiveRefs.forEach((elOrDirRef) => {
  11443. if (elOrDirRef.value.length > 0) {
  11444. if (!matchedReferences.has(elOrDirRef.name)) {
  11445. this._reportError(`There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan);
  11446. }
  11447. }
  11448. else if (!component) {
  11449. let refToken = null;
  11450. if (isTemplateElement) {
  11451. refToken = createTokenForExternalReference(this.reflector, Identifiers.TemplateRef);
  11452. }
  11453. targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
  11454. }
  11455. });
  11456. return directiveAsts;
  11457. }
  11458. _createDirectivePropertyAsts(directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
  11459. if (directiveProperties) {
  11460. const boundPropsByName = new Map();
  11461. boundProps.forEach(boundProp => {
  11462. const prevValue = boundPropsByName.get(boundProp.name);
  11463. if (!prevValue || prevValue.isLiteral) {
  11464. // give [a]="b" a higher precedence than a="b" on the same element
  11465. boundPropsByName.set(boundProp.name, boundProp);
  11466. }
  11467. });
  11468. Object.keys(directiveProperties).forEach(dirProp => {
  11469. const elProp = directiveProperties[dirProp];
  11470. const boundProp = boundPropsByName.get(elProp);
  11471. // Bindings are optional, so this binding only needs to be set up if an expression is given.
  11472. if (boundProp) {
  11473. targetBoundDirectivePropNames.add(boundProp.name);
  11474. if (!isEmptyExpression(boundProp.expression)) {
  11475. targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
  11476. }
  11477. }
  11478. });
  11479. }
  11480. }
  11481. _createElementPropertyAsts(elementName, props, boundDirectivePropNames) {
  11482. const boundElementProps = [];
  11483. props.forEach((prop) => {
  11484. if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
  11485. const boundProp = this._bindingParser.createBoundElementProperty(elementName, prop);
  11486. boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
  11487. }
  11488. });
  11489. return this._checkPropertiesInSchema(elementName, boundElementProps);
  11490. }
  11491. _findComponentDirectives(directives) {
  11492. return directives.filter(directive => directive.directive.isComponent);
  11493. }
  11494. _findComponentDirectiveNames(directives) {
  11495. return this._findComponentDirectives(directives)
  11496. .map(directive => identifierName(directive.directive.type));
  11497. }
  11498. _assertOnlyOneComponent(directives, sourceSpan) {
  11499. const componentTypeNames = this._findComponentDirectiveNames(directives);
  11500. if (componentTypeNames.length > 1) {
  11501. this._reportError(`More than one component matched on this element.\n` +
  11502. `Make sure that only one component's selector can match a given element.\n` +
  11503. `Conflicting components: ${componentTypeNames.join(',')}`, sourceSpan);
  11504. }
  11505. }
  11506. /**
  11507. * Make sure that non-angular tags conform to the schemas.
  11508. *
  11509. * Note: An element is considered an angular tag when at least one directive selector matches the
  11510. * tag name.
  11511. *
  11512. * @param matchElement Whether any directive has matched on the tag name
  11513. * @param element the html element
  11514. */
  11515. _assertElementExists(matchElement, element) {
  11516. const elName = element.name.replace(/^:xhtml:/, '');
  11517. if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
  11518. let errorMsg = `'${elName}' is not a known element:\n`;
  11519. errorMsg +=
  11520. `1. If '${elName}' is an Angular component, then verify that it is part of this module.\n`;
  11521. if (elName.indexOf('-') > -1) {
  11522. errorMsg +=
  11523. `2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;
  11524. }
  11525. else {
  11526. errorMsg +=
  11527. `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
  11528. }
  11529. this._reportError(errorMsg, element.sourceSpan);
  11530. }
  11531. }
  11532. _assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps, sourceSpan) {
  11533. const componentTypeNames = this._findComponentDirectiveNames(directives);
  11534. if (componentTypeNames.length > 0) {
  11535. this._reportError(`Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan);
  11536. }
  11537. elementProps.forEach(prop => {
  11538. 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);
  11539. });
  11540. }
  11541. _assertAllEventsPublishedByDirectives(directives, events) {
  11542. const allDirectiveEvents = new Set();
  11543. directives.forEach(directive => {
  11544. Object.keys(directive.directive.outputs).forEach(k => {
  11545. const eventName = directive.directive.outputs[k];
  11546. allDirectiveEvents.add(eventName);
  11547. });
  11548. });
  11549. events.forEach(event => {
  11550. if (event.target != null || !allDirectiveEvents.has(event.name)) {
  11551. 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);
  11552. }
  11553. });
  11554. }
  11555. _checkPropertiesInSchema(elementName, boundProps) {
  11556. // Note: We can't filter out empty expressions before this method,
  11557. // as we still want to validate them!
  11558. return boundProps.filter((boundProp) => {
  11559. if (boundProp.type === 0 /* Property */ &&
  11560. !this._schemaRegistry.hasProperty(elementName, boundProp.name, this._schemas)) {
  11561. let errorMsg = `Can't bind to '${boundProp.name}' since it isn't a known property of '${elementName}'.`;
  11562. if (elementName.startsWith('ng-')) {
  11563. errorMsg +=
  11564. `\n1. If '${boundProp.name}' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.` +
  11565. `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
  11566. }
  11567. else if (elementName.indexOf('-') > -1) {
  11568. errorMsg +=
  11569. `\n1. If '${elementName}' is an Angular component and it has '${boundProp.name}' input, then verify that it is part of this module.` +
  11570. `\n2. If '${elementName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.` +
  11571. `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
  11572. }
  11573. this._reportError(errorMsg, boundProp.sourceSpan);
  11574. }
  11575. return !isEmptyExpression(boundProp.value);
  11576. });
  11577. }
  11578. _reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
  11579. this._targetErrors.push(new ParseError(sourceSpan, message, level));
  11580. }
  11581. }
  11582. class NonBindableVisitor {
  11583. visitElement(ast, parent) {
  11584. const preparsedElement = preparseElement(ast);
  11585. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  11586. preparsedElement.type === PreparsedElementType.STYLE ||
  11587. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  11588. // Skipping <script> for security reasons
  11589. // Skipping <style> and stylesheets as we already processed them
  11590. // in the StyleCompiler
  11591. return null;
  11592. }
  11593. const attrNameAndValues = ast.attrs.map((attr) => [attr.name, attr.value]);
  11594. const selector = createElementCssSelector(ast.name, attrNameAndValues);
  11595. const ngContentIndex = parent.findNgContentIndex(selector);
  11596. const children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
  11597. return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
  11598. }
  11599. visitComment(comment, context) { return null; }
  11600. visitAttribute(attribute, context) {
  11601. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  11602. }
  11603. visitText(text, parent) {
  11604. const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  11605. return new TextAst(text.value, ngContentIndex, text.sourceSpan);
  11606. }
  11607. visitExpansion(expansion, context) { return expansion; }
  11608. visitExpansionCase(expansionCase, context) { return expansionCase; }
  11609. }
  11610. /**
  11611. * A reference to an element or directive in a template. E.g., the reference in this template:
  11612. *
  11613. * <div #myMenu="coolMenu">
  11614. *
  11615. * would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
  11616. */
  11617. class ElementOrDirectiveRef {
  11618. constructor(name, value, sourceSpan) {
  11619. this.name = name;
  11620. this.value = value;
  11621. this.sourceSpan = sourceSpan;
  11622. }
  11623. /** Gets whether this is a reference to the given directive. */
  11624. isReferenceToDirective(directive) {
  11625. return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
  11626. }
  11627. }
  11628. /** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
  11629. function splitExportAs(exportAs) {
  11630. return exportAs ? exportAs.split(',').map(e => e.trim()) : [];
  11631. }
  11632. function splitClasses(classAttrValue) {
  11633. return classAttrValue.trim().split(/\s+/g);
  11634. }
  11635. class ElementContext {
  11636. constructor(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
  11637. this.isTemplateElement = isTemplateElement;
  11638. this._ngContentIndexMatcher = _ngContentIndexMatcher;
  11639. this._wildcardNgContentIndex = _wildcardNgContentIndex;
  11640. this.providerContext = providerContext;
  11641. }
  11642. static create(isTemplateElement, directives, providerContext) {
  11643. const matcher = new SelectorMatcher();
  11644. let wildcardNgContentIndex = null;
  11645. const component = directives.find(directive => directive.directive.isComponent);
  11646. if (component) {
  11647. const ngContentSelectors = component.directive.template.ngContentSelectors;
  11648. for (let i = 0; i < ngContentSelectors.length; i++) {
  11649. const selector = ngContentSelectors[i];
  11650. if (selector === '*') {
  11651. wildcardNgContentIndex = i;
  11652. }
  11653. else {
  11654. matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
  11655. }
  11656. }
  11657. }
  11658. return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
  11659. }
  11660. findNgContentIndex(selector) {
  11661. const ngContentIndices = [];
  11662. this._ngContentIndexMatcher.match(selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); });
  11663. ngContentIndices.sort();
  11664. if (this._wildcardNgContentIndex != null) {
  11665. ngContentIndices.push(this._wildcardNgContentIndex);
  11666. }
  11667. return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
  11668. }
  11669. }
  11670. function createElementCssSelector(elementName, attributes) {
  11671. const cssSelector = new CssSelector();
  11672. const elNameNoNs = splitNsName(elementName)[1];
  11673. cssSelector.setElement(elNameNoNs);
  11674. for (let i = 0; i < attributes.length; i++) {
  11675. const attrName = attributes[i][0];
  11676. const attrNameNoNs = splitNsName(attrName)[1];
  11677. const attrValue = attributes[i][1];
  11678. cssSelector.addAttribute(attrNameNoNs, attrValue);
  11679. if (attrName.toLowerCase() == CLASS_ATTR) {
  11680. const classes = splitClasses(attrValue);
  11681. classes.forEach(className => cssSelector.addClassName(className));
  11682. }
  11683. }
  11684. return cssSelector;
  11685. }
  11686. const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
  11687. const NON_BINDABLE_VISITOR = new NonBindableVisitor();
  11688. function _isEmptyTextNode(node) {
  11689. return node instanceof Text$3 && node.value.trim().length == 0;
  11690. }
  11691. function removeSummaryDuplicates(items) {
  11692. const map = new Map();
  11693. items.forEach((item) => {
  11694. if (!map.get(item.type.reference)) {
  11695. map.set(item.type.reference, item);
  11696. }
  11697. });
  11698. return Array.from(map.values());
  11699. }
  11700. function isEmptyExpression(ast) {
  11701. if (ast instanceof ASTWithSource) {
  11702. ast = ast.ast;
  11703. }
  11704. return ast instanceof EmptyExpr;
  11705. }
  11706. /**
  11707. * @license
  11708. * Copyright Google Inc. All Rights Reserved.
  11709. *
  11710. * Use of this source code is governed by an MIT-style license that can be
  11711. * found in the LICENSE file at https://angular.io/license
  11712. */
  11713. /**
  11714. * Parses string representation of a style and converts it into object literal.
  11715. *
  11716. * @param value string representation of style as used in the `style` attribute in HTML.
  11717. * Example: `color: red; height: auto`.
  11718. * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
  11719. * 'auto']`
  11720. */
  11721. function parse(value) {
  11722. // we use a string array here instead of a string map
  11723. // because a string-map is not guaranteed to retain the
  11724. // order of the entries whereas a string array can be
  11725. // construted in a [key, value, key, value] format.
  11726. const styles = [];
  11727. let i = 0;
  11728. let parenDepth = 0;
  11729. let quote = 0 /* QuoteNone */;
  11730. let valueStart = 0;
  11731. let propStart = 0;
  11732. let currentProp = null;
  11733. let valueHasQuotes = false;
  11734. while (i < value.length) {
  11735. const token = value.charCodeAt(i++);
  11736. switch (token) {
  11737. case 40 /* OpenParen */:
  11738. parenDepth++;
  11739. break;
  11740. case 41 /* CloseParen */:
  11741. parenDepth--;
  11742. break;
  11743. case 39 /* QuoteSingle */:
  11744. // valueStart needs to be there since prop values don't
  11745. // have quotes in CSS
  11746. valueHasQuotes = valueHasQuotes || valueStart > 0;
  11747. if (quote === 0 /* QuoteNone */) {
  11748. quote = 39 /* QuoteSingle */;
  11749. }
  11750. else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  11751. quote = 0 /* QuoteNone */;
  11752. }
  11753. break;
  11754. case 34 /* QuoteDouble */:
  11755. // same logic as above
  11756. valueHasQuotes = valueHasQuotes || valueStart > 0;
  11757. if (quote === 0 /* QuoteNone */) {
  11758. quote = 34 /* QuoteDouble */;
  11759. }
  11760. else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  11761. quote = 0 /* QuoteNone */;
  11762. }
  11763. break;
  11764. case 58 /* Colon */:
  11765. if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  11766. currentProp = hyphenate(value.substring(propStart, i - 1).trim());
  11767. valueStart = i;
  11768. }
  11769. break;
  11770. case 59 /* Semicolon */:
  11771. if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  11772. const styleVal = value.substring(valueStart, i - 1).trim();
  11773. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  11774. propStart = i;
  11775. valueStart = 0;
  11776. currentProp = null;
  11777. valueHasQuotes = false;
  11778. }
  11779. break;
  11780. }
  11781. }
  11782. if (currentProp && valueStart) {
  11783. const styleVal = value.substr(valueStart).trim();
  11784. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  11785. }
  11786. return styles;
  11787. }
  11788. function stripUnnecessaryQuotes(value) {
  11789. const qS = value.charCodeAt(0);
  11790. const qE = value.charCodeAt(value.length - 1);
  11791. if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
  11792. const tempValue = value.substring(1, value.length - 1);
  11793. // special case to avoid using a multi-quoted string that was just chomped
  11794. // (e.g. `font-family: "Verdana", "sans-serif"`)
  11795. if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
  11796. value = tempValue;
  11797. }
  11798. }
  11799. return value;
  11800. }
  11801. function hyphenate(value) {
  11802. return value.replace(/[a-z][A-Z]/g, v => {
  11803. return v.charAt(0) + '-' + v.charAt(1);
  11804. }).toLowerCase();
  11805. }
  11806. /**
  11807. * @license
  11808. * Copyright Google Inc. All Rights Reserved.
  11809. *
  11810. * Use of this source code is governed by an MIT-style license that can be
  11811. * found in the LICENSE file at https://angular.io/license
  11812. */
  11813. let _stylingMode = 0;
  11814. function compilerIsNewStylingInUse() {
  11815. return _stylingMode > 0 /* UseOld */;
  11816. }
  11817. const IMPORTANT_FLAG = '!important';
  11818. /**
  11819. * Produces creation/update instructions for all styling bindings (class and style)
  11820. *
  11821. * It also produces the creation instruction to register all initial styling values
  11822. * (which are all the static class="..." and style="..." attribute values that exist
  11823. * on an element within a template).
  11824. *
  11825. * The builder class below handles producing instructions for the following cases:
  11826. *
  11827. * - Static style/class attributes (style="..." and class="...")
  11828. * - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
  11829. * - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
  11830. *
  11831. * Due to the complex relationship of all of these cases, the instructions generated
  11832. * for these attributes/properties/bindings must be done so in the correct order. The
  11833. * order which these must be generated is as follows:
  11834. *
  11835. * if (createMode) {
  11836. * styling(...)
  11837. * }
  11838. * if (updateMode) {
  11839. * styleMap(...)
  11840. * classMap(...)
  11841. * styleProp(...)
  11842. * classProp(...)
  11843. * stylingApp(...)
  11844. * }
  11845. *
  11846. * The creation/update methods within the builder class produce these instructions.
  11847. */
  11848. class StylingBuilder {
  11849. constructor(_elementIndexExpr, _directiveExpr) {
  11850. this._elementIndexExpr = _elementIndexExpr;
  11851. this._directiveExpr = _directiveExpr;
  11852. /** Whether or not there are any static styling values present */
  11853. this._hasInitialValues = false;
  11854. /**
  11855. * Whether or not there are any styling bindings present
  11856. * (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
  11857. */
  11858. this.hasBindings = false;
  11859. /** the input for [class] (if it exists) */
  11860. this._classMapInput = null;
  11861. /** the input for [style] (if it exists) */
  11862. this._styleMapInput = null;
  11863. /** an array of each [style.prop] input */
  11864. this._singleStyleInputs = null;
  11865. /** an array of each [class.name] input */
  11866. this._singleClassInputs = null;
  11867. this._lastStylingInput = null;
  11868. this._firstStylingInput = null;
  11869. // maps are used instead of hash maps because a Map will
  11870. // retain the ordering of the keys
  11871. /**
  11872. * Represents the location of each style binding in the template
  11873. * (e.g. `<div [style.width]="w" [style.height]="h">` implies
  11874. * that `width=0` and `height=1`)
  11875. */
  11876. this._stylesIndex = new Map();
  11877. /**
  11878. * Represents the location of each class binding in the template
  11879. * (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
  11880. * that `big=0` and `hidden=1`)
  11881. */
  11882. this._classesIndex = new Map();
  11883. this._initialStyleValues = [];
  11884. this._initialClassValues = [];
  11885. // certain style properties ALWAYS need sanitization
  11886. // this is checked each time new styles are encountered
  11887. this._useDefaultSanitizer = false;
  11888. }
  11889. /**
  11890. * Registers a given input to the styling builder to be later used when producing AOT code.
  11891. *
  11892. * The code below will only accept the input if it is somehow tied to styling (whether it be
  11893. * style/class bindings or static style/class attributes).
  11894. */
  11895. registerBoundInput(input) {
  11896. // [attr.style] or [attr.class] are skipped in the code below,
  11897. // they should not be treated as styling-based bindings since
  11898. // they are intended to be written directly to the attr and
  11899. // will therefore skip all style/class resolution that is present
  11900. // with style="", [style]="" and [style.prop]="", class="",
  11901. // [class.prop]="". [class]="" assignments
  11902. let binding = null;
  11903. let name = input.name;
  11904. switch (input.type) {
  11905. case 0 /* Property */:
  11906. binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
  11907. break;
  11908. case 3 /* Style */:
  11909. binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
  11910. break;
  11911. case 2 /* Class */:
  11912. binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
  11913. break;
  11914. }
  11915. return binding ? true : false;
  11916. }
  11917. registerInputBasedOnName(name, expression, sourceSpan) {
  11918. let binding = null;
  11919. const nameToMatch = name.substring(0, 5); // class | style
  11920. const isStyle = nameToMatch === 'style';
  11921. const isClass = isStyle ? false : (nameToMatch === 'class');
  11922. if (isStyle || isClass) {
  11923. const isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
  11924. const property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
  11925. if (isStyle) {
  11926. binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
  11927. }
  11928. else {
  11929. binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
  11930. }
  11931. }
  11932. return binding;
  11933. }
  11934. registerStyleInput(name, isMapBased, value, sourceSpan, unit) {
  11935. if (isEmptyExpression(value)) {
  11936. return null;
  11937. }
  11938. const { property, hasOverrideFlag, unit: bindingUnit } = parseProperty(name);
  11939. const entry = {
  11940. name: property,
  11941. unit: unit || bindingUnit, value, sourceSpan, hasOverrideFlag
  11942. };
  11943. if (isMapBased) {
  11944. this._useDefaultSanitizer = true;
  11945. this._styleMapInput = entry;
  11946. }
  11947. else {
  11948. (this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
  11949. this._useDefaultSanitizer = this._useDefaultSanitizer || isStyleSanitizable(name);
  11950. registerIntoMap(this._stylesIndex, property);
  11951. }
  11952. this._lastStylingInput = entry;
  11953. this._firstStylingInput = this._firstStylingInput || entry;
  11954. this.hasBindings = true;
  11955. return entry;
  11956. }
  11957. registerClassInput(name, isMapBased, value, sourceSpan) {
  11958. if (isEmptyExpression(value)) {
  11959. return null;
  11960. }
  11961. const { property, hasOverrideFlag } = parseProperty(name);
  11962. const entry = { name: property, value, sourceSpan, hasOverrideFlag, unit: null };
  11963. if (isMapBased) {
  11964. this._classMapInput = entry;
  11965. }
  11966. else {
  11967. (this._singleClassInputs = this._singleClassInputs || []).push(entry);
  11968. registerIntoMap(this._classesIndex, property);
  11969. }
  11970. this._lastStylingInput = entry;
  11971. this._firstStylingInput = this._firstStylingInput || entry;
  11972. this.hasBindings = true;
  11973. return entry;
  11974. }
  11975. /**
  11976. * Registers the element's static style string value to the builder.
  11977. *
  11978. * @param value the style string (e.g. `width:100px; height:200px;`)
  11979. */
  11980. registerStyleAttr(value) {
  11981. this._initialStyleValues = parse(value);
  11982. this._hasInitialValues = true;
  11983. }
  11984. /**
  11985. * Registers the element's static class string value to the builder.
  11986. *
  11987. * @param value the className string (e.g. `disabled gold zoom`)
  11988. */
  11989. registerClassAttr(value) {
  11990. this._initialClassValues = value.trim().split(/\s+/g);
  11991. this._hasInitialValues = true;
  11992. }
  11993. /**
  11994. * Appends all styling-related expressions to the provided attrs array.
  11995. *
  11996. * @param attrs an existing array where each of the styling expressions
  11997. * will be inserted into.
  11998. */
  11999. populateInitialStylingAttrs(attrs) {
  12000. // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
  12001. if (this._initialClassValues.length) {
  12002. attrs.push(literal(1 /* Classes */));
  12003. for (let i = 0; i < this._initialClassValues.length; i++) {
  12004. attrs.push(literal(this._initialClassValues[i]));
  12005. }
  12006. }
  12007. // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
  12008. if (this._initialStyleValues.length) {
  12009. attrs.push(literal(2 /* Styles */));
  12010. for (let i = 0; i < this._initialStyleValues.length; i += 2) {
  12011. attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
  12012. }
  12013. }
  12014. }
  12015. /**
  12016. * Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
  12017. *
  12018. * The instruction generation code below is used for producing the AOT statement code which is
  12019. * responsible for registering initial styles (within a directive hostBindings' creation block),
  12020. * as well as any of the provided attribute values, to the directive host element.
  12021. */
  12022. buildHostAttrsInstruction(sourceSpan, attrs, constantPool) {
  12023. if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
  12024. return {
  12025. sourceSpan,
  12026. reference: Identifiers$1.elementHostAttrs,
  12027. allocateBindingSlots: 0,
  12028. buildParams: () => {
  12029. // params => elementHostAttrs(attrs)
  12030. this.populateInitialStylingAttrs(attrs);
  12031. const attrArray = !attrs.some(attr => attr instanceof WrappedNodeExpr) ?
  12032. getConstantLiteralFromArray(constantPool, attrs) :
  12033. literalArr(attrs);
  12034. return [attrArray];
  12035. }
  12036. };
  12037. }
  12038. return null;
  12039. }
  12040. /**
  12041. * Builds an instruction with all the expressions and parameters for `styling`.
  12042. *
  12043. * The instruction generation code below is used for producing the AOT statement code which is
  12044. * responsible for registering style/class bindings to an element.
  12045. */
  12046. buildStylingInstruction(sourceSpan, constantPool) {
  12047. if (this.hasBindings) {
  12048. return {
  12049. sourceSpan,
  12050. allocateBindingSlots: 0,
  12051. reference: Identifiers$1.styling,
  12052. buildParams: () => {
  12053. // a string array of every style-based binding
  12054. const styleBindingProps = this._singleStyleInputs ? this._singleStyleInputs.map(i => literal(i.name)) : [];
  12055. // a string array of every class-based binding
  12056. const classBindingNames = this._singleClassInputs ? this._singleClassInputs.map(i => literal(i.name)) : [];
  12057. // to salvage space in the AOT generated code, there is no point in passing
  12058. // in `null` into a param if any follow-up params are not used. Therefore,
  12059. // only when a trailing param is used then it will be filled with nulls in between
  12060. // (otherwise a shorter amount of params will be filled). The code below helps
  12061. // determine how many params are required in the expression code.
  12062. //
  12063. // min params => styling()
  12064. // max params => styling(classBindings, styleBindings, sanitizer)
  12065. //
  12066. const params = [];
  12067. let expectedNumberOfArgs = 0;
  12068. if (this._useDefaultSanitizer) {
  12069. expectedNumberOfArgs = 3;
  12070. }
  12071. else if (styleBindingProps.length) {
  12072. expectedNumberOfArgs = 2;
  12073. }
  12074. else if (classBindingNames.length) {
  12075. expectedNumberOfArgs = 1;
  12076. }
  12077. addParam(params, classBindingNames.length > 0, getConstantLiteralFromArray(constantPool, classBindingNames), 1, expectedNumberOfArgs);
  12078. addParam(params, styleBindingProps.length > 0, getConstantLiteralFromArray(constantPool, styleBindingProps), 2, expectedNumberOfArgs);
  12079. addParam(params, this._useDefaultSanitizer, importExpr(Identifiers$1.defaultStyleSanitizer), 3, expectedNumberOfArgs);
  12080. return params;
  12081. }
  12082. };
  12083. }
  12084. return null;
  12085. }
  12086. /**
  12087. * Builds an instruction with all the expressions and parameters for `classMap`.
  12088. *
  12089. * The instruction data will contain all expressions for `classMap` to function
  12090. * which includes the `[class]` expression params.
  12091. */
  12092. buildClassMapInstruction(valueConverter) {
  12093. if (this._classMapInput) {
  12094. return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
  12095. }
  12096. return null;
  12097. }
  12098. /**
  12099. * Builds an instruction with all the expressions and parameters for `styleMap`.
  12100. *
  12101. * The instruction data will contain all expressions for `styleMap` to function
  12102. * which includes the `[style]` expression params.
  12103. */
  12104. buildStyleMapInstruction(valueConverter) {
  12105. if (this._styleMapInput) {
  12106. return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
  12107. }
  12108. return null;
  12109. }
  12110. _buildMapBasedInstruction(valueConverter, isClassBased, stylingInput) {
  12111. let totalBindingSlotsRequired = 0;
  12112. if (compilerIsNewStylingInUse()) {
  12113. // the old implementation does not reserve slot values for
  12114. // binding entries. The new one does.
  12115. totalBindingSlotsRequired++;
  12116. }
  12117. // these values must be outside of the update block so that they can
  12118. // be evaluated (the AST visit call) during creation time so that any
  12119. // pipes can be picked up in time before the template is built
  12120. const mapValue = stylingInput.value.visit(valueConverter);
  12121. if (mapValue instanceof Interpolation) {
  12122. totalBindingSlotsRequired += mapValue.expressions.length;
  12123. }
  12124. const reference = isClassBased ? Identifiers$1.classMap : Identifiers$1.styleMap;
  12125. return {
  12126. sourceSpan: stylingInput.sourceSpan,
  12127. reference,
  12128. allocateBindingSlots: totalBindingSlotsRequired,
  12129. buildParams: (convertFn) => { return [convertFn(mapValue)]; }
  12130. };
  12131. }
  12132. _buildSingleInputs(reference, inputs, mapIndex, allowUnits, valueConverter) {
  12133. let totalBindingSlotsRequired = 0;
  12134. return inputs.map(input => {
  12135. const bindingIndex = mapIndex.get(input.name);
  12136. const value = input.value.visit(valueConverter);
  12137. totalBindingSlotsRequired += (value instanceof Interpolation) ? value.expressions.length : 0;
  12138. if (compilerIsNewStylingInUse()) {
  12139. // the old implementation does not reserve slot values for
  12140. // binding entries. The new one does.
  12141. totalBindingSlotsRequired++;
  12142. }
  12143. return {
  12144. sourceSpan: input.sourceSpan,
  12145. allocateBindingSlots: totalBindingSlotsRequired, reference,
  12146. buildParams: (convertFn) => {
  12147. // min params => stylingProp(elmIndex, bindingIndex, value)
  12148. // max params => stylingProp(elmIndex, bindingIndex, value, overrideFlag)
  12149. const params = [];
  12150. params.push(literal(bindingIndex));
  12151. params.push(convertFn(value));
  12152. if (allowUnits) {
  12153. if (input.unit) {
  12154. params.push(literal(input.unit));
  12155. }
  12156. else if (input.hasOverrideFlag) {
  12157. params.push(NULL_EXPR);
  12158. }
  12159. }
  12160. if (input.hasOverrideFlag) {
  12161. params.push(literal(true));
  12162. }
  12163. return params;
  12164. }
  12165. };
  12166. });
  12167. }
  12168. _buildClassInputs(valueConverter) {
  12169. if (this._singleClassInputs) {
  12170. return this._buildSingleInputs(Identifiers$1.classProp, this._singleClassInputs, this._classesIndex, false, valueConverter);
  12171. }
  12172. return [];
  12173. }
  12174. _buildStyleInputs(valueConverter) {
  12175. if (this._singleStyleInputs) {
  12176. return this._buildSingleInputs(Identifiers$1.styleProp, this._singleStyleInputs, this._stylesIndex, true, valueConverter);
  12177. }
  12178. return [];
  12179. }
  12180. _buildApplyFn() {
  12181. return {
  12182. sourceSpan: this._lastStylingInput ? this._lastStylingInput.sourceSpan : null,
  12183. reference: Identifiers$1.stylingApply,
  12184. allocateBindingSlots: 0,
  12185. buildParams: () => { return []; }
  12186. };
  12187. }
  12188. _buildSanitizerFn() {
  12189. return {
  12190. sourceSpan: this._firstStylingInput ? this._firstStylingInput.sourceSpan : null,
  12191. reference: Identifiers$1.styleSanitizer,
  12192. allocateBindingSlots: 0,
  12193. buildParams: () => [importExpr(Identifiers$1.defaultStyleSanitizer)]
  12194. };
  12195. }
  12196. /**
  12197. * Constructs all instructions which contain the expressions that will be placed
  12198. * into the update block of a template function or a directive hostBindings function.
  12199. */
  12200. buildUpdateLevelInstructions(valueConverter) {
  12201. const instructions = [];
  12202. if (this.hasBindings) {
  12203. if (compilerIsNewStylingInUse() && this._useDefaultSanitizer) {
  12204. instructions.push(this._buildSanitizerFn());
  12205. }
  12206. const styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
  12207. if (styleMapInstruction) {
  12208. instructions.push(styleMapInstruction);
  12209. }
  12210. const classMapInstruction = this.buildClassMapInstruction(valueConverter);
  12211. if (classMapInstruction) {
  12212. instructions.push(classMapInstruction);
  12213. }
  12214. instructions.push(...this._buildStyleInputs(valueConverter));
  12215. instructions.push(...this._buildClassInputs(valueConverter));
  12216. instructions.push(this._buildApplyFn());
  12217. }
  12218. return instructions;
  12219. }
  12220. }
  12221. function registerIntoMap(map, key) {
  12222. if (!map.has(key)) {
  12223. map.set(key, map.size);
  12224. }
  12225. }
  12226. function isStyleSanitizable(prop) {
  12227. // Note that browsers support both the dash case and
  12228. // camel case property names when setting through JS.
  12229. return prop === 'background-image' || prop === 'backgroundImage' || prop === 'background' ||
  12230. prop === 'border-image' || prop === 'borderImage' || prop === 'filter' ||
  12231. prop === 'list-style' || prop === 'listStyle' || prop === 'list-style-image' ||
  12232. prop === 'listStyleImage' || prop === 'clip-path' || prop === 'clipPath';
  12233. }
  12234. /**
  12235. * Simple helper function to either provide the constant literal that will house the value
  12236. * here or a null value if the provided values are empty.
  12237. */
  12238. function getConstantLiteralFromArray(constantPool, values) {
  12239. return values.length ? constantPool.getConstLiteral(literalArr(values), true) : NULL_EXPR;
  12240. }
  12241. /**
  12242. * Simple helper function that adds a parameter or does nothing at all depending on the provided
  12243. * predicate and totalExpectedArgs values
  12244. */
  12245. function addParam(params, predicate, value, argNumber, totalExpectedArgs) {
  12246. if (predicate && value) {
  12247. params.push(value);
  12248. }
  12249. else if (argNumber < totalExpectedArgs) {
  12250. params.push(NULL_EXPR);
  12251. }
  12252. }
  12253. function parseProperty(name) {
  12254. let hasOverrideFlag = false;
  12255. const overrideIndex = name.indexOf(IMPORTANT_FLAG);
  12256. if (overrideIndex !== -1) {
  12257. name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
  12258. hasOverrideFlag = true;
  12259. }
  12260. let unit = '';
  12261. let property = name;
  12262. const unitIndex = name.lastIndexOf('.');
  12263. if (unitIndex > 0) {
  12264. unit = name.substr(unitIndex + 1);
  12265. property = name.substring(0, unitIndex);
  12266. }
  12267. return { property, unit, hasOverrideFlag };
  12268. }
  12269. /**
  12270. * @license
  12271. * Copyright Google Inc. All Rights Reserved.
  12272. *
  12273. * Use of this source code is governed by an MIT-style license that can be
  12274. * found in the LICENSE file at https://angular.io/license
  12275. */
  12276. var TokenType$1;
  12277. (function (TokenType) {
  12278. TokenType[TokenType["Character"] = 0] = "Character";
  12279. TokenType[TokenType["Identifier"] = 1] = "Identifier";
  12280. TokenType[TokenType["Keyword"] = 2] = "Keyword";
  12281. TokenType[TokenType["String"] = 3] = "String";
  12282. TokenType[TokenType["Operator"] = 4] = "Operator";
  12283. TokenType[TokenType["Number"] = 5] = "Number";
  12284. TokenType[TokenType["Error"] = 6] = "Error";
  12285. })(TokenType$1 || (TokenType$1 = {}));
  12286. const KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
  12287. class Lexer {
  12288. tokenize(text) {
  12289. const scanner = new _Scanner(text);
  12290. const tokens = [];
  12291. let token = scanner.scanToken();
  12292. while (token != null) {
  12293. tokens.push(token);
  12294. token = scanner.scanToken();
  12295. }
  12296. return tokens;
  12297. }
  12298. }
  12299. class Token$1 {
  12300. constructor(index, type, numValue, strValue) {
  12301. this.index = index;
  12302. this.type = type;
  12303. this.numValue = numValue;
  12304. this.strValue = strValue;
  12305. }
  12306. isCharacter(code) {
  12307. return this.type == TokenType$1.Character && this.numValue == code;
  12308. }
  12309. isNumber() { return this.type == TokenType$1.Number; }
  12310. isString() { return this.type == TokenType$1.String; }
  12311. isOperator(operator) {
  12312. return this.type == TokenType$1.Operator && this.strValue == operator;
  12313. }
  12314. isIdentifier() { return this.type == TokenType$1.Identifier; }
  12315. isKeyword() { return this.type == TokenType$1.Keyword; }
  12316. isKeywordLet() { return this.type == TokenType$1.Keyword && this.strValue == 'let'; }
  12317. isKeywordAs() { return this.type == TokenType$1.Keyword && this.strValue == 'as'; }
  12318. isKeywordNull() { return this.type == TokenType$1.Keyword && this.strValue == 'null'; }
  12319. isKeywordUndefined() {
  12320. return this.type == TokenType$1.Keyword && this.strValue == 'undefined';
  12321. }
  12322. isKeywordTrue() { return this.type == TokenType$1.Keyword && this.strValue == 'true'; }
  12323. isKeywordFalse() { return this.type == TokenType$1.Keyword && this.strValue == 'false'; }
  12324. isKeywordThis() { return this.type == TokenType$1.Keyword && this.strValue == 'this'; }
  12325. isError() { return this.type == TokenType$1.Error; }
  12326. toNumber() { return this.type == TokenType$1.Number ? this.numValue : -1; }
  12327. toString() {
  12328. switch (this.type) {
  12329. case TokenType$1.Character:
  12330. case TokenType$1.Identifier:
  12331. case TokenType$1.Keyword:
  12332. case TokenType$1.Operator:
  12333. case TokenType$1.String:
  12334. case TokenType$1.Error:
  12335. return this.strValue;
  12336. case TokenType$1.Number:
  12337. return this.numValue.toString();
  12338. default:
  12339. return null;
  12340. }
  12341. }
  12342. }
  12343. function newCharacterToken(index, code) {
  12344. return new Token$1(index, TokenType$1.Character, code, String.fromCharCode(code));
  12345. }
  12346. function newIdentifierToken(index, text) {
  12347. return new Token$1(index, TokenType$1.Identifier, 0, text);
  12348. }
  12349. function newKeywordToken(index, text) {
  12350. return new Token$1(index, TokenType$1.Keyword, 0, text);
  12351. }
  12352. function newOperatorToken(index, text) {
  12353. return new Token$1(index, TokenType$1.Operator, 0, text);
  12354. }
  12355. function newStringToken(index, text) {
  12356. return new Token$1(index, TokenType$1.String, 0, text);
  12357. }
  12358. function newNumberToken(index, n) {
  12359. return new Token$1(index, TokenType$1.Number, n, '');
  12360. }
  12361. function newErrorToken(index, message) {
  12362. return new Token$1(index, TokenType$1.Error, 0, message);
  12363. }
  12364. const EOF = new Token$1(-1, TokenType$1.Character, 0, '');
  12365. class _Scanner {
  12366. constructor(input) {
  12367. this.input = input;
  12368. this.peek = 0;
  12369. this.index = -1;
  12370. this.length = input.length;
  12371. this.advance();
  12372. }
  12373. advance() {
  12374. this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
  12375. }
  12376. scanToken() {
  12377. const input = this.input, length = this.length;
  12378. let peek = this.peek, index = this.index;
  12379. // Skip whitespace.
  12380. while (peek <= $SPACE) {
  12381. if (++index >= length) {
  12382. peek = $EOF;
  12383. break;
  12384. }
  12385. else {
  12386. peek = input.charCodeAt(index);
  12387. }
  12388. }
  12389. this.peek = peek;
  12390. this.index = index;
  12391. if (index >= length) {
  12392. return null;
  12393. }
  12394. // Handle identifiers and numbers.
  12395. if (isIdentifierStart(peek))
  12396. return this.scanIdentifier();
  12397. if (isDigit(peek))
  12398. return this.scanNumber(index);
  12399. const start = index;
  12400. switch (peek) {
  12401. case $PERIOD:
  12402. this.advance();
  12403. return isDigit(this.peek) ? this.scanNumber(start) :
  12404. newCharacterToken(start, $PERIOD);
  12405. case $LPAREN:
  12406. case $RPAREN:
  12407. case $LBRACE:
  12408. case $RBRACE:
  12409. case $LBRACKET:
  12410. case $RBRACKET:
  12411. case $COMMA:
  12412. case $COLON:
  12413. case $SEMICOLON:
  12414. return this.scanCharacter(start, peek);
  12415. case $SQ:
  12416. case $DQ:
  12417. return this.scanString();
  12418. case $HASH:
  12419. case $PLUS:
  12420. case $MINUS:
  12421. case $STAR:
  12422. case $SLASH:
  12423. case $PERCENT:
  12424. case $CARET:
  12425. return this.scanOperator(start, String.fromCharCode(peek));
  12426. case $QUESTION:
  12427. return this.scanComplexOperator(start, '?', $PERIOD, '.');
  12428. case $LT:
  12429. case $GT:
  12430. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
  12431. case $BANG:
  12432. case $EQ:
  12433. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
  12434. case $AMPERSAND:
  12435. return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
  12436. case $BAR:
  12437. return this.scanComplexOperator(start, '|', $BAR, '|');
  12438. case $NBSP:
  12439. while (isWhitespace(this.peek))
  12440. this.advance();
  12441. return this.scanToken();
  12442. }
  12443. this.advance();
  12444. return this.error(`Unexpected character [${String.fromCharCode(peek)}]`, 0);
  12445. }
  12446. scanCharacter(start, code) {
  12447. this.advance();
  12448. return newCharacterToken(start, code);
  12449. }
  12450. scanOperator(start, str) {
  12451. this.advance();
  12452. return newOperatorToken(start, str);
  12453. }
  12454. /**
  12455. * Tokenize a 2/3 char long operator
  12456. *
  12457. * @param start start index in the expression
  12458. * @param one first symbol (always part of the operator)
  12459. * @param twoCode code point for the second symbol
  12460. * @param two second symbol (part of the operator when the second code point matches)
  12461. * @param threeCode code point for the third symbol
  12462. * @param three third symbol (part of the operator when provided and matches source expression)
  12463. */
  12464. scanComplexOperator(start, one, twoCode, two, threeCode, three) {
  12465. this.advance();
  12466. let str = one;
  12467. if (this.peek == twoCode) {
  12468. this.advance();
  12469. str += two;
  12470. }
  12471. if (threeCode != null && this.peek == threeCode) {
  12472. this.advance();
  12473. str += three;
  12474. }
  12475. return newOperatorToken(start, str);
  12476. }
  12477. scanIdentifier() {
  12478. const start = this.index;
  12479. this.advance();
  12480. while (isIdentifierPart(this.peek))
  12481. this.advance();
  12482. const str = this.input.substring(start, this.index);
  12483. return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
  12484. newIdentifierToken(start, str);
  12485. }
  12486. scanNumber(start) {
  12487. let simple = (this.index === start);
  12488. this.advance(); // Skip initial digit.
  12489. while (true) {
  12490. if (isDigit(this.peek)) ;
  12491. else if (this.peek == $PERIOD) {
  12492. simple = false;
  12493. }
  12494. else if (isExponentStart(this.peek)) {
  12495. this.advance();
  12496. if (isExponentSign(this.peek))
  12497. this.advance();
  12498. if (!isDigit(this.peek))
  12499. return this.error('Invalid exponent', -1);
  12500. simple = false;
  12501. }
  12502. else {
  12503. break;
  12504. }
  12505. this.advance();
  12506. }
  12507. const str = this.input.substring(start, this.index);
  12508. const value = simple ? parseIntAutoRadix(str) : parseFloat(str);
  12509. return newNumberToken(start, value);
  12510. }
  12511. scanString() {
  12512. const start = this.index;
  12513. const quote = this.peek;
  12514. this.advance(); // Skip initial quote.
  12515. let buffer = '';
  12516. let marker = this.index;
  12517. const input = this.input;
  12518. while (this.peek != quote) {
  12519. if (this.peek == $BACKSLASH) {
  12520. buffer += input.substring(marker, this.index);
  12521. this.advance();
  12522. let unescapedCode;
  12523. // Workaround for TS2.1-introduced type strictness
  12524. this.peek = this.peek;
  12525. if (this.peek == $u) {
  12526. // 4 character hex code for unicode character.
  12527. const hex = input.substring(this.index + 1, this.index + 5);
  12528. if (/^[0-9a-f]+$/i.test(hex)) {
  12529. unescapedCode = parseInt(hex, 16);
  12530. }
  12531. else {
  12532. return this.error(`Invalid unicode escape [\\u${hex}]`, 0);
  12533. }
  12534. for (let i = 0; i < 5; i++) {
  12535. this.advance();
  12536. }
  12537. }
  12538. else {
  12539. unescapedCode = unescape(this.peek);
  12540. this.advance();
  12541. }
  12542. buffer += String.fromCharCode(unescapedCode);
  12543. marker = this.index;
  12544. }
  12545. else if (this.peek == $EOF) {
  12546. return this.error('Unterminated quote', 0);
  12547. }
  12548. else {
  12549. this.advance();
  12550. }
  12551. }
  12552. const last = input.substring(marker, this.index);
  12553. this.advance(); // Skip terminating quote.
  12554. return newStringToken(start, buffer + last);
  12555. }
  12556. error(message, offset) {
  12557. const position = this.index + offset;
  12558. return newErrorToken(position, `Lexer Error: ${message} at column ${position} in expression [${this.input}]`);
  12559. }
  12560. }
  12561. function isIdentifierStart(code) {
  12562. return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
  12563. (code == $_) || (code == $$);
  12564. }
  12565. function isIdentifier(input) {
  12566. if (input.length == 0)
  12567. return false;
  12568. const scanner = new _Scanner(input);
  12569. if (!isIdentifierStart(scanner.peek))
  12570. return false;
  12571. scanner.advance();
  12572. while (scanner.peek !== $EOF) {
  12573. if (!isIdentifierPart(scanner.peek))
  12574. return false;
  12575. scanner.advance();
  12576. }
  12577. return true;
  12578. }
  12579. function isIdentifierPart(code) {
  12580. return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
  12581. (code == $$);
  12582. }
  12583. function isExponentStart(code) {
  12584. return code == $e || code == $E;
  12585. }
  12586. function isExponentSign(code) {
  12587. return code == $MINUS || code == $PLUS;
  12588. }
  12589. function isQuote(code) {
  12590. return code === $SQ || code === $DQ || code === $BT;
  12591. }
  12592. function unescape(code) {
  12593. switch (code) {
  12594. case $n:
  12595. return $LF;
  12596. case $f:
  12597. return $FF;
  12598. case $r:
  12599. return $CR;
  12600. case $t:
  12601. return $TAB;
  12602. case $v:
  12603. return $VTAB;
  12604. default:
  12605. return code;
  12606. }
  12607. }
  12608. function parseIntAutoRadix(text) {
  12609. const result = parseInt(text);
  12610. if (isNaN(result)) {
  12611. throw new Error('Invalid integer literal when parsing ' + text);
  12612. }
  12613. return result;
  12614. }
  12615. /**
  12616. * @license
  12617. * Copyright Google Inc. All Rights Reserved.
  12618. *
  12619. * Use of this source code is governed by an MIT-style license that can be
  12620. * found in the LICENSE file at https://angular.io/license
  12621. */
  12622. class SplitInterpolation {
  12623. constructor(strings, expressions, offsets) {
  12624. this.strings = strings;
  12625. this.expressions = expressions;
  12626. this.offsets = offsets;
  12627. }
  12628. }
  12629. class TemplateBindingParseResult {
  12630. constructor(templateBindings, warnings, errors) {
  12631. this.templateBindings = templateBindings;
  12632. this.warnings = warnings;
  12633. this.errors = errors;
  12634. }
  12635. }
  12636. function _createInterpolateRegExp(config) {
  12637. const pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
  12638. return new RegExp(pattern, 'g');
  12639. }
  12640. class Parser$1 {
  12641. constructor(_lexer) {
  12642. this._lexer = _lexer;
  12643. this.errors = [];
  12644. }
  12645. parseAction(input, location, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
  12646. this._checkNoInterpolation(input, location, interpolationConfig);
  12647. const sourceToLex = this._stripComments(input);
  12648. const tokens = this._lexer.tokenize(this._stripComments(input));
  12649. const ast = new _ParseAST(input, location, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
  12650. .parseChain();
  12651. return new ASTWithSource(ast, input, location, this.errors);
  12652. }
  12653. parseBinding(input, location, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
  12654. const ast = this._parseBindingAst(input, location, interpolationConfig);
  12655. return new ASTWithSource(ast, input, location, this.errors);
  12656. }
  12657. parseSimpleBinding(input, location, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
  12658. const ast = this._parseBindingAst(input, location, interpolationConfig);
  12659. const errors = SimpleExpressionChecker.check(ast);
  12660. if (errors.length > 0) {
  12661. this._reportError(`Host binding expression cannot contain ${errors.join(' ')}`, input, location);
  12662. }
  12663. return new ASTWithSource(ast, input, location, this.errors);
  12664. }
  12665. _reportError(message, input, errLocation, ctxLocation) {
  12666. this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
  12667. }
  12668. _parseBindingAst(input, location, interpolationConfig) {
  12669. // Quotes expressions use 3rd-party expression language. We don't want to use
  12670. // our lexer or parser for that, so we check for that ahead of time.
  12671. const quote = this._parseQuote(input, location);
  12672. if (quote != null) {
  12673. return quote;
  12674. }
  12675. this._checkNoInterpolation(input, location, interpolationConfig);
  12676. const sourceToLex = this._stripComments(input);
  12677. const tokens = this._lexer.tokenize(sourceToLex);
  12678. return new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
  12679. .parseChain();
  12680. }
  12681. _parseQuote(input, location) {
  12682. if (input == null)
  12683. return null;
  12684. const prefixSeparatorIndex = input.indexOf(':');
  12685. if (prefixSeparatorIndex == -1)
  12686. return null;
  12687. const prefix = input.substring(0, prefixSeparatorIndex).trim();
  12688. if (!isIdentifier(prefix))
  12689. return null;
  12690. const uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
  12691. return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
  12692. }
  12693. parseTemplateBindings(tplKey, tplValue, location) {
  12694. const tokens = this._lexer.tokenize(tplValue);
  12695. return new _ParseAST(tplValue, location, tokens, tplValue.length, false, this.errors, 0)
  12696. .parseTemplateBindings(tplKey);
  12697. }
  12698. parseInterpolation(input, location, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
  12699. const split = this.splitInterpolation(input, location, interpolationConfig);
  12700. if (split == null)
  12701. return null;
  12702. const expressions = [];
  12703. for (let i = 0; i < split.expressions.length; ++i) {
  12704. const expressionText = split.expressions[i];
  12705. const sourceToLex = this._stripComments(expressionText);
  12706. const tokens = this._lexer.tokenize(sourceToLex);
  12707. const ast = new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, split.offsets[i] + (expressionText.length - sourceToLex.length))
  12708. .parseChain();
  12709. expressions.push(ast);
  12710. }
  12711. return new ASTWithSource(new Interpolation(new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions), input, location, this.errors);
  12712. }
  12713. splitInterpolation(input, location, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
  12714. const regexp = _createInterpolateRegExp(interpolationConfig);
  12715. const parts = input.split(regexp);
  12716. if (parts.length <= 1) {
  12717. return null;
  12718. }
  12719. const strings = [];
  12720. const expressions = [];
  12721. const offsets = [];
  12722. let offset = 0;
  12723. for (let i = 0; i < parts.length; i++) {
  12724. const part = parts[i];
  12725. if (i % 2 === 0) {
  12726. // fixed string
  12727. strings.push(part);
  12728. offset += part.length;
  12729. }
  12730. else if (part.trim().length > 0) {
  12731. offset += interpolationConfig.start.length;
  12732. expressions.push(part);
  12733. offsets.push(offset);
  12734. offset += part.length + interpolationConfig.end.length;
  12735. }
  12736. else {
  12737. this._reportError('Blank expressions are not allowed in interpolated strings', input, `at column ${this._findInterpolationErrorColumn(parts, i, interpolationConfig)} in`, location);
  12738. expressions.push('$implict');
  12739. offsets.push(offset);
  12740. }
  12741. }
  12742. return new SplitInterpolation(strings, expressions, offsets);
  12743. }
  12744. wrapLiteralPrimitive(input, location) {
  12745. return new ASTWithSource(new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input, location, this.errors);
  12746. }
  12747. _stripComments(input) {
  12748. const i = this._commentStart(input);
  12749. return i != null ? input.substring(0, i).trim() : input;
  12750. }
  12751. _commentStart(input) {
  12752. let outerQuote = null;
  12753. for (let i = 0; i < input.length - 1; i++) {
  12754. const char = input.charCodeAt(i);
  12755. const nextChar = input.charCodeAt(i + 1);
  12756. if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
  12757. return i;
  12758. if (outerQuote === char) {
  12759. outerQuote = null;
  12760. }
  12761. else if (outerQuote == null && isQuote(char)) {
  12762. outerQuote = char;
  12763. }
  12764. }
  12765. return null;
  12766. }
  12767. _checkNoInterpolation(input, location, interpolationConfig) {
  12768. const regexp = _createInterpolateRegExp(interpolationConfig);
  12769. const parts = input.split(regexp);
  12770. if (parts.length > 1) {
  12771. this._reportError(`Got interpolation (${interpolationConfig.start}${interpolationConfig.end}) where expression was expected`, input, `at column ${this._findInterpolationErrorColumn(parts, 1, interpolationConfig)} in`, location);
  12772. }
  12773. }
  12774. _findInterpolationErrorColumn(parts, partInErrIdx, interpolationConfig) {
  12775. let errLocation = '';
  12776. for (let j = 0; j < partInErrIdx; j++) {
  12777. errLocation += j % 2 === 0 ?
  12778. parts[j] :
  12779. `${interpolationConfig.start}${parts[j]}${interpolationConfig.end}`;
  12780. }
  12781. return errLocation.length;
  12782. }
  12783. }
  12784. class _ParseAST {
  12785. constructor(input, location, tokens, inputLength, parseAction, errors, offset) {
  12786. this.input = input;
  12787. this.location = location;
  12788. this.tokens = tokens;
  12789. this.inputLength = inputLength;
  12790. this.parseAction = parseAction;
  12791. this.errors = errors;
  12792. this.offset = offset;
  12793. this.rparensExpected = 0;
  12794. this.rbracketsExpected = 0;
  12795. this.rbracesExpected = 0;
  12796. this.index = 0;
  12797. }
  12798. peek(offset) {
  12799. const i = this.index + offset;
  12800. return i < this.tokens.length ? this.tokens[i] : EOF;
  12801. }
  12802. get next() { return this.peek(0); }
  12803. get inputIndex() {
  12804. return (this.index < this.tokens.length) ? this.next.index + this.offset :
  12805. this.inputLength + this.offset;
  12806. }
  12807. span(start) { return new ParseSpan(start, this.inputIndex); }
  12808. advance() { this.index++; }
  12809. optionalCharacter(code) {
  12810. if (this.next.isCharacter(code)) {
  12811. this.advance();
  12812. return true;
  12813. }
  12814. else {
  12815. return false;
  12816. }
  12817. }
  12818. peekKeywordLet() { return this.next.isKeywordLet(); }
  12819. peekKeywordAs() { return this.next.isKeywordAs(); }
  12820. expectCharacter(code) {
  12821. if (this.optionalCharacter(code))
  12822. return;
  12823. this.error(`Missing expected ${String.fromCharCode(code)}`);
  12824. }
  12825. optionalOperator(op) {
  12826. if (this.next.isOperator(op)) {
  12827. this.advance();
  12828. return true;
  12829. }
  12830. else {
  12831. return false;
  12832. }
  12833. }
  12834. expectOperator(operator) {
  12835. if (this.optionalOperator(operator))
  12836. return;
  12837. this.error(`Missing expected operator ${operator}`);
  12838. }
  12839. expectIdentifierOrKeyword() {
  12840. const n = this.next;
  12841. if (!n.isIdentifier() && !n.isKeyword()) {
  12842. this.error(`Unexpected token ${n}, expected identifier or keyword`);
  12843. return '';
  12844. }
  12845. this.advance();
  12846. return n.toString();
  12847. }
  12848. expectIdentifierOrKeywordOrString() {
  12849. const n = this.next;
  12850. if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
  12851. this.error(`Unexpected token ${n}, expected identifier, keyword, or string`);
  12852. return '';
  12853. }
  12854. this.advance();
  12855. return n.toString();
  12856. }
  12857. parseChain() {
  12858. const exprs = [];
  12859. const start = this.inputIndex;
  12860. while (this.index < this.tokens.length) {
  12861. const expr = this.parsePipe();
  12862. exprs.push(expr);
  12863. if (this.optionalCharacter($SEMICOLON)) {
  12864. if (!this.parseAction) {
  12865. this.error('Binding expression cannot contain chained expression');
  12866. }
  12867. while (this.optionalCharacter($SEMICOLON)) {
  12868. } // read all semicolons
  12869. }
  12870. else if (this.index < this.tokens.length) {
  12871. this.error(`Unexpected token '${this.next}'`);
  12872. }
  12873. }
  12874. if (exprs.length == 0)
  12875. return new EmptyExpr(this.span(start));
  12876. if (exprs.length == 1)
  12877. return exprs[0];
  12878. return new Chain(this.span(start), exprs);
  12879. }
  12880. parsePipe() {
  12881. let result = this.parseExpression();
  12882. if (this.optionalOperator('|')) {
  12883. if (this.parseAction) {
  12884. this.error('Cannot have a pipe in an action expression');
  12885. }
  12886. do {
  12887. const name = this.expectIdentifierOrKeyword();
  12888. const args = [];
  12889. while (this.optionalCharacter($COLON)) {
  12890. args.push(this.parseExpression());
  12891. }
  12892. result = new BindingPipe(this.span(result.span.start), result, name, args);
  12893. } while (this.optionalOperator('|'));
  12894. }
  12895. return result;
  12896. }
  12897. parseExpression() { return this.parseConditional(); }
  12898. parseConditional() {
  12899. const start = this.inputIndex;
  12900. const result = this.parseLogicalOr();
  12901. if (this.optionalOperator('?')) {
  12902. const yes = this.parsePipe();
  12903. let no;
  12904. if (!this.optionalCharacter($COLON)) {
  12905. const end = this.inputIndex;
  12906. const expression = this.input.substring(start, end);
  12907. this.error(`Conditional expression ${expression} requires all 3 expressions`);
  12908. no = new EmptyExpr(this.span(start));
  12909. }
  12910. else {
  12911. no = this.parsePipe();
  12912. }
  12913. return new Conditional(this.span(start), result, yes, no);
  12914. }
  12915. else {
  12916. return result;
  12917. }
  12918. }
  12919. parseLogicalOr() {
  12920. // '||'
  12921. let result = this.parseLogicalAnd();
  12922. while (this.optionalOperator('||')) {
  12923. const right = this.parseLogicalAnd();
  12924. result = new Binary(this.span(result.span.start), '||', result, right);
  12925. }
  12926. return result;
  12927. }
  12928. parseLogicalAnd() {
  12929. // '&&'
  12930. let result = this.parseEquality();
  12931. while (this.optionalOperator('&&')) {
  12932. const right = this.parseEquality();
  12933. result = new Binary(this.span(result.span.start), '&&', result, right);
  12934. }
  12935. return result;
  12936. }
  12937. parseEquality() {
  12938. // '==','!=','===','!=='
  12939. let result = this.parseRelational();
  12940. while (this.next.type == TokenType$1.Operator) {
  12941. const operator = this.next.strValue;
  12942. switch (operator) {
  12943. case '==':
  12944. case '===':
  12945. case '!=':
  12946. case '!==':
  12947. this.advance();
  12948. const right = this.parseRelational();
  12949. result = new Binary(this.span(result.span.start), operator, result, right);
  12950. continue;
  12951. }
  12952. break;
  12953. }
  12954. return result;
  12955. }
  12956. parseRelational() {
  12957. // '<', '>', '<=', '>='
  12958. let result = this.parseAdditive();
  12959. while (this.next.type == TokenType$1.Operator) {
  12960. const operator = this.next.strValue;
  12961. switch (operator) {
  12962. case '<':
  12963. case '>':
  12964. case '<=':
  12965. case '>=':
  12966. this.advance();
  12967. const right = this.parseAdditive();
  12968. result = new Binary(this.span(result.span.start), operator, result, right);
  12969. continue;
  12970. }
  12971. break;
  12972. }
  12973. return result;
  12974. }
  12975. parseAdditive() {
  12976. // '+', '-'
  12977. let result = this.parseMultiplicative();
  12978. while (this.next.type == TokenType$1.Operator) {
  12979. const operator = this.next.strValue;
  12980. switch (operator) {
  12981. case '+':
  12982. case '-':
  12983. this.advance();
  12984. let right = this.parseMultiplicative();
  12985. result = new Binary(this.span(result.span.start), operator, result, right);
  12986. continue;
  12987. }
  12988. break;
  12989. }
  12990. return result;
  12991. }
  12992. parseMultiplicative() {
  12993. // '*', '%', '/'
  12994. let result = this.parsePrefix();
  12995. while (this.next.type == TokenType$1.Operator) {
  12996. const operator = this.next.strValue;
  12997. switch (operator) {
  12998. case '*':
  12999. case '%':
  13000. case '/':
  13001. this.advance();
  13002. let right = this.parsePrefix();
  13003. result = new Binary(this.span(result.span.start), operator, result, right);
  13004. continue;
  13005. }
  13006. break;
  13007. }
  13008. return result;
  13009. }
  13010. parsePrefix() {
  13011. if (this.next.type == TokenType$1.Operator) {
  13012. const start = this.inputIndex;
  13013. const operator = this.next.strValue;
  13014. let result;
  13015. switch (operator) {
  13016. case '+':
  13017. this.advance();
  13018. result = this.parsePrefix();
  13019. return new Binary(this.span(start), '-', result, new LiteralPrimitive(new ParseSpan(start, start), 0));
  13020. case '-':
  13021. this.advance();
  13022. result = this.parsePrefix();
  13023. return new Binary(this.span(start), operator, new LiteralPrimitive(new ParseSpan(start, start), 0), result);
  13024. case '!':
  13025. this.advance();
  13026. result = this.parsePrefix();
  13027. return new PrefixNot(this.span(start), result);
  13028. }
  13029. }
  13030. return this.parseCallChain();
  13031. }
  13032. parseCallChain() {
  13033. let result = this.parsePrimary();
  13034. while (true) {
  13035. if (this.optionalCharacter($PERIOD)) {
  13036. result = this.parseAccessMemberOrMethodCall(result, false);
  13037. }
  13038. else if (this.optionalOperator('?.')) {
  13039. result = this.parseAccessMemberOrMethodCall(result, true);
  13040. }
  13041. else if (this.optionalCharacter($LBRACKET)) {
  13042. this.rbracketsExpected++;
  13043. const key = this.parsePipe();
  13044. this.rbracketsExpected--;
  13045. this.expectCharacter($RBRACKET);
  13046. if (this.optionalOperator('=')) {
  13047. const value = this.parseConditional();
  13048. result = new KeyedWrite(this.span(result.span.start), result, key, value);
  13049. }
  13050. else {
  13051. result = new KeyedRead(this.span(result.span.start), result, key);
  13052. }
  13053. }
  13054. else if (this.optionalCharacter($LPAREN)) {
  13055. this.rparensExpected++;
  13056. const args = this.parseCallArguments();
  13057. this.rparensExpected--;
  13058. this.expectCharacter($RPAREN);
  13059. result = new FunctionCall(this.span(result.span.start), result, args);
  13060. }
  13061. else if (this.optionalOperator('!')) {
  13062. result = new NonNullAssert(this.span(result.span.start), result);
  13063. }
  13064. else {
  13065. return result;
  13066. }
  13067. }
  13068. }
  13069. parsePrimary() {
  13070. const start = this.inputIndex;
  13071. if (this.optionalCharacter($LPAREN)) {
  13072. this.rparensExpected++;
  13073. const result = this.parsePipe();
  13074. this.rparensExpected--;
  13075. this.expectCharacter($RPAREN);
  13076. return result;
  13077. }
  13078. else if (this.next.isKeywordNull()) {
  13079. this.advance();
  13080. return new LiteralPrimitive(this.span(start), null);
  13081. }
  13082. else if (this.next.isKeywordUndefined()) {
  13083. this.advance();
  13084. return new LiteralPrimitive(this.span(start), void 0);
  13085. }
  13086. else if (this.next.isKeywordTrue()) {
  13087. this.advance();
  13088. return new LiteralPrimitive(this.span(start), true);
  13089. }
  13090. else if (this.next.isKeywordFalse()) {
  13091. this.advance();
  13092. return new LiteralPrimitive(this.span(start), false);
  13093. }
  13094. else if (this.next.isKeywordThis()) {
  13095. this.advance();
  13096. return new ImplicitReceiver(this.span(start));
  13097. }
  13098. else if (this.optionalCharacter($LBRACKET)) {
  13099. this.rbracketsExpected++;
  13100. const elements = this.parseExpressionList($RBRACKET);
  13101. this.rbracketsExpected--;
  13102. this.expectCharacter($RBRACKET);
  13103. return new LiteralArray(this.span(start), elements);
  13104. }
  13105. else if (this.next.isCharacter($LBRACE)) {
  13106. return this.parseLiteralMap();
  13107. }
  13108. else if (this.next.isIdentifier()) {
  13109. return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start)), false);
  13110. }
  13111. else if (this.next.isNumber()) {
  13112. const value = this.next.toNumber();
  13113. this.advance();
  13114. return new LiteralPrimitive(this.span(start), value);
  13115. }
  13116. else if (this.next.isString()) {
  13117. const literalValue = this.next.toString();
  13118. this.advance();
  13119. return new LiteralPrimitive(this.span(start), literalValue);
  13120. }
  13121. else if (this.index >= this.tokens.length) {
  13122. this.error(`Unexpected end of expression: ${this.input}`);
  13123. return new EmptyExpr(this.span(start));
  13124. }
  13125. else {
  13126. this.error(`Unexpected token ${this.next}`);
  13127. return new EmptyExpr(this.span(start));
  13128. }
  13129. }
  13130. parseExpressionList(terminator) {
  13131. const result = [];
  13132. if (!this.next.isCharacter(terminator)) {
  13133. do {
  13134. result.push(this.parsePipe());
  13135. } while (this.optionalCharacter($COMMA));
  13136. }
  13137. return result;
  13138. }
  13139. parseLiteralMap() {
  13140. const keys = [];
  13141. const values = [];
  13142. const start = this.inputIndex;
  13143. this.expectCharacter($LBRACE);
  13144. if (!this.optionalCharacter($RBRACE)) {
  13145. this.rbracesExpected++;
  13146. do {
  13147. const quoted = this.next.isString();
  13148. const key = this.expectIdentifierOrKeywordOrString();
  13149. keys.push({ key, quoted });
  13150. this.expectCharacter($COLON);
  13151. values.push(this.parsePipe());
  13152. } while (this.optionalCharacter($COMMA));
  13153. this.rbracesExpected--;
  13154. this.expectCharacter($RBRACE);
  13155. }
  13156. return new LiteralMap(this.span(start), keys, values);
  13157. }
  13158. parseAccessMemberOrMethodCall(receiver, isSafe = false) {
  13159. const start = receiver.span.start;
  13160. const id = this.expectIdentifierOrKeyword();
  13161. if (this.optionalCharacter($LPAREN)) {
  13162. this.rparensExpected++;
  13163. const args = this.parseCallArguments();
  13164. this.expectCharacter($RPAREN);
  13165. this.rparensExpected--;
  13166. const span = this.span(start);
  13167. return isSafe ? new SafeMethodCall(span, receiver, id, args) :
  13168. new MethodCall(span, receiver, id, args);
  13169. }
  13170. else {
  13171. if (isSafe) {
  13172. if (this.optionalOperator('=')) {
  13173. this.error('The \'?.\' operator cannot be used in the assignment');
  13174. return new EmptyExpr(this.span(start));
  13175. }
  13176. else {
  13177. return new SafePropertyRead(this.span(start), receiver, id);
  13178. }
  13179. }
  13180. else {
  13181. if (this.optionalOperator('=')) {
  13182. if (!this.parseAction) {
  13183. this.error('Bindings cannot contain assignments');
  13184. return new EmptyExpr(this.span(start));
  13185. }
  13186. const value = this.parseConditional();
  13187. return new PropertyWrite(this.span(start), receiver, id, value);
  13188. }
  13189. else {
  13190. return new PropertyRead(this.span(start), receiver, id);
  13191. }
  13192. }
  13193. }
  13194. }
  13195. parseCallArguments() {
  13196. if (this.next.isCharacter($RPAREN))
  13197. return [];
  13198. const positionals = [];
  13199. do {
  13200. positionals.push(this.parsePipe());
  13201. } while (this.optionalCharacter($COMMA));
  13202. return positionals;
  13203. }
  13204. /**
  13205. * An identifier, a keyword, a string with an optional `-` in between.
  13206. */
  13207. expectTemplateBindingKey() {
  13208. let result = '';
  13209. let operatorFound = false;
  13210. do {
  13211. result += this.expectIdentifierOrKeywordOrString();
  13212. operatorFound = this.optionalOperator('-');
  13213. if (operatorFound) {
  13214. result += '-';
  13215. }
  13216. } while (operatorFound);
  13217. return result.toString();
  13218. }
  13219. // Parses the AST for `<some-tag *tplKey=AST>`
  13220. parseTemplateBindings(tplKey) {
  13221. let firstBinding = true;
  13222. const bindings = [];
  13223. const warnings = [];
  13224. do {
  13225. const start = this.inputIndex;
  13226. let rawKey;
  13227. let key;
  13228. let isVar = false;
  13229. if (firstBinding) {
  13230. rawKey = key = tplKey;
  13231. firstBinding = false;
  13232. }
  13233. else {
  13234. isVar = this.peekKeywordLet();
  13235. if (isVar)
  13236. this.advance();
  13237. rawKey = this.expectTemplateBindingKey();
  13238. key = isVar ? rawKey : tplKey + rawKey[0].toUpperCase() + rawKey.substring(1);
  13239. this.optionalCharacter($COLON);
  13240. }
  13241. let name = null;
  13242. let expression = null;
  13243. if (isVar) {
  13244. if (this.optionalOperator('=')) {
  13245. name = this.expectTemplateBindingKey();
  13246. }
  13247. else {
  13248. name = '\$implicit';
  13249. }
  13250. }
  13251. else if (this.peekKeywordAs()) {
  13252. this.advance(); // consume `as`
  13253. name = rawKey;
  13254. key = this.expectTemplateBindingKey(); // read local var name
  13255. isVar = true;
  13256. }
  13257. else if (this.next !== EOF && !this.peekKeywordLet()) {
  13258. const start = this.inputIndex;
  13259. const ast = this.parsePipe();
  13260. const source = this.input.substring(start - this.offset, this.inputIndex - this.offset);
  13261. expression = new ASTWithSource(ast, source, this.location, this.errors);
  13262. }
  13263. bindings.push(new TemplateBinding(this.span(start), key, isVar, name, expression));
  13264. if (this.peekKeywordAs() && !isVar) {
  13265. const letStart = this.inputIndex;
  13266. this.advance(); // consume `as`
  13267. const letName = this.expectTemplateBindingKey(); // read local var name
  13268. bindings.push(new TemplateBinding(this.span(letStart), letName, true, key, null));
  13269. }
  13270. if (!this.optionalCharacter($SEMICOLON)) {
  13271. this.optionalCharacter($COMMA);
  13272. }
  13273. } while (this.index < this.tokens.length);
  13274. return new TemplateBindingParseResult(bindings, warnings, this.errors);
  13275. }
  13276. error(message, index = null) {
  13277. this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
  13278. this.skip();
  13279. }
  13280. locationText(index = null) {
  13281. if (index == null)
  13282. index = this.index;
  13283. return (index < this.tokens.length) ? `at column ${this.tokens[index].index + 1} in` :
  13284. `at the end of the expression`;
  13285. }
  13286. // Error recovery should skip tokens until it encounters a recovery point. skip() treats
  13287. // the end of input and a ';' as unconditionally a recovery point. It also treats ')',
  13288. // '}' and ']' as conditional recovery points if one of calling productions is expecting
  13289. // one of these symbols. This allows skip() to recover from errors such as '(a.) + 1' allowing
  13290. // more of the AST to be retained (it doesn't skip any tokens as the ')' is retained because
  13291. // of the '(' begins an '(' <expr> ')' production). The recovery points of grouping symbols
  13292. // must be conditional as they must be skipped if none of the calling productions are not
  13293. // expecting the closing token else we will never make progress in the case of an
  13294. // extraneous group closing symbol (such as a stray ')'). This is not the case for ';' because
  13295. // parseChain() is always the root production and it expects a ';'.
  13296. // If a production expects one of these token it increments the corresponding nesting count,
  13297. // and then decrements it just prior to checking if the token is in the input.
  13298. skip() {
  13299. let n = this.next;
  13300. while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
  13301. (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
  13302. (this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
  13303. (this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET))) {
  13304. if (this.next.isError()) {
  13305. this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
  13306. }
  13307. this.advance();
  13308. n = this.next;
  13309. }
  13310. }
  13311. }
  13312. class SimpleExpressionChecker {
  13313. constructor() {
  13314. this.errors = [];
  13315. }
  13316. static check(ast) {
  13317. const s = new SimpleExpressionChecker();
  13318. ast.visit(s);
  13319. return s.errors;
  13320. }
  13321. visitImplicitReceiver(ast, context) { }
  13322. visitInterpolation(ast, context) { }
  13323. visitLiteralPrimitive(ast, context) { }
  13324. visitPropertyRead(ast, context) { }
  13325. visitPropertyWrite(ast, context) { }
  13326. visitSafePropertyRead(ast, context) { }
  13327. visitMethodCall(ast, context) { }
  13328. visitSafeMethodCall(ast, context) { }
  13329. visitFunctionCall(ast, context) { }
  13330. visitLiteralArray(ast, context) { this.visitAll(ast.expressions); }
  13331. visitLiteralMap(ast, context) { this.visitAll(ast.values); }
  13332. visitBinary(ast, context) { }
  13333. visitPrefixNot(ast, context) { }
  13334. visitNonNullAssert(ast, context) { }
  13335. visitConditional(ast, context) { }
  13336. visitPipe(ast, context) { this.errors.push('pipes'); }
  13337. visitKeyedRead(ast, context) { }
  13338. visitKeyedWrite(ast, context) { }
  13339. visitAll(asts) { return asts.map(node => node.visit(this)); }
  13340. visitChain(ast, context) { }
  13341. visitQuote(ast, context) { }
  13342. }
  13343. /**
  13344. * @license
  13345. * Copyright Google Inc. All Rights Reserved.
  13346. *
  13347. * Use of this source code is governed by an MIT-style license that can be
  13348. * found in the LICENSE file at https://angular.io/license
  13349. */
  13350. // =================================================================================================
  13351. // =================================================================================================
  13352. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  13353. // =================================================================================================
  13354. // =================================================================================================
  13355. //
  13356. // DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
  13357. // Reach out to mprobst for details.
  13358. //
  13359. // =================================================================================================
  13360. /** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
  13361. let _SECURITY_SCHEMA;
  13362. function SECURITY_SCHEMA() {
  13363. if (!_SECURITY_SCHEMA) {
  13364. _SECURITY_SCHEMA = {};
  13365. // Case is insignificant below, all element and attribute names are lower-cased for lookup.
  13366. registerContext(SecurityContext.HTML, [
  13367. 'iframe|srcdoc',
  13368. '*|innerHTML',
  13369. '*|outerHTML',
  13370. ]);
  13371. registerContext(SecurityContext.STYLE, ['*|style']);
  13372. // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
  13373. registerContext(SecurityContext.URL, [
  13374. '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
  13375. 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
  13376. 'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
  13377. 'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
  13378. ]);
  13379. registerContext(SecurityContext.RESOURCE_URL, [
  13380. 'applet|code',
  13381. 'applet|codebase',
  13382. 'base|href',
  13383. 'embed|src',
  13384. 'frame|src',
  13385. 'head|profile',
  13386. 'html|manifest',
  13387. 'iframe|src',
  13388. 'link|href',
  13389. 'media|src',
  13390. 'object|codebase',
  13391. 'object|data',
  13392. 'script|src',
  13393. ]);
  13394. }
  13395. return _SECURITY_SCHEMA;
  13396. }
  13397. function registerContext(ctx, specs) {
  13398. for (const spec of specs)
  13399. _SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
  13400. }
  13401. /**
  13402. * @license
  13403. * Copyright Google Inc. All Rights Reserved.
  13404. *
  13405. * Use of this source code is governed by an MIT-style license that can be
  13406. * found in the LICENSE file at https://angular.io/license
  13407. */
  13408. class ElementSchemaRegistry {
  13409. }
  13410. /**
  13411. * @license
  13412. * Copyright Google Inc. All Rights Reserved.
  13413. *
  13414. * Use of this source code is governed by an MIT-style license that can be
  13415. * found in the LICENSE file at https://angular.io/license
  13416. */
  13417. const BOOLEAN = 'boolean';
  13418. const NUMBER = 'number';
  13419. const STRING = 'string';
  13420. const OBJECT = 'object';
  13421. /**
  13422. * This array represents the DOM schema. It encodes inheritance, properties, and events.
  13423. *
  13424. * ## Overview
  13425. *
  13426. * Each line represents one kind of element. The `element_inheritance` and properties are joined
  13427. * using `element_inheritance|properties` syntax.
  13428. *
  13429. * ## Element Inheritance
  13430. *
  13431. * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
  13432. * Here the individual elements are separated by `,` (commas). Every element in the list
  13433. * has identical properties.
  13434. *
  13435. * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
  13436. * specified then `""` (blank) element is assumed.
  13437. *
  13438. * NOTE: The blank element inherits from root `[Element]` element, the super element of all
  13439. * elements.
  13440. *
  13441. * NOTE an element prefix such as `:svg:` has no special meaning to the schema.
  13442. *
  13443. * ## Properties
  13444. *
  13445. * Each element has a set of properties separated by `,` (commas). Each property can be prefixed
  13446. * by a special character designating its type:
  13447. *
  13448. * - (no prefix): property is a string.
  13449. * - `*`: property represents an event.
  13450. * - `!`: property is a boolean.
  13451. * - `#`: property is a number.
  13452. * - `%`: property is an object.
  13453. *
  13454. * ## Query
  13455. *
  13456. * The class creates an internal squas representation which allows to easily answer the query of
  13457. * if a given property exist on a given element.
  13458. *
  13459. * NOTE: We don't yet support querying for types or events.
  13460. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
  13461. * see dom_element_schema_registry_spec.ts
  13462. */
  13463. // =================================================================================================
  13464. // =================================================================================================
  13465. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  13466. // =================================================================================================
  13467. // =================================================================================================
  13468. //
  13469. // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
  13470. //
  13471. // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
  13472. // dom_security_schema.ts. Reach out to mprobst & rjamet for details.
  13473. //
  13474. // =================================================================================================
  13475. const SCHEMA = [
  13476. '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
  13477. /* added manually to avoid breaking changes */
  13478. ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
  13479. '[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',
  13480. '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',
  13481. 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
  13482. ':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',
  13483. ':svg:graphics^:svg:|',
  13484. ':svg:animation^:svg:|*begin,*end,*repeat',
  13485. ':svg:geometry^:svg:|',
  13486. ':svg:componentTransferFunction^:svg:|',
  13487. ':svg:gradient^:svg:|',
  13488. ':svg:textContent^:svg:graphics|',
  13489. ':svg:textPositioning^:svg:textContent|',
  13490. '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',
  13491. 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
  13492. 'audio^media|',
  13493. 'br^[HTMLElement]|clear',
  13494. 'base^[HTMLElement]|href,target',
  13495. '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',
  13496. 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
  13497. 'canvas^[HTMLElement]|#height,#width',
  13498. 'content^[HTMLElement]|select',
  13499. 'dl^[HTMLElement]|!compact',
  13500. 'datalist^[HTMLElement]|',
  13501. 'details^[HTMLElement]|!open',
  13502. 'dialog^[HTMLElement]|!open,returnValue',
  13503. 'dir^[HTMLElement]|!compact',
  13504. 'div^[HTMLElement]|align',
  13505. 'embed^[HTMLElement]|align,height,name,src,type,width',
  13506. 'fieldset^[HTMLElement]|!disabled,name',
  13507. 'font^[HTMLElement]|color,face,size',
  13508. 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
  13509. 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
  13510. 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
  13511. 'hr^[HTMLElement]|align,color,!noShade,size,width',
  13512. 'head^[HTMLElement]|',
  13513. 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
  13514. 'html^[HTMLElement]|version',
  13515. 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
  13516. 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
  13517. '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',
  13518. 'li^[HTMLElement]|type,#value',
  13519. 'label^[HTMLElement]|htmlFor',
  13520. 'legend^[HTMLElement]|align',
  13521. 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
  13522. 'map^[HTMLElement]|name',
  13523. 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
  13524. 'menu^[HTMLElement]|!compact',
  13525. 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
  13526. 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
  13527. 'ins,del^[HTMLElement]|cite,dateTime',
  13528. 'ol^[HTMLElement]|!compact,!reversed,#start,type',
  13529. 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
  13530. 'optgroup^[HTMLElement]|!disabled,label',
  13531. 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
  13532. 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
  13533. 'p^[HTMLElement]|align',
  13534. 'param^[HTMLElement]|name,type,value,valueType',
  13535. 'picture^[HTMLElement]|',
  13536. 'pre^[HTMLElement]|#width',
  13537. 'progress^[HTMLElement]|#max,#value',
  13538. 'q,blockquote,cite^[HTMLElement]|',
  13539. 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
  13540. 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
  13541. 'shadow^[HTMLElement]|',
  13542. 'slot^[HTMLElement]|name',
  13543. 'source^[HTMLElement]|media,sizes,src,srcset,type',
  13544. 'span^[HTMLElement]|',
  13545. 'style^[HTMLElement]|!disabled,media,type',
  13546. 'caption^[HTMLElement]|align',
  13547. 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
  13548. 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
  13549. 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
  13550. 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
  13551. 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
  13552. 'template^[HTMLElement]|',
  13553. 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
  13554. 'title^[HTMLElement]|text',
  13555. 'track^[HTMLElement]|!default,kind,label,src,srclang',
  13556. 'ul^[HTMLElement]|!compact,type',
  13557. 'unknown^[HTMLElement]|',
  13558. 'video^media|#height,poster,#width',
  13559. ':svg:a^:svg:graphics|',
  13560. ':svg:animate^:svg:animation|',
  13561. ':svg:animateMotion^:svg:animation|',
  13562. ':svg:animateTransform^:svg:animation|',
  13563. ':svg:circle^:svg:geometry|',
  13564. ':svg:clipPath^:svg:graphics|',
  13565. ':svg:defs^:svg:graphics|',
  13566. ':svg:desc^:svg:|',
  13567. ':svg:discard^:svg:|',
  13568. ':svg:ellipse^:svg:geometry|',
  13569. ':svg:feBlend^:svg:|',
  13570. ':svg:feColorMatrix^:svg:|',
  13571. ':svg:feComponentTransfer^:svg:|',
  13572. ':svg:feComposite^:svg:|',
  13573. ':svg:feConvolveMatrix^:svg:|',
  13574. ':svg:feDiffuseLighting^:svg:|',
  13575. ':svg:feDisplacementMap^:svg:|',
  13576. ':svg:feDistantLight^:svg:|',
  13577. ':svg:feDropShadow^:svg:|',
  13578. ':svg:feFlood^:svg:|',
  13579. ':svg:feFuncA^:svg:componentTransferFunction|',
  13580. ':svg:feFuncB^:svg:componentTransferFunction|',
  13581. ':svg:feFuncG^:svg:componentTransferFunction|',
  13582. ':svg:feFuncR^:svg:componentTransferFunction|',
  13583. ':svg:feGaussianBlur^:svg:|',
  13584. ':svg:feImage^:svg:|',
  13585. ':svg:feMerge^:svg:|',
  13586. ':svg:feMergeNode^:svg:|',
  13587. ':svg:feMorphology^:svg:|',
  13588. ':svg:feOffset^:svg:|',
  13589. ':svg:fePointLight^:svg:|',
  13590. ':svg:feSpecularLighting^:svg:|',
  13591. ':svg:feSpotLight^:svg:|',
  13592. ':svg:feTile^:svg:|',
  13593. ':svg:feTurbulence^:svg:|',
  13594. ':svg:filter^:svg:|',
  13595. ':svg:foreignObject^:svg:graphics|',
  13596. ':svg:g^:svg:graphics|',
  13597. ':svg:image^:svg:graphics|',
  13598. ':svg:line^:svg:geometry|',
  13599. ':svg:linearGradient^:svg:gradient|',
  13600. ':svg:mpath^:svg:|',
  13601. ':svg:marker^:svg:|',
  13602. ':svg:mask^:svg:|',
  13603. ':svg:metadata^:svg:|',
  13604. ':svg:path^:svg:geometry|',
  13605. ':svg:pattern^:svg:|',
  13606. ':svg:polygon^:svg:geometry|',
  13607. ':svg:polyline^:svg:geometry|',
  13608. ':svg:radialGradient^:svg:gradient|',
  13609. ':svg:rect^:svg:geometry|',
  13610. ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
  13611. ':svg:script^:svg:|type',
  13612. ':svg:set^:svg:animation|',
  13613. ':svg:stop^:svg:|',
  13614. ':svg:style^:svg:|!disabled,media,title,type',
  13615. ':svg:switch^:svg:graphics|',
  13616. ':svg:symbol^:svg:|',
  13617. ':svg:tspan^:svg:textPositioning|',
  13618. ':svg:text^:svg:textPositioning|',
  13619. ':svg:textPath^:svg:textContent|',
  13620. ':svg:title^:svg:|',
  13621. ':svg:use^:svg:graphics|',
  13622. ':svg:view^:svg:|#zoomAndPan',
  13623. 'data^[HTMLElement]|value',
  13624. 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
  13625. 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
  13626. 'summary^[HTMLElement]|',
  13627. 'time^[HTMLElement]|dateTime',
  13628. ':svg:cursor^:svg:|',
  13629. ];
  13630. const _ATTR_TO_PROP = {
  13631. 'class': 'className',
  13632. 'for': 'htmlFor',
  13633. 'formaction': 'formAction',
  13634. 'innerHtml': 'innerHTML',
  13635. 'readonly': 'readOnly',
  13636. 'tabindex': 'tabIndex',
  13637. };
  13638. class DomElementSchemaRegistry extends ElementSchemaRegistry {
  13639. constructor() {
  13640. super();
  13641. this._schema = {};
  13642. SCHEMA.forEach(encodedType => {
  13643. const type = {};
  13644. const [strType, strProperties] = encodedType.split('|');
  13645. const properties = strProperties.split(',');
  13646. const [typeNames, superName] = strType.split('^');
  13647. typeNames.split(',').forEach(tag => this._schema[tag.toLowerCase()] = type);
  13648. const superType = superName && this._schema[superName.toLowerCase()];
  13649. if (superType) {
  13650. Object.keys(superType).forEach((prop) => { type[prop] = superType[prop]; });
  13651. }
  13652. properties.forEach((property) => {
  13653. if (property.length > 0) {
  13654. switch (property[0]) {
  13655. case '*':
  13656. // We don't yet support events.
  13657. // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
  13658. // will
  13659. // almost certainly introduce bad XSS vulnerabilities.
  13660. // type[property.substring(1)] = EVENT;
  13661. break;
  13662. case '!':
  13663. type[property.substring(1)] = BOOLEAN;
  13664. break;
  13665. case '#':
  13666. type[property.substring(1)] = NUMBER;
  13667. break;
  13668. case '%':
  13669. type[property.substring(1)] = OBJECT;
  13670. break;
  13671. default:
  13672. type[property] = STRING;
  13673. }
  13674. }
  13675. });
  13676. });
  13677. }
  13678. hasProperty(tagName, propName, schemaMetas) {
  13679. if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) {
  13680. return true;
  13681. }
  13682. if (tagName.indexOf('-') > -1) {
  13683. if (isNgContainer(tagName) || isNgContent(tagName)) {
  13684. return false;
  13685. }
  13686. if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) {
  13687. // Can't tell now as we don't know which properties a custom element will get
  13688. // once it is instantiated
  13689. return true;
  13690. }
  13691. }
  13692. const elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
  13693. return !!elementProperties[propName];
  13694. }
  13695. hasElement(tagName, schemaMetas) {
  13696. if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) {
  13697. return true;
  13698. }
  13699. if (tagName.indexOf('-') > -1) {
  13700. if (isNgContainer(tagName) || isNgContent(tagName)) {
  13701. return true;
  13702. }
  13703. if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) {
  13704. // Allow any custom elements
  13705. return true;
  13706. }
  13707. }
  13708. return !!this._schema[tagName.toLowerCase()];
  13709. }
  13710. /**
  13711. * securityContext returns the security context for the given property on the given DOM tag.
  13712. *
  13713. * Tag and property name are statically known and cannot change at runtime, i.e. it is not
  13714. * possible to bind a value into a changing attribute or tag name.
  13715. *
  13716. * The filtering is based on a list of allowed tags|attributes. All attributes in the schema
  13717. * above are assumed to have the 'NONE' security context, i.e. that they are safe inert
  13718. * string values. Only specific well known attack vectors are assigned their appropriate context.
  13719. */
  13720. securityContext(tagName, propName, isAttribute) {
  13721. if (isAttribute) {
  13722. // NB: For security purposes, use the mapped property name, not the attribute name.
  13723. propName = this.getMappedPropName(propName);
  13724. }
  13725. // Make sure comparisons are case insensitive, so that case differences between attribute and
  13726. // property names do not have a security impact.
  13727. tagName = tagName.toLowerCase();
  13728. propName = propName.toLowerCase();
  13729. let ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
  13730. if (ctx) {
  13731. return ctx;
  13732. }
  13733. ctx = SECURITY_SCHEMA()['*|' + propName];
  13734. return ctx ? ctx : SecurityContext.NONE;
  13735. }
  13736. getMappedPropName(propName) { return _ATTR_TO_PROP[propName] || propName; }
  13737. getDefaultComponentElementName() { return 'ng-component'; }
  13738. validateProperty(name) {
  13739. if (name.toLowerCase().startsWith('on')) {
  13740. const msg = `Binding to event property '${name}' is disallowed for security reasons, ` +
  13741. `please use (${name.slice(2)})=...` +
  13742. `\nIf '${name}' is a directive input, make sure the directive is imported by the` +
  13743. ` current module.`;
  13744. return { error: true, msg: msg };
  13745. }
  13746. else {
  13747. return { error: false };
  13748. }
  13749. }
  13750. validateAttribute(name) {
  13751. if (name.toLowerCase().startsWith('on')) {
  13752. const msg = `Binding to event attribute '${name}' is disallowed for security reasons, ` +
  13753. `please use (${name.slice(2)})=...`;
  13754. return { error: true, msg: msg };
  13755. }
  13756. else {
  13757. return { error: false };
  13758. }
  13759. }
  13760. allKnownElementNames() { return Object.keys(this._schema); }
  13761. normalizeAnimationStyleProperty(propName) {
  13762. return dashCaseToCamelCase(propName);
  13763. }
  13764. normalizeAnimationStyleValue(camelCaseProp, userProvidedProp, val) {
  13765. let unit = '';
  13766. const strVal = val.toString().trim();
  13767. let errorMsg = null;
  13768. if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
  13769. if (typeof val === 'number') {
  13770. unit = 'px';
  13771. }
  13772. else {
  13773. const valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
  13774. if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
  13775. errorMsg = `Please provide a CSS unit value for ${userProvidedProp}:${val}`;
  13776. }
  13777. }
  13778. }
  13779. return { error: errorMsg, value: strVal + unit };
  13780. }
  13781. }
  13782. function _isPixelDimensionStyle(prop) {
  13783. switch (prop) {
  13784. case 'width':
  13785. case 'height':
  13786. case 'minWidth':
  13787. case 'minHeight':
  13788. case 'maxWidth':
  13789. case 'maxHeight':
  13790. case 'left':
  13791. case 'top':
  13792. case 'bottom':
  13793. case 'right':
  13794. case 'fontSize':
  13795. case 'outlineWidth':
  13796. case 'outlineOffset':
  13797. case 'paddingTop':
  13798. case 'paddingLeft':
  13799. case 'paddingBottom':
  13800. case 'paddingRight':
  13801. case 'marginTop':
  13802. case 'marginLeft':
  13803. case 'marginBottom':
  13804. case 'marginRight':
  13805. case 'borderRadius':
  13806. case 'borderWidth':
  13807. case 'borderTopWidth':
  13808. case 'borderLeftWidth':
  13809. case 'borderRightWidth':
  13810. case 'borderBottomWidth':
  13811. case 'textIndent':
  13812. return true;
  13813. default:
  13814. return false;
  13815. }
  13816. }
  13817. /**
  13818. * @license
  13819. * Copyright Google Inc. All Rights Reserved.
  13820. *
  13821. * Use of this source code is governed by an MIT-style license that can be
  13822. * found in the LICENSE file at https://angular.io/license
  13823. */
  13824. const BIND_NAME_REGEXP$1 = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  13825. // Group 1 = "bind-"
  13826. const KW_BIND_IDX$1 = 1;
  13827. // Group 2 = "let-"
  13828. const KW_LET_IDX$1 = 2;
  13829. // Group 3 = "ref-/#"
  13830. const KW_REF_IDX$1 = 3;
  13831. // Group 4 = "on-"
  13832. const KW_ON_IDX$1 = 4;
  13833. // Group 5 = "bindon-"
  13834. const KW_BINDON_IDX$1 = 5;
  13835. // Group 6 = "@"
  13836. const KW_AT_IDX$1 = 6;
  13837. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  13838. const IDENT_KW_IDX$1 = 7;
  13839. // Group 8 = identifier inside [()]
  13840. const IDENT_BANANA_BOX_IDX$1 = 8;
  13841. // Group 9 = identifier inside []
  13842. const IDENT_PROPERTY_IDX$1 = 9;
  13843. // Group 10 = identifier inside ()
  13844. const IDENT_EVENT_IDX$1 = 10;
  13845. const TEMPLATE_ATTR_PREFIX$1 = '*';
  13846. function htmlAstToRender3Ast(htmlNodes, bindingParser) {
  13847. const transformer = new HtmlAstToIvyAst(bindingParser);
  13848. const ivyNodes = visitAll$1(transformer, htmlNodes);
  13849. // Errors might originate in either the binding parser or the html to ivy transformer
  13850. const allErrors = bindingParser.errors.concat(transformer.errors);
  13851. const errors = allErrors.filter(e => e.level === ParseErrorLevel.ERROR);
  13852. if (errors.length > 0) {
  13853. const errorString = errors.join('\n');
  13854. throw syntaxError(`Template parse errors:\n${errorString}`, errors);
  13855. }
  13856. return {
  13857. nodes: ivyNodes,
  13858. errors: allErrors,
  13859. styleUrls: transformer.styleUrls,
  13860. styles: transformer.styles,
  13861. };
  13862. }
  13863. class HtmlAstToIvyAst {
  13864. constructor(bindingParser) {
  13865. this.bindingParser = bindingParser;
  13866. this.errors = [];
  13867. this.styles = [];
  13868. this.styleUrls = [];
  13869. }
  13870. // HTML visitor
  13871. visitElement(element) {
  13872. const preparsedElement = preparseElement(element);
  13873. if (preparsedElement.type === PreparsedElementType.SCRIPT) {
  13874. return null;
  13875. }
  13876. else if (preparsedElement.type === PreparsedElementType.STYLE) {
  13877. const contents = textContents(element);
  13878. if (contents !== null) {
  13879. this.styles.push(contents);
  13880. }
  13881. return null;
  13882. }
  13883. else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  13884. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  13885. this.styleUrls.push(preparsedElement.hrefAttr);
  13886. return null;
  13887. }
  13888. // Whether the element is a `<ng-template>`
  13889. const isTemplateElement = isNgTemplate(element.name);
  13890. const parsedProperties = [];
  13891. const boundEvents = [];
  13892. const variables = [];
  13893. const references = [];
  13894. const attributes = [];
  13895. const i18nAttrsMeta = {};
  13896. const templateParsedProperties = [];
  13897. const templateVariables = [];
  13898. // Whether the element has any *-attribute
  13899. let elementHasInlineTemplate = false;
  13900. for (const attribute of element.attrs) {
  13901. let hasBinding = false;
  13902. const normalizedName = normalizeAttributeName(attribute.name);
  13903. // `*attr` defines template bindings
  13904. let isTemplateBinding = false;
  13905. if (attribute.i18n) {
  13906. i18nAttrsMeta[attribute.name] = attribute.i18n;
  13907. }
  13908. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
  13909. // *-attributes
  13910. if (elementHasInlineTemplate) {
  13911. this.reportError(`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`, attribute.sourceSpan);
  13912. }
  13913. isTemplateBinding = true;
  13914. elementHasInlineTemplate = true;
  13915. const templateValue = attribute.value;
  13916. const templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
  13917. const parsedVariables = [];
  13918. this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, [], templateParsedProperties, parsedVariables);
  13919. templateVariables.push(...parsedVariables.map(v => new Variable(v.name, v.value, v.sourceSpan)));
  13920. }
  13921. else {
  13922. // Check for variables, events, property bindings, interpolation
  13923. hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
  13924. }
  13925. if (!hasBinding && !isTemplateBinding) {
  13926. // don't include the bindings as attributes as well in the AST
  13927. attributes.push(this.visitAttribute(attribute));
  13928. }
  13929. }
  13930. const children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
  13931. let parsedElement;
  13932. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  13933. // `<ng-content>`
  13934. if (element.children &&
  13935. !element.children.every((node) => isEmptyTextNode(node) || isCommentNode(node))) {
  13936. this.reportError(`<ng-content> element cannot have content.`, element.sourceSpan);
  13937. }
  13938. const selector = preparsedElement.selectAttr;
  13939. const attrs = element.attrs.map(attr => this.visitAttribute(attr));
  13940. parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
  13941. }
  13942. else if (isTemplateElement) {
  13943. // `<ng-template>`
  13944. const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  13945. parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  13946. }
  13947. else {
  13948. const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  13949. parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  13950. }
  13951. if (elementHasInlineTemplate) {
  13952. // If this node is an inline-template (e.g. has *ngFor) then we need to create a template
  13953. // node that contains this node.
  13954. // Moreover, if the node is an element, then we need to hoist its attributes to the template
  13955. // node for matching against content projection selectors.
  13956. const attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
  13957. const templateAttrs = [];
  13958. attrs.literal.forEach(attr => templateAttrs.push(attr));
  13959. attrs.bound.forEach(attr => templateAttrs.push(attr));
  13960. const hoistedAttrs = parsedElement instanceof Element ?
  13961. {
  13962. attributes: parsedElement.attributes,
  13963. inputs: parsedElement.inputs,
  13964. outputs: parsedElement.outputs,
  13965. } :
  13966. { attributes: [], inputs: [], outputs: [] };
  13967. // TODO(pk): test for this case
  13968. parsedElement = new Template(parsedElement.name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs, [parsedElement], [ /* no references */], templateVariables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  13969. }
  13970. return parsedElement;
  13971. }
  13972. visitAttribute(attribute) {
  13973. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.valueSpan, attribute.i18n);
  13974. }
  13975. visitText(text) {
  13976. return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
  13977. }
  13978. visitExpansion(expansion) {
  13979. const meta = expansion.i18n;
  13980. // do not generate Icu in case it was created
  13981. // outside of i18n block in a template
  13982. if (!meta) {
  13983. return null;
  13984. }
  13985. const vars = {};
  13986. const placeholders = {};
  13987. // extract VARs from ICUs - we process them separately while
  13988. // assembling resulting message via goog.getMsg function, since
  13989. // we need to pass them to top-level goog.getMsg call
  13990. Object.keys(meta.placeholders).forEach(key => {
  13991. const value = meta.placeholders[key];
  13992. if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
  13993. const config = this.bindingParser.interpolationConfig;
  13994. // ICU expression is a plain string, not wrapped into start
  13995. // and end tags, so we wrap it before passing to binding parser
  13996. const wrapped = `${config.start}${value}${config.end}`;
  13997. vars[key] = this._visitTextWithInterpolation(wrapped, expansion.sourceSpan);
  13998. }
  13999. else {
  14000. placeholders[key] = this._visitTextWithInterpolation(value, expansion.sourceSpan);
  14001. }
  14002. });
  14003. return new Icu(vars, placeholders, expansion.sourceSpan, meta);
  14004. }
  14005. visitExpansionCase(expansionCase) { return null; }
  14006. visitComment(comment) { return null; }
  14007. // convert view engine `ParsedProperty` to a format suitable for IVY
  14008. extractAttributes(elementName, properties, i18nPropsMeta) {
  14009. const bound = [];
  14010. const literal = [];
  14011. properties.forEach(prop => {
  14012. const i18n = i18nPropsMeta[prop.name];
  14013. if (prop.isLiteral) {
  14014. literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, undefined, i18n));
  14015. }
  14016. else {
  14017. // Note that validation is skipped and property mapping is disabled
  14018. // due to the fact that we need to make sure a given prop is not an
  14019. // input of a directive and directive matching happens at runtime.
  14020. const bep = this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
  14021. bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
  14022. }
  14023. });
  14024. return { bound, literal };
  14025. }
  14026. parseAttribute(isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
  14027. const name = normalizeAttributeName(attribute.name);
  14028. const value = attribute.value;
  14029. const srcSpan = attribute.sourceSpan;
  14030. const bindParts = name.match(BIND_NAME_REGEXP$1);
  14031. let hasBinding = false;
  14032. if (bindParts) {
  14033. hasBinding = true;
  14034. if (bindParts[KW_BIND_IDX$1] != null) {
  14035. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14036. }
  14037. else if (bindParts[KW_LET_IDX$1]) {
  14038. if (isTemplateElement) {
  14039. const identifier = bindParts[IDENT_KW_IDX$1];
  14040. this.parseVariable(identifier, value, srcSpan, variables);
  14041. }
  14042. else {
  14043. this.reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
  14044. }
  14045. }
  14046. else if (bindParts[KW_REF_IDX$1]) {
  14047. const identifier = bindParts[IDENT_KW_IDX$1];
  14048. this.parseReference(identifier, value, srcSpan, references);
  14049. }
  14050. else if (bindParts[KW_ON_IDX$1]) {
  14051. const events = [];
  14052. this.bindingParser.parseEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14053. addEvents(events, boundEvents);
  14054. }
  14055. else if (bindParts[KW_BINDON_IDX$1]) {
  14056. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14057. this.parseAssignmentEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14058. }
  14059. else if (bindParts[KW_AT_IDX$1]) {
  14060. this.bindingParser.parseLiteralAttr(name, value, srcSpan, matchableAttributes, parsedProperties);
  14061. }
  14062. else if (bindParts[IDENT_BANANA_BOX_IDX$1]) {
  14063. this.bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14064. this.parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14065. }
  14066. else if (bindParts[IDENT_PROPERTY_IDX$1]) {
  14067. this.bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14068. }
  14069. else if (bindParts[IDENT_EVENT_IDX$1]) {
  14070. const events = [];
  14071. this.bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14072. addEvents(events, boundEvents);
  14073. }
  14074. }
  14075. else {
  14076. hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, matchableAttributes, parsedProperties);
  14077. }
  14078. return hasBinding;
  14079. }
  14080. _visitTextWithInterpolation(value, sourceSpan, i18n) {
  14081. const valueNoNgsp = replaceNgsp(value);
  14082. const expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
  14083. return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
  14084. }
  14085. parseVariable(identifier, value, sourceSpan, variables) {
  14086. if (identifier.indexOf('-') > -1) {
  14087. this.reportError(`"-" is not allowed in variable names`, sourceSpan);
  14088. }
  14089. variables.push(new Variable(identifier, value, sourceSpan));
  14090. }
  14091. parseReference(identifier, value, sourceSpan, references) {
  14092. if (identifier.indexOf('-') > -1) {
  14093. this.reportError(`"-" is not allowed in reference names`, sourceSpan);
  14094. }
  14095. references.push(new Reference(identifier, value, sourceSpan));
  14096. }
  14097. parseAssignmentEvent(name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents) {
  14098. const events = [];
  14099. this.bindingParser.parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events);
  14100. addEvents(events, boundEvents);
  14101. }
  14102. reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
  14103. this.errors.push(new ParseError(sourceSpan, message, level));
  14104. }
  14105. }
  14106. class NonBindableVisitor$1 {
  14107. visitElement(ast) {
  14108. const preparsedElement = preparseElement(ast);
  14109. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  14110. preparsedElement.type === PreparsedElementType.STYLE ||
  14111. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  14112. // Skipping <script> for security reasons
  14113. // Skipping <style> and stylesheets as we already processed them
  14114. // in the StyleCompiler
  14115. return null;
  14116. }
  14117. const children = visitAll$1(this, ast.children, null);
  14118. return new Element(ast.name, visitAll$1(this, ast.attrs),
  14119. /* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
  14120. }
  14121. visitComment(comment) { return null; }
  14122. visitAttribute(attribute) {
  14123. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, undefined, attribute.i18n);
  14124. }
  14125. visitText(text) { return new Text(text.value, text.sourceSpan); }
  14126. visitExpansion(expansion) { return null; }
  14127. visitExpansionCase(expansionCase) { return null; }
  14128. }
  14129. const NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
  14130. function normalizeAttributeName(attrName) {
  14131. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  14132. }
  14133. function addEvents(events, boundEvents) {
  14134. boundEvents.push(...events.map(e => BoundEvent.fromParsedEvent(e)));
  14135. }
  14136. function isEmptyTextNode(node) {
  14137. return node instanceof Text$3 && node.value.trim().length == 0;
  14138. }
  14139. function isCommentNode(node) {
  14140. return node instanceof Comment;
  14141. }
  14142. function textContents(node) {
  14143. if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
  14144. return null;
  14145. }
  14146. else {
  14147. return node.children[0].value;
  14148. }
  14149. }
  14150. /**
  14151. * @license
  14152. * Copyright Google Inc. All Rights Reserved.
  14153. *
  14154. * Use of this source code is governed by an MIT-style license that can be
  14155. * found in the LICENSE file at https://angular.io/license
  14156. */
  14157. var TagType;
  14158. (function (TagType) {
  14159. TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
  14160. TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
  14161. TagType[TagType["PROJECTION"] = 2] = "PROJECTION";
  14162. })(TagType || (TagType = {}));
  14163. /**
  14164. * Generates an object that is used as a shared state between parent and all child contexts.
  14165. */
  14166. function setupRegistry() {
  14167. return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
  14168. }
  14169. /**
  14170. * I18nContext is a helper class which keeps track of all i18n-related aspects
  14171. * (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
  14172. *
  14173. * When we enter a nested template, the top-level context is being passed down
  14174. * to the nested component, which uses this context to generate a child instance
  14175. * of I18nContext class (to handle nested template) and at the end, reconciles it back
  14176. * with the parent context.
  14177. *
  14178. * @param index Instruction index of i18nStart, which initiates this context
  14179. * @param ref Reference to a translation const that represents the content if thus context
  14180. * @param level Nestng level defined for child contexts
  14181. * @param templateIndex Instruction index of a template which this context belongs to
  14182. * @param meta Meta information (id, meaning, description, etc) associated with this context
  14183. */
  14184. class I18nContext {
  14185. constructor(index, ref, level = 0, templateIndex = null, meta, registry) {
  14186. this.index = index;
  14187. this.ref = ref;
  14188. this.level = level;
  14189. this.templateIndex = templateIndex;
  14190. this.meta = meta;
  14191. this.registry = registry;
  14192. this.bindings = new Set();
  14193. this.placeholders = new Map();
  14194. this.isEmitted = false;
  14195. this._unresolvedCtxCount = 0;
  14196. this._registry = registry || setupRegistry();
  14197. this.id = this._registry.getUniqueId();
  14198. }
  14199. appendTag(type, node, index, closed) {
  14200. if (node.isVoid && closed) {
  14201. return; // ignore "close" for void tags
  14202. }
  14203. const ph = node.isVoid || !closed ? node.startName : node.closeName;
  14204. const content = { type, index, ctx: this.id, isVoid: node.isVoid, closed };
  14205. updatePlaceholderMap(this.placeholders, ph, content);
  14206. }
  14207. get icus() { return this._registry.icus; }
  14208. get isRoot() { return this.level === 0; }
  14209. get isResolved() { return this._unresolvedCtxCount === 0; }
  14210. getSerializedPlaceholders() {
  14211. const result = new Map();
  14212. this.placeholders.forEach((values, key) => result.set(key, values.map(serializePlaceholderValue)));
  14213. return result;
  14214. }
  14215. // public API to accumulate i18n-related content
  14216. appendBinding(binding) { this.bindings.add(binding); }
  14217. appendIcu(name, ref) {
  14218. updatePlaceholderMap(this._registry.icus, name, ref);
  14219. }
  14220. appendBoundText(node) {
  14221. const phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
  14222. phs.forEach((values, key) => updatePlaceholderMap(this.placeholders, key, ...values));
  14223. }
  14224. appendTemplate(node, index) {
  14225. // add open and close tags at the same time,
  14226. // since we process nested templates separately
  14227. this.appendTag(TagType.TEMPLATE, node, index, false);
  14228. this.appendTag(TagType.TEMPLATE, node, index, true);
  14229. this._unresolvedCtxCount++;
  14230. }
  14231. appendElement(node, index, closed) {
  14232. this.appendTag(TagType.ELEMENT, node, index, closed);
  14233. }
  14234. appendProjection(node, index) {
  14235. // add open and close tags at the same time,
  14236. // since we process projected content separately
  14237. this.appendTag(TagType.PROJECTION, node, index, false);
  14238. this.appendTag(TagType.PROJECTION, node, index, true);
  14239. }
  14240. /**
  14241. * Generates an instance of a child context based on the root one,
  14242. * when we enter a nested template within I18n section.
  14243. *
  14244. * @param index Instruction index of corresponding i18nStart, which initiates this context
  14245. * @param templateIndex Instruction index of a template which this context belongs to
  14246. * @param meta Meta information (id, meaning, description, etc) associated with this context
  14247. *
  14248. * @returns I18nContext instance
  14249. */
  14250. forkChildContext(index, templateIndex, meta) {
  14251. return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
  14252. }
  14253. /**
  14254. * Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
  14255. *
  14256. * @param context Child I18nContext instance to be reconciled with parent context.
  14257. */
  14258. reconcileChildContext(context) {
  14259. // set the right context id for open and close
  14260. // template tags, so we can use it as sub-block ids
  14261. ['start', 'close'].forEach((op) => {
  14262. const key = context.meta[`${op}Name`];
  14263. const phs = this.placeholders.get(key) || [];
  14264. const tag = phs.find(findTemplateFn(this.id, context.templateIndex));
  14265. if (tag) {
  14266. tag.ctx = context.id;
  14267. }
  14268. });
  14269. // reconcile placeholders
  14270. const childPhs = context.placeholders;
  14271. childPhs.forEach((values, key) => {
  14272. const phs = this.placeholders.get(key);
  14273. if (!phs) {
  14274. this.placeholders.set(key, values);
  14275. return;
  14276. }
  14277. // try to find matching template...
  14278. const tmplIdx = findIndex(phs, findTemplateFn(context.id, context.templateIndex));
  14279. if (tmplIdx >= 0) {
  14280. // ... if found - replace it with nested template content
  14281. const isCloseTag = key.startsWith('CLOSE');
  14282. const isTemplateTag = key.endsWith('NG-TEMPLATE');
  14283. if (isTemplateTag) {
  14284. // current template's content is placed before or after
  14285. // parent template tag, depending on the open/close atrribute
  14286. phs.splice(tmplIdx + (isCloseTag ? 0 : 1), 0, ...values);
  14287. }
  14288. else {
  14289. const idx = isCloseTag ? values.length - 1 : 0;
  14290. values[idx].tmpl = phs[tmplIdx];
  14291. phs.splice(tmplIdx, 1, ...values);
  14292. }
  14293. }
  14294. else {
  14295. // ... otherwise just append content to placeholder value
  14296. phs.push(...values);
  14297. }
  14298. this.placeholders.set(key, phs);
  14299. });
  14300. this._unresolvedCtxCount--;
  14301. }
  14302. }
  14303. //
  14304. // Helper methods
  14305. //
  14306. function wrap(symbol, index, contextId, closed) {
  14307. const state = closed ? '/' : '';
  14308. return wrapI18nPlaceholder(`${state}${symbol}${index}`, contextId);
  14309. }
  14310. function wrapTag(symbol, { index, ctx, isVoid }, closed) {
  14311. return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
  14312. wrap(symbol, index, ctx, closed);
  14313. }
  14314. function findTemplateFn(ctx, templateIndex) {
  14315. return (token) => typeof token === 'object' && token.type === TagType.TEMPLATE &&
  14316. token.index === templateIndex && token.ctx === ctx;
  14317. }
  14318. function serializePlaceholderValue(value) {
  14319. const element = (data, closed) => wrapTag('#', data, closed);
  14320. const template = (data, closed) => wrapTag('*', data, closed);
  14321. const projection = (data, closed) => wrapTag('!', data, closed);
  14322. switch (value.type) {
  14323. case TagType.ELEMENT:
  14324. // close element tag
  14325. if (value.closed) {
  14326. return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
  14327. }
  14328. // open element tag that also initiates a template
  14329. if (value.tmpl) {
  14330. return template(value.tmpl) + element(value) +
  14331. (value.isVoid ? template(value.tmpl, true) : '');
  14332. }
  14333. return element(value);
  14334. case TagType.TEMPLATE:
  14335. return template(value, value.closed);
  14336. case TagType.PROJECTION:
  14337. return projection(value, value.closed);
  14338. default:
  14339. return value;
  14340. }
  14341. }
  14342. /**
  14343. * @license
  14344. * Copyright Google Inc. All Rights Reserved.
  14345. *
  14346. * Use of this source code is governed by an MIT-style license that can be
  14347. * found in the LICENSE file at https://angular.io/license
  14348. */
  14349. const TAG_TO_PLACEHOLDER_NAMES = {
  14350. 'A': 'LINK',
  14351. 'B': 'BOLD_TEXT',
  14352. 'BR': 'LINE_BREAK',
  14353. 'EM': 'EMPHASISED_TEXT',
  14354. 'H1': 'HEADING_LEVEL1',
  14355. 'H2': 'HEADING_LEVEL2',
  14356. 'H3': 'HEADING_LEVEL3',
  14357. 'H4': 'HEADING_LEVEL4',
  14358. 'H5': 'HEADING_LEVEL5',
  14359. 'H6': 'HEADING_LEVEL6',
  14360. 'HR': 'HORIZONTAL_RULE',
  14361. 'I': 'ITALIC_TEXT',
  14362. 'LI': 'LIST_ITEM',
  14363. 'LINK': 'MEDIA_LINK',
  14364. 'OL': 'ORDERED_LIST',
  14365. 'P': 'PARAGRAPH',
  14366. 'Q': 'QUOTATION',
  14367. 'S': 'STRIKETHROUGH_TEXT',
  14368. 'SMALL': 'SMALL_TEXT',
  14369. 'SUB': 'SUBSTRIPT',
  14370. 'SUP': 'SUPERSCRIPT',
  14371. 'TBODY': 'TABLE_BODY',
  14372. 'TD': 'TABLE_CELL',
  14373. 'TFOOT': 'TABLE_FOOTER',
  14374. 'TH': 'TABLE_HEADER_CELL',
  14375. 'THEAD': 'TABLE_HEADER',
  14376. 'TR': 'TABLE_ROW',
  14377. 'TT': 'MONOSPACED_TEXT',
  14378. 'U': 'UNDERLINED_TEXT',
  14379. 'UL': 'UNORDERED_LIST',
  14380. };
  14381. /**
  14382. * Creates unique names for placeholder with different content.
  14383. *
  14384. * Returns the same placeholder name when the content is identical.
  14385. */
  14386. class PlaceholderRegistry {
  14387. constructor() {
  14388. // Count the occurrence of the base name top generate a unique name
  14389. this._placeHolderNameCounts = {};
  14390. // Maps signature to placeholder names
  14391. this._signatureToName = {};
  14392. }
  14393. getStartTagPlaceholderName(tag, attrs, isVoid) {
  14394. const signature = this._hashTag(tag, attrs, isVoid);
  14395. if (this._signatureToName[signature]) {
  14396. return this._signatureToName[signature];
  14397. }
  14398. const upperTag = tag.toUpperCase();
  14399. const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
  14400. const name = this._generateUniqueName(isVoid ? baseName : `START_${baseName}`);
  14401. this._signatureToName[signature] = name;
  14402. return name;
  14403. }
  14404. getCloseTagPlaceholderName(tag) {
  14405. const signature = this._hashClosingTag(tag);
  14406. if (this._signatureToName[signature]) {
  14407. return this._signatureToName[signature];
  14408. }
  14409. const upperTag = tag.toUpperCase();
  14410. const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
  14411. const name = this._generateUniqueName(`CLOSE_${baseName}`);
  14412. this._signatureToName[signature] = name;
  14413. return name;
  14414. }
  14415. getPlaceholderName(name, content) {
  14416. const upperName = name.toUpperCase();
  14417. const signature = `PH: ${upperName}=${content}`;
  14418. if (this._signatureToName[signature]) {
  14419. return this._signatureToName[signature];
  14420. }
  14421. const uniqueName = this._generateUniqueName(upperName);
  14422. this._signatureToName[signature] = uniqueName;
  14423. return uniqueName;
  14424. }
  14425. getUniquePlaceholder(name) {
  14426. return this._generateUniqueName(name.toUpperCase());
  14427. }
  14428. // Generate a hash for a tag - does not take attribute order into account
  14429. _hashTag(tag, attrs, isVoid) {
  14430. const start = `<${tag}`;
  14431. const strAttrs = Object.keys(attrs).sort().map((name) => ` ${name}=${attrs[name]}`).join('');
  14432. const end = isVoid ? '/>' : `></${tag}>`;
  14433. return start + strAttrs + end;
  14434. }
  14435. _hashClosingTag(tag) { return this._hashTag(`/${tag}`, {}, false); }
  14436. _generateUniqueName(base) {
  14437. const seen = this._placeHolderNameCounts.hasOwnProperty(base);
  14438. if (!seen) {
  14439. this._placeHolderNameCounts[base] = 1;
  14440. return base;
  14441. }
  14442. const id = this._placeHolderNameCounts[base];
  14443. this._placeHolderNameCounts[base] = id + 1;
  14444. return `${base}_${id}`;
  14445. }
  14446. }
  14447. /**
  14448. * @license
  14449. * Copyright Google Inc. All Rights Reserved.
  14450. *
  14451. * Use of this source code is governed by an MIT-style license that can be
  14452. * found in the LICENSE file at https://angular.io/license
  14453. */
  14454. const _expParser = new Parser$1(new Lexer());
  14455. /**
  14456. * Returns a function converting html nodes to an i18n Message given an interpolationConfig
  14457. */
  14458. function createI18nMessageFactory(interpolationConfig) {
  14459. const visitor = new _I18nVisitor(_expParser, interpolationConfig);
  14460. return (nodes, meaning, description, id, visitNodeFn) => visitor.toI18nMessage(nodes, meaning, description, id, visitNodeFn);
  14461. }
  14462. class _I18nVisitor {
  14463. constructor(_expressionParser, _interpolationConfig) {
  14464. this._expressionParser = _expressionParser;
  14465. this._interpolationConfig = _interpolationConfig;
  14466. }
  14467. toI18nMessage(nodes, meaning, description, id, visitNodeFn) {
  14468. this._isIcu = nodes.length == 1 && nodes[0] instanceof Expansion;
  14469. this._icuDepth = 0;
  14470. this._placeholderRegistry = new PlaceholderRegistry();
  14471. this._placeholderToContent = {};
  14472. this._placeholderToMessage = {};
  14473. this._visitNodeFn = visitNodeFn;
  14474. const i18nodes = visitAll$1(this, nodes, {});
  14475. return new Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description, id);
  14476. }
  14477. _visitNode(html, i18n) {
  14478. if (this._visitNodeFn) {
  14479. this._visitNodeFn(html, i18n);
  14480. }
  14481. return i18n;
  14482. }
  14483. visitElement(el, context) {
  14484. const children = visitAll$1(this, el.children);
  14485. const attrs = {};
  14486. el.attrs.forEach(attr => {
  14487. // Do not visit the attributes, translatable ones are top-level ASTs
  14488. attrs[attr.name] = attr.value;
  14489. });
  14490. const isVoid = getHtmlTagDefinition(el.name).isVoid;
  14491. const startPhName = this._placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
  14492. this._placeholderToContent[startPhName] = el.sourceSpan.toString();
  14493. let closePhName = '';
  14494. if (!isVoid) {
  14495. closePhName = this._placeholderRegistry.getCloseTagPlaceholderName(el.name);
  14496. this._placeholderToContent[closePhName] = `</${el.name}>`;
  14497. }
  14498. const node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan);
  14499. return this._visitNode(el, node);
  14500. }
  14501. visitAttribute(attribute, context) {
  14502. const node = this._visitTextWithInterpolation(attribute.value, attribute.sourceSpan);
  14503. return this._visitNode(attribute, node);
  14504. }
  14505. visitText(text, context) {
  14506. const node = this._visitTextWithInterpolation(text.value, text.sourceSpan);
  14507. return this._visitNode(text, node);
  14508. }
  14509. visitComment(comment, context) { return null; }
  14510. visitExpansion(icu, context) {
  14511. this._icuDepth++;
  14512. const i18nIcuCases = {};
  14513. const i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
  14514. icu.cases.forEach((caze) => {
  14515. i18nIcuCases[caze.value] = new Container(caze.expression.map((node) => node.visit(this, {})), caze.expSourceSpan);
  14516. });
  14517. this._icuDepth--;
  14518. if (this._isIcu || this._icuDepth > 0) {
  14519. // Returns an ICU node when:
  14520. // - the message (vs a part of the message) is an ICU message, or
  14521. // - the ICU message is nested.
  14522. const expPh = this._placeholderRegistry.getUniquePlaceholder(`VAR_${icu.type}`);
  14523. i18nIcu.expressionPlaceholder = expPh;
  14524. this._placeholderToContent[expPh] = icu.switchValue;
  14525. return this._visitNode(icu, i18nIcu);
  14526. }
  14527. // Else returns a placeholder
  14528. // ICU placeholders should not be replaced with their original content but with the their
  14529. // translations. We need to create a new visitor (they are not re-entrant) to compute the
  14530. // message id.
  14531. // TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
  14532. const phName = this._placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
  14533. const visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
  14534. this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '', '');
  14535. const node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
  14536. return this._visitNode(icu, node);
  14537. }
  14538. visitExpansionCase(icuCase, context) {
  14539. throw new Error('Unreachable code');
  14540. }
  14541. _visitTextWithInterpolation(text, sourceSpan) {
  14542. const splitInterpolation = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
  14543. if (!splitInterpolation) {
  14544. // No expression, return a single text
  14545. return new Text$1(text, sourceSpan);
  14546. }
  14547. // Return a group of text + expressions
  14548. const nodes = [];
  14549. const container = new Container(nodes, sourceSpan);
  14550. const { start: sDelimiter, end: eDelimiter } = this._interpolationConfig;
  14551. for (let i = 0; i < splitInterpolation.strings.length - 1; i++) {
  14552. const expression = splitInterpolation.expressions[i];
  14553. const baseName = _extractPlaceholderName(expression) || 'INTERPOLATION';
  14554. const phName = this._placeholderRegistry.getPlaceholderName(baseName, expression);
  14555. if (splitInterpolation.strings[i].length) {
  14556. // No need to add empty strings
  14557. nodes.push(new Text$1(splitInterpolation.strings[i], sourceSpan));
  14558. }
  14559. nodes.push(new Placeholder(expression, phName, sourceSpan));
  14560. this._placeholderToContent[phName] = sDelimiter + expression + eDelimiter;
  14561. }
  14562. // The last index contains no expression
  14563. const lastStringIdx = splitInterpolation.strings.length - 1;
  14564. if (splitInterpolation.strings[lastStringIdx].length) {
  14565. nodes.push(new Text$1(splitInterpolation.strings[lastStringIdx], sourceSpan));
  14566. }
  14567. return container;
  14568. }
  14569. }
  14570. const _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
  14571. function _extractPlaceholderName(input) {
  14572. return input.split(_CUSTOM_PH_EXP)[2];
  14573. }
  14574. /**
  14575. * @license
  14576. * Copyright Google Inc. All Rights Reserved.
  14577. *
  14578. * Use of this source code is governed by an MIT-style license that can be
  14579. * found in the LICENSE file at https://angular.io/license
  14580. */
  14581. function setI18nRefs(html, i18n) {
  14582. html.i18n = i18n;
  14583. }
  14584. /**
  14585. * This visitor walks over HTML parse tree and converts information stored in
  14586. * i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
  14587. * stored with other element's and attribute's information.
  14588. */
  14589. class I18nMetaVisitor {
  14590. constructor(interpolationConfig = DEFAULT_INTERPOLATION_CONFIG, keepI18nAttrs = false) {
  14591. this.interpolationConfig = interpolationConfig;
  14592. this.keepI18nAttrs = keepI18nAttrs;
  14593. // i18n message generation factory
  14594. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  14595. }
  14596. _generateI18nMessage(nodes, meta = '', visitNodeFn) {
  14597. const parsed = typeof meta === 'string' ? parseI18nMeta(meta) : metaFromI18nMessage(meta);
  14598. const message = this._createI18nMessage(nodes, parsed.meaning || '', parsed.description || '', parsed.id || '', visitNodeFn);
  14599. if (!message.id) {
  14600. // generate (or restore) message id if not specified in template
  14601. message.id = typeof meta !== 'string' && meta.id || decimalDigest(message);
  14602. }
  14603. return message;
  14604. }
  14605. visitElement(element, context) {
  14606. if (hasI18nAttrs(element)) {
  14607. const attrs = [];
  14608. const attrsMeta = {};
  14609. for (const attr of element.attrs) {
  14610. if (attr.name === I18N_ATTR) {
  14611. // root 'i18n' node attribute
  14612. const i18n = element.i18n || attr.value;
  14613. const message = this._generateI18nMessage(element.children, i18n, setI18nRefs);
  14614. // do not assign empty i18n meta
  14615. if (message.nodes.length) {
  14616. element.i18n = message;
  14617. }
  14618. }
  14619. else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
  14620. // 'i18n-*' attributes
  14621. const key = attr.name.slice(I18N_ATTR_PREFIX.length);
  14622. attrsMeta[key] = attr.value;
  14623. }
  14624. else {
  14625. // non-i18n attributes
  14626. attrs.push(attr);
  14627. }
  14628. }
  14629. // set i18n meta for attributes
  14630. if (Object.keys(attrsMeta).length) {
  14631. for (const attr of attrs) {
  14632. const meta = attrsMeta[attr.name];
  14633. // do not create translation for empty attributes
  14634. if (meta !== undefined && attr.value) {
  14635. attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
  14636. }
  14637. }
  14638. }
  14639. if (!this.keepI18nAttrs) {
  14640. // update element's attributes,
  14641. // keeping only non-i18n related ones
  14642. element.attrs = attrs;
  14643. }
  14644. }
  14645. visitAll$1(this, element.children);
  14646. return element;
  14647. }
  14648. visitExpansion(expansion, context) {
  14649. let message;
  14650. const meta = expansion.i18n;
  14651. if (meta instanceof IcuPlaceholder) {
  14652. // set ICU placeholder name (e.g. "ICU_1"),
  14653. // generated while processing root element contents,
  14654. // so we can reference it when we output translation
  14655. const name = meta.name;
  14656. message = this._generateI18nMessage([expansion], meta);
  14657. const icu = icuFromI18nMessage(message);
  14658. icu.name = name;
  14659. }
  14660. else {
  14661. // when ICU is a root level translation
  14662. message = this._generateI18nMessage([expansion], meta);
  14663. }
  14664. expansion.i18n = message;
  14665. return expansion;
  14666. }
  14667. visitText(text, context) { return text; }
  14668. visitAttribute(attribute, context) { return attribute; }
  14669. visitComment(comment, context) { return comment; }
  14670. visitExpansionCase(expansionCase, context) { return expansionCase; }
  14671. }
  14672. /**
  14673. * @license
  14674. * Copyright Google Inc. All Rights Reserved.
  14675. *
  14676. * Use of this source code is governed by an MIT-style license that can be
  14677. * found in the LICENSE file at https://angular.io/license
  14678. */
  14679. const formatPh = (value) => `{$${formatI18nPlaceholderName(value)}}`;
  14680. /**
  14681. * This visitor walks over i18n tree and generates its string representation,
  14682. * including ICUs and placeholders in {$PLACEHOLDER} format.
  14683. */
  14684. class SerializerVisitor {
  14685. visitText(text, context) { return text.value; }
  14686. visitContainer(container, context) {
  14687. return container.children.map(child => child.visit(this)).join('');
  14688. }
  14689. visitIcu(icu, context) {
  14690. const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
  14691. return `{${icu.expressionPlaceholder}, ${icu.type}, ${strCases.join(' ')}}`;
  14692. }
  14693. visitTagPlaceholder(ph, context) {
  14694. return ph.isVoid ?
  14695. formatPh(ph.startName) :
  14696. `${formatPh(ph.startName)}${ph.children.map(child => child.visit(this)).join('')}${formatPh(ph.closeName)}`;
  14697. }
  14698. visitPlaceholder(ph, context) { return formatPh(ph.name); }
  14699. visitIcuPlaceholder(ph, context) { return formatPh(ph.name); }
  14700. }
  14701. const serializerVisitor$1 = new SerializerVisitor();
  14702. function getSerializedI18nContent(message) {
  14703. return message.nodes.map(node => node.visit(serializerVisitor$1, null)).join('');
  14704. }
  14705. /**
  14706. * @license
  14707. * Copyright Google Inc. All Rights Reserved.
  14708. *
  14709. * Use of this source code is governed by an MIT-style license that can be
  14710. * found in the LICENSE file at https://angular.io/license
  14711. */
  14712. // Selector attribute name of `<ng-content>`
  14713. const NG_CONTENT_SELECT_ATTR$1 = 'select';
  14714. // Attribute name of `ngProjectAs`.
  14715. const NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
  14716. // List of supported global targets for event listeners
  14717. const GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers$1.resolveWindow], ['document', Identifiers$1.resolveDocument], ['body', Identifiers$1.resolveBody]]);
  14718. const LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
  14719. // if (rf & flags) { .. }
  14720. function renderFlagCheckIfStmt(flags, statements) {
  14721. return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
  14722. }
  14723. function prepareEventListenerParameters(eventAst, handlerName = null, scope = null) {
  14724. const { type, name, target, phase, handler } = eventAst;
  14725. if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
  14726. throw new Error(`Unexpected global target '${target}' defined for '${name}' event.
  14727. Supported list of global targets: ${Array.from(GLOBAL_TARGET_RESOLVERS.keys())}.`);
  14728. }
  14729. const implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
  14730. variable(CONTEXT_NAME) :
  14731. scope.getOrCreateSharedContextVar(0);
  14732. const bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', () => error('Unexpected interpolation'), eventAst.handlerSpan);
  14733. const statements = [];
  14734. if (scope) {
  14735. statements.push(...scope.restoreViewStatement());
  14736. statements.push(...scope.variableDeclarations());
  14737. }
  14738. statements.push(...bindingExpr.render3Stmts);
  14739. const eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
  14740. const fnName = handlerName && sanitizeIdentifier(handlerName);
  14741. const fnArgs = [new FnParam('$event', DYNAMIC_TYPE)];
  14742. const handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
  14743. const params = [literal(eventName), handlerFn];
  14744. if (target) {
  14745. params.push(literal(false), // `useCapture` flag, defaults to `false`
  14746. importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
  14747. }
  14748. return params;
  14749. }
  14750. class TemplateDefinitionBuilder {
  14751. constructor(constantPool, parentBindingScope, level = 0, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds) {
  14752. this.constantPool = constantPool;
  14753. this.level = level;
  14754. this.contextName = contextName;
  14755. this.i18nContext = i18nContext;
  14756. this.templateIndex = templateIndex;
  14757. this.templateName = templateName;
  14758. this.directiveMatcher = directiveMatcher;
  14759. this.directives = directives;
  14760. this.pipeTypeByName = pipeTypeByName;
  14761. this.pipes = pipes;
  14762. this._namespace = _namespace;
  14763. this.relativeContextFilePath = relativeContextFilePath;
  14764. this.i18nUseExternalIds = i18nUseExternalIds;
  14765. this._dataIndex = 0;
  14766. this._bindingContext = 0;
  14767. this._prefixCode = [];
  14768. /**
  14769. * List of callbacks to generate creation mode instructions. We store them here as we process
  14770. * the template so bindings in listeners are resolved only once all nodes have been visited.
  14771. * This ensures all local refs and context variables are available for matching.
  14772. */
  14773. this._creationCodeFns = [];
  14774. /**
  14775. * List of callbacks to generate update mode instructions. We store them here as we process
  14776. * the template so bindings are resolved only once all nodes have been visited. This ensures
  14777. * all local refs and context variables are available for matching.
  14778. */
  14779. this._updateCodeFns = [];
  14780. /**
  14781. * Memorizes the last node index for which a select instruction has been generated.
  14782. * We're initializing this to -1 to ensure the `select(0)` instruction is generated before any
  14783. * relevant update instructions.
  14784. */
  14785. this._lastNodeIndexWithFlush = -1;
  14786. /** Temporary variable declarations generated from visiting pipes, literals, etc. */
  14787. this._tempVariables = [];
  14788. /**
  14789. * List of callbacks to build nested templates. Nested templates must not be visited until
  14790. * after the parent template has finished visiting all of its nodes. This ensures that all
  14791. * local ref bindings in nested templates are able to find local ref values if the refs
  14792. * are defined after the template declaration.
  14793. */
  14794. this._nestedTemplateFns = [];
  14795. this._unsupported = unsupported;
  14796. // i18n context local to this template
  14797. this.i18n = null;
  14798. // Number of slots to reserve for pureFunctions
  14799. this._pureFunctionSlots = 0;
  14800. // Number of binding slots
  14801. this._bindingSlots = 0;
  14802. // Projection slots found in the template. Projection slots can distribute projected
  14803. // nodes based on a selector, or can just use the wildcard selector to match
  14804. // all nodes which aren't matching any selector.
  14805. this._ngContentReservedSlots = [];
  14806. // Number of non-default selectors found in all parent templates of this template. We need to
  14807. // track it to properly adjust projection slot index in the `projection` instruction.
  14808. this._ngContentSelectorsOffset = 0;
  14809. // Expression that should be used as implicit receiver when converting template
  14810. // expressions to output AST.
  14811. this._implicitReceiverExpr = null;
  14812. // These should be handled in the template or element directly.
  14813. this.visitReference = invalid$1;
  14814. this.visitVariable = invalid$1;
  14815. this.visitTextAttribute = invalid$1;
  14816. this.visitBoundAttribute = invalid$1;
  14817. this.visitBoundEvent = invalid$1;
  14818. this._bindingScope = parentBindingScope.nestedScope(level);
  14819. // Turn the relative context file path into an identifier by replacing non-alphanumeric
  14820. // characters with underscores.
  14821. this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
  14822. this._valueConverter = new ValueConverter(constantPool, () => this.allocateDataSlot(), (numSlots) => this.allocatePureFunctionSlots(numSlots), (name, localName, slot, value) => {
  14823. const pipeType = pipeTypeByName.get(name);
  14824. if (pipeType) {
  14825. this.pipes.add(pipeType);
  14826. }
  14827. this._bindingScope.set(this.level, localName, value);
  14828. this.creationInstruction(null, Identifiers$1.pipe, [literal(slot), literal(name)]);
  14829. });
  14830. }
  14831. registerContextVariables(variable$1) {
  14832. const scopedName = this._bindingScope.freshReferenceName();
  14833. const retrievalLevel = this.level;
  14834. const lhs = variable(variable$1.name + scopedName);
  14835. this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, (scope, relativeLevel) => {
  14836. let rhs;
  14837. if (scope.bindingLevel === retrievalLevel) {
  14838. // e.g. ctx
  14839. rhs = variable(CONTEXT_NAME);
  14840. }
  14841. else {
  14842. const sharedCtxVar = scope.getSharedContextName(retrievalLevel);
  14843. // e.g. ctx_r0 OR x(2);
  14844. rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
  14845. }
  14846. // e.g. const $item$ = x(2).$implicit;
  14847. return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
  14848. });
  14849. }
  14850. buildTemplateFunction(nodes, variables, ngContentSelectorsOffset = 0, i18n) {
  14851. this._ngContentSelectorsOffset = ngContentSelectorsOffset;
  14852. if (this._namespace !== Identifiers$1.namespaceHTML) {
  14853. this.creationInstruction(null, this._namespace);
  14854. }
  14855. // Create variable bindings
  14856. variables.forEach(v => this.registerContextVariables(v));
  14857. // Initiate i18n context in case:
  14858. // - this template has parent i18n context
  14859. // - or the template has i18n meta associated with it,
  14860. // but it's not initiated by the Element (e.g. <ng-template i18n>)
  14861. const initI18nContext = this.i18nContext || (isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
  14862. !(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
  14863. const selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
  14864. if (initI18nContext) {
  14865. this.i18nStart(null, i18n, selfClosingI18nInstruction);
  14866. }
  14867. // This is the initial pass through the nodes of this template. In this pass, we
  14868. // queue all creation mode and update mode instructions for generation in the second
  14869. // pass. It's necessary to separate the passes to ensure local refs are defined before
  14870. // resolving bindings. We also count bindings in this pass as we walk bound expressions.
  14871. visitAll(this, nodes);
  14872. // Add total binding count to pure function count so pure function instructions are
  14873. // generated with the correct slot offset when update instructions are processed.
  14874. this._pureFunctionSlots += this._bindingSlots;
  14875. // Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
  14876. // `pipeBind` update instructions), so we have to update the slot offsets manually
  14877. // to account for bindings.
  14878. this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
  14879. // Nested templates must be processed before creation instructions so template()
  14880. // instructions can be generated with the correct internal const count.
  14881. this._nestedTemplateFns.forEach(buildTemplateFn => buildTemplateFn());
  14882. // Output the `projectionDef` instruction when some `<ng-content>` tags are present.
  14883. // The `projectionDef` instruction is only emitted for the component template and
  14884. // is skipped for nested templates (<ng-template> tags).
  14885. if (this.level === 0 && this._ngContentReservedSlots.length) {
  14886. const parameters = [];
  14887. // By default the `projectionDef` instructions creates one slot for the wildcard
  14888. // selector if no parameters are passed. Therefore we only want to allocate a new
  14889. // array for the projection slots if the default projection slot is not sufficient.
  14890. if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
  14891. const r3ReservedSlots = this._ngContentReservedSlots.map(s => s !== '*' ? parseSelectorToR3Selector(s) : s);
  14892. parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
  14893. }
  14894. // Since we accumulate ngContent selectors while processing template elements,
  14895. // we *prepend* `projectionDef` to creation instructions block, to put it before
  14896. // any `projection` instructions
  14897. this.creationInstruction(null, Identifiers$1.projectionDef, parameters, /* prepend */ true);
  14898. }
  14899. if (initI18nContext) {
  14900. this.i18nEnd(null, selfClosingI18nInstruction);
  14901. }
  14902. // Generate all the creation mode instructions (e.g. resolve bindings in listeners)
  14903. const creationStatements = this._creationCodeFns.map((fn) => fn());
  14904. // Generate all the update mode instructions (e.g. resolve property or text bindings)
  14905. const updateStatements = this._updateCodeFns.map((fn) => fn());
  14906. // Variable declaration must occur after binding resolution so we can generate context
  14907. // instructions that build on each other.
  14908. // e.g. const b = nextContext().$implicit(); const b = nextContext();
  14909. const creationVariables = this._bindingScope.viewSnapshotStatements();
  14910. const updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
  14911. const creationBlock = creationStatements.length > 0 ?
  14912. [renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
  14913. [];
  14914. const updateBlock = updateStatements.length > 0 ?
  14915. [renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
  14916. [];
  14917. return fn(
  14918. // i.e. (rf: RenderFlags, ctx: any)
  14919. [new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
  14920. // Temporary variable declarations for query refresh (i.e. let _t: any;)
  14921. ...this._prefixCode,
  14922. // Creating mode (i.e. if (rf & RenderFlags.Create) { ... })
  14923. ...creationBlock,
  14924. // Binding and refresh mode (i.e. if (rf & RenderFlags.Update) {...})
  14925. ...updateBlock,
  14926. ], INFERRED_TYPE, null, this.templateName);
  14927. }
  14928. // LocalResolver
  14929. getLocal(name) { return this._bindingScope.get(name); }
  14930. // LocalResolver
  14931. notifyImplicitReceiverUse() { this._bindingScope.notifyImplicitReceiverUse(); }
  14932. i18nTranslate(message, params = {}, ref, transformFn) {
  14933. const _ref = ref || variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  14934. // Closure Compiler requires const names to start with `MSG_` but disallows any other const to
  14935. // start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
  14936. const closureVar = this.i18nGenerateClosureVar(message.id);
  14937. const _params = {};
  14938. if (params && Object.keys(params).length) {
  14939. Object.keys(params).forEach(key => _params[formatI18nPlaceholderName(key)] = params[key]);
  14940. }
  14941. const meta = metaFromI18nMessage(message);
  14942. const content = getSerializedI18nContent(message);
  14943. const statements = getTranslationDeclStmts(_ref, closureVar, content, meta, _params, transformFn);
  14944. this.constantPool.statements.push(...statements);
  14945. return _ref;
  14946. }
  14947. i18nAppendBindings(expressions) {
  14948. if (expressions.length > 0) {
  14949. expressions.forEach(expression => this.i18n.appendBinding(expression));
  14950. }
  14951. }
  14952. i18nBindProps(props) {
  14953. const bound = {};
  14954. Object.keys(props).forEach(key => {
  14955. const prop = props[key];
  14956. if (prop instanceof Text) {
  14957. bound[key] = literal(prop.value);
  14958. }
  14959. else {
  14960. const value = prop.value.visit(this._valueConverter);
  14961. this.allocateBindingSlots(value);
  14962. if (value instanceof Interpolation) {
  14963. const { strings, expressions } = value;
  14964. const { id, bindings } = this.i18n;
  14965. const label = assembleI18nBoundString(strings, bindings.size, id);
  14966. this.i18nAppendBindings(expressions);
  14967. bound[key] = literal(label);
  14968. }
  14969. }
  14970. });
  14971. return bound;
  14972. }
  14973. i18nGenerateClosureVar(messageId) {
  14974. let name;
  14975. const suffix = this.fileBasedI18nSuffix.toUpperCase();
  14976. if (this.i18nUseExternalIds) {
  14977. const prefix = getTranslationConstPrefix(`EXTERNAL_`);
  14978. const uniqueSuffix = this.constantPool.uniqueName(suffix);
  14979. name = `${prefix}${sanitizeIdentifier(messageId)}$$${uniqueSuffix}`;
  14980. }
  14981. else {
  14982. const prefix = getTranslationConstPrefix(suffix);
  14983. name = this.constantPool.uniqueName(prefix);
  14984. }
  14985. return variable(name);
  14986. }
  14987. i18nUpdateRef(context) {
  14988. const { icus, meta, isRoot, isResolved, isEmitted } = context;
  14989. if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
  14990. context.isEmitted = true;
  14991. const placeholders = context.getSerializedPlaceholders();
  14992. let icuMapping = {};
  14993. let params = placeholders.size ? placeholdersToParams(placeholders) : {};
  14994. if (icus.size) {
  14995. icus.forEach((refs, key) => {
  14996. if (refs.length === 1) {
  14997. // if we have one ICU defined for a given
  14998. // placeholder - just output its reference
  14999. params[key] = refs[0];
  15000. }
  15001. else {
  15002. // ... otherwise we need to activate post-processing
  15003. // to replace ICU placeholders with proper values
  15004. const placeholder = wrapI18nPlaceholder(`${I18N_ICU_MAPPING_PREFIX}${key}`);
  15005. params[key] = literal(placeholder);
  15006. icuMapping[key] = literalArr(refs);
  15007. }
  15008. });
  15009. }
  15010. // translation requires post processing in 2 cases:
  15011. // - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
  15012. // - if we have multiple ICUs that refer to the same placeholder name
  15013. const needsPostprocessing = Array.from(placeholders.values()).some((value) => value.length > 1) ||
  15014. Object.keys(icuMapping).length;
  15015. let transformFn;
  15016. if (needsPostprocessing) {
  15017. transformFn = (raw) => {
  15018. const args = [raw];
  15019. if (Object.keys(icuMapping).length) {
  15020. args.push(mapLiteral(icuMapping, true));
  15021. }
  15022. return instruction(null, Identifiers$1.i18nPostprocess, args);
  15023. };
  15024. }
  15025. this.i18nTranslate(meta, params, context.ref, transformFn);
  15026. }
  15027. }
  15028. i18nStart(span = null, meta, selfClosing) {
  15029. const index = this.allocateDataSlot();
  15030. if (this.i18nContext) {
  15031. this.i18n = this.i18nContext.forkChildContext(index, this.templateIndex, meta);
  15032. }
  15033. else {
  15034. const ref = variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  15035. this.i18n = new I18nContext(index, ref, 0, this.templateIndex, meta);
  15036. }
  15037. // generate i18nStart instruction
  15038. const { id, ref } = this.i18n;
  15039. const params = [literal(index), ref];
  15040. if (id > 0) {
  15041. // do not push 3rd argument (sub-block id)
  15042. // into i18nStart call for top level i18n context
  15043. params.push(literal(id));
  15044. }
  15045. this.creationInstruction(span, selfClosing ? Identifiers$1.i18n : Identifiers$1.i18nStart, params);
  15046. }
  15047. i18nEnd(span = null, selfClosing) {
  15048. if (!this.i18n) {
  15049. throw new Error('i18nEnd is executed with no i18n context present');
  15050. }
  15051. if (this.i18nContext) {
  15052. this.i18nContext.reconcileChildContext(this.i18n);
  15053. this.i18nUpdateRef(this.i18nContext);
  15054. }
  15055. else {
  15056. this.i18nUpdateRef(this.i18n);
  15057. }
  15058. // setup accumulated bindings
  15059. const { index, bindings } = this.i18n;
  15060. if (bindings.size) {
  15061. const chainBindings = [];
  15062. bindings.forEach(binding => {
  15063. chainBindings.push({ sourceSpan: span, value: () => this.convertPropertyBinding(binding) });
  15064. });
  15065. this.updateInstructionChain(index, Identifiers$1.i18nExp, chainBindings);
  15066. this.updateInstruction(index, span, Identifiers$1.i18nApply, [literal(index)]);
  15067. }
  15068. if (!selfClosing) {
  15069. this.creationInstruction(span, Identifiers$1.i18nEnd);
  15070. }
  15071. this.i18n = null; // reset local i18n context
  15072. }
  15073. visitContent(ngContent) {
  15074. const slot = this.allocateDataSlot();
  15075. const projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
  15076. const parameters = [literal(slot)];
  15077. const attributes = [];
  15078. this._ngContentReservedSlots.push(ngContent.selector);
  15079. ngContent.attributes.forEach((attribute) => {
  15080. const { name, value } = attribute;
  15081. if (name === NG_PROJECT_AS_ATTR_NAME) {
  15082. attributes.push(...getNgProjectAsLiteral(attribute));
  15083. }
  15084. else if (name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1) {
  15085. attributes.push(literal(name), literal(value));
  15086. }
  15087. });
  15088. if (attributes.length > 0) {
  15089. parameters.push(literal(projectionSlotIdx), literalArr(attributes));
  15090. }
  15091. else if (projectionSlotIdx !== 0) {
  15092. parameters.push(literal(projectionSlotIdx));
  15093. }
  15094. this.creationInstruction(ngContent.sourceSpan, Identifiers$1.projection, parameters);
  15095. if (this.i18n) {
  15096. this.i18n.appendProjection(ngContent.i18n, slot);
  15097. }
  15098. }
  15099. getNamespaceInstruction(namespaceKey) {
  15100. switch (namespaceKey) {
  15101. case 'math':
  15102. return Identifiers$1.namespaceMathML;
  15103. case 'svg':
  15104. return Identifiers$1.namespaceSVG;
  15105. default:
  15106. return Identifiers$1.namespaceHTML;
  15107. }
  15108. }
  15109. addNamespaceInstruction(nsInstruction, element) {
  15110. this._namespace = nsInstruction;
  15111. this.creationInstruction(element.sourceSpan, nsInstruction);
  15112. }
  15113. visitElement(element) {
  15114. const elementIndex = this.allocateDataSlot();
  15115. const stylingBuilder = new StylingBuilder(literal(elementIndex), null);
  15116. let isNonBindableMode = false;
  15117. const isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
  15118. if (isI18nRootElement && this.i18n) {
  15119. throw new Error(`Could not mark an element as translatable inside of a translatable section`);
  15120. }
  15121. const i18nAttrs = [];
  15122. const outputAttrs = [];
  15123. const [namespaceKey, elementName] = splitNsName(element.name);
  15124. const isNgContainer$1 = isNgContainer(element.name);
  15125. // Handle styling, i18n, ngNonBindable attributes
  15126. for (const attr of element.attributes) {
  15127. const { name, value } = attr;
  15128. if (name === NON_BINDABLE_ATTR) {
  15129. isNonBindableMode = true;
  15130. }
  15131. else if (name === 'style') {
  15132. stylingBuilder.registerStyleAttr(value);
  15133. }
  15134. else if (name === 'class') {
  15135. stylingBuilder.registerClassAttr(value);
  15136. }
  15137. else {
  15138. if (attr.i18n) {
  15139. // Place attributes into a separate array for i18n processing, but also keep such
  15140. // attributes in the main list to make them available for directive matching at runtime.
  15141. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  15142. // arguments
  15143. i18nAttrs.push(attr);
  15144. }
  15145. else {
  15146. outputAttrs.push(attr);
  15147. }
  15148. }
  15149. }
  15150. // Match directives on non i18n attributes
  15151. this.matchDirectives(element.name, element);
  15152. // Regular element or ng-container creation mode
  15153. const parameters = [literal(elementIndex)];
  15154. if (!isNgContainer$1) {
  15155. parameters.push(literal(elementName));
  15156. }
  15157. // Add the attributes
  15158. const attributes = [];
  15159. const allOtherInputs = [];
  15160. element.inputs.forEach((input) => {
  15161. const stylingInputWasSet = stylingBuilder.registerBoundInput(input);
  15162. if (!stylingInputWasSet) {
  15163. if (input.type === 0 /* Property */ && input.i18n) {
  15164. // Place attributes into a separate array for i18n processing, but also keep such
  15165. // attributes in the main list to make them available for directive matching at runtime.
  15166. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  15167. // arguments
  15168. i18nAttrs.push(input);
  15169. }
  15170. else {
  15171. allOtherInputs.push(input);
  15172. }
  15173. }
  15174. });
  15175. outputAttrs.forEach(attr => {
  15176. if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
  15177. attributes.push(...getNgProjectAsLiteral(attr));
  15178. }
  15179. else {
  15180. attributes.push(...getAttributeNameLiterals(attr.name), literal(attr.value));
  15181. }
  15182. });
  15183. // add attributes for directive and projection matching purposes
  15184. attributes.push(...this.prepareNonRenderAttrs(allOtherInputs, element.outputs, stylingBuilder, [], i18nAttrs));
  15185. parameters.push(this.toAttrsParam(attributes));
  15186. // local refs (ex.: <div #foo #bar="baz">)
  15187. parameters.push(this.prepareRefsParameter(element.references));
  15188. const wasInNamespace = this._namespace;
  15189. const currentNamespace = this.getNamespaceInstruction(namespaceKey);
  15190. // If the namespace is changing now, include an instruction to change it
  15191. // during element creation.
  15192. if (currentNamespace !== wasInNamespace) {
  15193. this.addNamespaceInstruction(currentNamespace, element);
  15194. }
  15195. if (this.i18n) {
  15196. this.i18n.appendElement(element.i18n, elementIndex);
  15197. }
  15198. const hasChildren = () => {
  15199. if (!isI18nRootElement && this.i18n) {
  15200. // we do not append text node instructions and ICUs inside i18n section,
  15201. // so we exclude them while calculating whether current element has children
  15202. return !hasTextChildrenOnly(element.children);
  15203. }
  15204. return element.children.length > 0;
  15205. };
  15206. const createSelfClosingInstruction = !stylingBuilder.hasBindings && !isNgContainer$1 &&
  15207. element.outputs.length === 0 && i18nAttrs.length === 0 && !hasChildren();
  15208. const createSelfClosingI18nInstruction = !createSelfClosingInstruction &&
  15209. !stylingBuilder.hasBindings && hasTextChildrenOnly(element.children);
  15210. if (createSelfClosingInstruction) {
  15211. this.creationInstruction(element.sourceSpan, Identifiers$1.element, trimTrailingNulls(parameters));
  15212. }
  15213. else {
  15214. this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainerStart : Identifiers$1.elementStart, trimTrailingNulls(parameters));
  15215. if (isNonBindableMode) {
  15216. this.creationInstruction(element.sourceSpan, Identifiers$1.disableBindings);
  15217. }
  15218. // process i18n element attributes
  15219. if (i18nAttrs.length) {
  15220. let hasBindings = false;
  15221. const i18nAttrArgs = [];
  15222. const bindings = [];
  15223. i18nAttrs.forEach(attr => {
  15224. const message = attr.i18n;
  15225. if (attr instanceof TextAttribute) {
  15226. i18nAttrArgs.push(literal(attr.name), this.i18nTranslate(message));
  15227. }
  15228. else {
  15229. const converted = attr.value.visit(this._valueConverter);
  15230. this.allocateBindingSlots(converted);
  15231. if (converted instanceof Interpolation) {
  15232. const placeholders = assembleBoundTextPlaceholders(message);
  15233. const params = placeholdersToParams(placeholders);
  15234. i18nAttrArgs.push(literal(attr.name), this.i18nTranslate(message, params));
  15235. converted.expressions.forEach(expression => {
  15236. hasBindings = true;
  15237. bindings.push({
  15238. sourceSpan: element.sourceSpan,
  15239. value: () => this.convertExpressionBinding(expression)
  15240. });
  15241. });
  15242. }
  15243. }
  15244. });
  15245. if (bindings.length) {
  15246. this.updateInstructionChain(elementIndex, Identifiers$1.i18nExp, bindings);
  15247. }
  15248. if (i18nAttrArgs.length) {
  15249. const index = literal(this.allocateDataSlot());
  15250. const args = this.constantPool.getConstLiteral(literalArr(i18nAttrArgs), true);
  15251. this.creationInstruction(element.sourceSpan, Identifiers$1.i18nAttributes, [index, args]);
  15252. if (hasBindings) {
  15253. this.updateInstruction(elementIndex, element.sourceSpan, Identifiers$1.i18nApply, [index]);
  15254. }
  15255. }
  15256. }
  15257. // The style bindings code is placed into two distinct blocks within the template function AOT
  15258. // code: creation and update. The creation code contains the `styling` instructions
  15259. // which will apply the collected binding values to the element. `styling` is
  15260. // designed to run inside of `elementStart` and `elementEnd`. The update instructions
  15261. // (things like `styleProp`, `classProp`, etc..) are applied later on in this
  15262. // file
  15263. this.processStylingInstruction(elementIndex, stylingBuilder.buildStylingInstruction(element.sourceSpan, this.constantPool), true);
  15264. // Generate Listeners (outputs)
  15265. element.outputs.forEach((outputAst) => {
  15266. this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, this.prepareListenerParameter(element.name, outputAst, elementIndex));
  15267. });
  15268. // Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
  15269. // listeners, to make sure i18nAttributes instruction targets current element at runtime.
  15270. if (isI18nRootElement) {
  15271. this.i18nStart(element.sourceSpan, element.i18n, createSelfClosingI18nInstruction);
  15272. }
  15273. }
  15274. // the code here will collect all update-level styling instructions and add them to the
  15275. // update block of the template function AOT code. Instructions like `styleProp`,
  15276. // `styleMap`, `classMap`, `classProp` and `stylingApply`
  15277. // are all generated and assigned in the code below.
  15278. const stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
  15279. const limit = stylingInstructions.length - 1;
  15280. for (let i = 0; i <= limit; i++) {
  15281. const instruction = stylingInstructions[i];
  15282. this._bindingSlots += instruction.allocateBindingSlots;
  15283. this.processStylingInstruction(elementIndex, instruction, false);
  15284. }
  15285. // the reason why `undefined` is used is because the renderer understands this as a
  15286. // special value to symbolize that there is no RHS to this binding
  15287. // TODO (matsko): revisit this once FW-959 is approached
  15288. const emptyValueBindInstruction = literal(undefined);
  15289. const propertyBindings = [];
  15290. const attributeBindings = [];
  15291. // Generate element input bindings
  15292. allOtherInputs.forEach((input) => {
  15293. const inputType = input.type;
  15294. if (inputType === 4 /* Animation */) {
  15295. const value = input.value.visit(this._valueConverter);
  15296. // animation bindings can be presented in the following formats:
  15297. // 1. [@binding]="fooExp"
  15298. // 2. [@binding]="{value:fooExp, params:{...}}"
  15299. // 3. [@binding]
  15300. // 4. @binding
  15301. // All formats will be valid for when a synthetic binding is created.
  15302. // The reasoning for this is because the renderer should get each
  15303. // synthetic binding value in the order of the array that they are
  15304. // defined in...
  15305. const hasValue = value instanceof LiteralPrimitive ? !!value.value : true;
  15306. this.allocateBindingSlots(value);
  15307. propertyBindings.push({
  15308. name: prepareSyntheticPropertyName(input.name),
  15309. sourceSpan: input.sourceSpan,
  15310. value: () => hasValue ? this.convertPropertyBinding(value) : emptyValueBindInstruction
  15311. });
  15312. }
  15313. else {
  15314. // we must skip attributes with associated i18n context, since these attributes are handled
  15315. // separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
  15316. if (input.i18n)
  15317. return;
  15318. const value = input.value.visit(this._valueConverter);
  15319. if (value !== undefined) {
  15320. const params = [];
  15321. const [attrNamespace, attrName] = splitNsName(input.name);
  15322. const isAttributeBinding = inputType === 1 /* Attribute */;
  15323. const sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
  15324. if (sanitizationRef)
  15325. params.push(sanitizationRef);
  15326. if (attrNamespace) {
  15327. const namespaceLiteral = literal(attrNamespace);
  15328. if (sanitizationRef) {
  15329. params.push(namespaceLiteral);
  15330. }
  15331. else {
  15332. // If there wasn't a sanitization ref, we need to add
  15333. // an extra param so that we can pass in the namespace.
  15334. params.push(literal(null), namespaceLiteral);
  15335. }
  15336. }
  15337. this.allocateBindingSlots(value);
  15338. if (inputType === 0 /* Property */) {
  15339. if (value instanceof Interpolation) {
  15340. // prop="{{value}}" and friends
  15341. this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value), elementIndex, attrName, input, value, params);
  15342. }
  15343. else {
  15344. // [prop]="value"
  15345. // Collect all the properties so that we can chain into a single function at the end.
  15346. propertyBindings.push({
  15347. name: attrName,
  15348. sourceSpan: input.sourceSpan,
  15349. value: () => this.convertPropertyBinding(value), params
  15350. });
  15351. }
  15352. }
  15353. else if (inputType === 1 /* Attribute */) {
  15354. if (value instanceof Interpolation && getInterpolationArgsLength(value) > 1) {
  15355. // attr.name="text{{value}}" and friends
  15356. this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value), elementIndex, attrName, input, value, params);
  15357. }
  15358. else {
  15359. const boundValue = value instanceof Interpolation ? value.expressions[0] : value;
  15360. // [attr.name]="value" or attr.name="{{value}}"
  15361. // Collect the attribute bindings so that they can be chained at the end.
  15362. attributeBindings.push({
  15363. name: attrName,
  15364. sourceSpan: input.sourceSpan,
  15365. value: () => this.convertPropertyBinding(boundValue), params
  15366. });
  15367. }
  15368. }
  15369. else {
  15370. // class prop
  15371. this.updateInstruction(elementIndex, input.sourceSpan, Identifiers$1.classProp, () => {
  15372. return [
  15373. literal(elementIndex), literal(attrName), this.convertPropertyBinding(value),
  15374. ...params
  15375. ];
  15376. });
  15377. }
  15378. }
  15379. }
  15380. });
  15381. if (propertyBindings.length > 0) {
  15382. this.updateInstructionChain(elementIndex, Identifiers$1.property, propertyBindings);
  15383. }
  15384. if (attributeBindings.length > 0) {
  15385. this.updateInstructionChain(elementIndex, Identifiers$1.attribute, attributeBindings);
  15386. }
  15387. // Traverse element child nodes
  15388. visitAll(this, element.children);
  15389. if (!isI18nRootElement && this.i18n) {
  15390. this.i18n.appendElement(element.i18n, elementIndex, true);
  15391. }
  15392. if (!createSelfClosingInstruction) {
  15393. // Finish element construction mode.
  15394. const span = element.endSourceSpan || element.sourceSpan;
  15395. if (isI18nRootElement) {
  15396. this.i18nEnd(span, createSelfClosingI18nInstruction);
  15397. }
  15398. if (isNonBindableMode) {
  15399. this.creationInstruction(span, Identifiers$1.enableBindings);
  15400. }
  15401. this.creationInstruction(span, isNgContainer$1 ? Identifiers$1.elementContainerEnd : Identifiers$1.elementEnd);
  15402. }
  15403. }
  15404. /**
  15405. * Adds an update instruction for an interpolated property or attribute, such as
  15406. * `prop="{{value}}"` or `attr.title="{{value}}"`
  15407. */
  15408. interpolatedUpdateInstruction(instruction, elementIndex, attrName, input, value, params) {
  15409. this.updateInstruction(elementIndex, input.sourceSpan, instruction, () => [literal(attrName), ...this.getUpdateInstructionArguments(value), ...params]);
  15410. }
  15411. visitTemplate(template) {
  15412. const NG_TEMPLATE_TAG_NAME = 'ng-template';
  15413. const templateIndex = this.allocateDataSlot();
  15414. if (this.i18n) {
  15415. this.i18n.appendTemplate(template.i18n, templateIndex);
  15416. }
  15417. const tagName = sanitizeIdentifier(template.tagName || '');
  15418. const contextName = `${this.contextName}${tagName ? '_' + tagName : ''}_${templateIndex}`;
  15419. const templateName = `${contextName}_Template`;
  15420. const parameters = [
  15421. literal(templateIndex),
  15422. variable(templateName),
  15423. // We don't care about the tag's namespace here, because we infer
  15424. // it based on the parent nodes inside the template instruction.
  15425. literal(template.tagName ? splitNsName(template.tagName)[1] : template.tagName),
  15426. ];
  15427. // find directives matching on a given <ng-template> node
  15428. this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
  15429. // prepare attributes parameter (including attributes used for directive matching)
  15430. const attrsExprs = [];
  15431. template.attributes.forEach((a) => { attrsExprs.push(asLiteral(a.name), asLiteral(a.value)); });
  15432. attrsExprs.push(...this.prepareNonRenderAttrs(template.inputs, template.outputs, undefined, template.templateAttrs));
  15433. parameters.push(this.toAttrsParam(attrsExprs));
  15434. // local refs (ex.: <ng-template #foo>)
  15435. if (template.references && template.references.length) {
  15436. parameters.push(this.prepareRefsParameter(template.references));
  15437. parameters.push(importExpr(Identifiers$1.templateRefExtractor));
  15438. }
  15439. // Create the template function
  15440. const 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);
  15441. // Nested templates must not be visited until after their parent templates have completed
  15442. // processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
  15443. // be able to support bindings in nested templates to local refs that occur after the
  15444. // template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
  15445. this._nestedTemplateFns.push(() => {
  15446. const templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, this._ngContentReservedSlots.length + this._ngContentSelectorsOffset, template.i18n);
  15447. this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName, null));
  15448. if (templateVisitor._ngContentReservedSlots.length) {
  15449. this._ngContentReservedSlots.push(...templateVisitor._ngContentReservedSlots);
  15450. }
  15451. });
  15452. // e.g. template(1, MyComp_Template_1)
  15453. this.creationInstruction(template.sourceSpan, Identifiers$1.templateCreate, () => {
  15454. parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
  15455. return trimTrailingNulls(parameters);
  15456. });
  15457. // handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
  15458. this.templatePropertyBindings(templateIndex, template.templateAttrs);
  15459. // Only add normal input/output binding instructions on explicit ng-template elements.
  15460. if (template.tagName === NG_TEMPLATE_TAG_NAME) {
  15461. // Add the input bindings
  15462. this.templatePropertyBindings(templateIndex, template.inputs);
  15463. // Generate listeners for directive output
  15464. template.outputs.forEach((outputAst) => {
  15465. this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, this.prepareListenerParameter('ng_template', outputAst, templateIndex));
  15466. });
  15467. }
  15468. }
  15469. visitBoundText(text) {
  15470. if (this.i18n) {
  15471. const value = text.value.visit(this._valueConverter);
  15472. this.allocateBindingSlots(value);
  15473. if (value instanceof Interpolation) {
  15474. this.i18n.appendBoundText(text.i18n);
  15475. this.i18nAppendBindings(value.expressions);
  15476. }
  15477. return;
  15478. }
  15479. const nodeIndex = this.allocateDataSlot();
  15480. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(nodeIndex)]);
  15481. const value = text.value.visit(this._valueConverter);
  15482. this.allocateBindingSlots(value);
  15483. if (value instanceof Interpolation) {
  15484. this.updateInstruction(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), () => this.getUpdateInstructionArguments(value));
  15485. }
  15486. else {
  15487. this.updateInstruction(nodeIndex, text.sourceSpan, Identifiers$1.textBinding, () => [this.convertPropertyBinding(value)]);
  15488. }
  15489. }
  15490. visitText(text) {
  15491. // when a text element is located within a translatable
  15492. // block, we exclude this text element from instructions set,
  15493. // since it will be captured in i18n content and processed at runtime
  15494. if (!this.i18n) {
  15495. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(this.allocateDataSlot()), literal(text.value)]);
  15496. }
  15497. }
  15498. visitIcu(icu) {
  15499. let initWasInvoked = false;
  15500. // if an ICU was created outside of i18n block, we still treat
  15501. // it as a translatable entity and invoke i18nStart and i18nEnd
  15502. // to generate i18n context and the necessary instructions
  15503. if (!this.i18n) {
  15504. initWasInvoked = true;
  15505. this.i18nStart(null, icu.i18n, true);
  15506. }
  15507. const i18n = this.i18n;
  15508. const vars = this.i18nBindProps(icu.vars);
  15509. const placeholders = this.i18nBindProps(icu.placeholders);
  15510. // output ICU directly and keep ICU reference in context
  15511. const message = icu.i18n;
  15512. const transformFn = (raw) => instruction(null, Identifiers$1.i18nPostprocess, [raw, mapLiteral(vars, true)]);
  15513. // in case the whole i18n message is a single ICU - we do not need to
  15514. // create a separate top-level translation, we can use the root ref instead
  15515. // and make this ICU a top-level translation
  15516. if (isSingleI18nIcu(i18n.meta)) {
  15517. this.i18nTranslate(message, placeholders, i18n.ref, transformFn);
  15518. }
  15519. else {
  15520. // output ICU directly and keep ICU reference in context
  15521. const ref = this.i18nTranslate(message, placeholders, undefined, transformFn);
  15522. i18n.appendIcu(icuFromI18nMessage(message).name, ref);
  15523. }
  15524. if (initWasInvoked) {
  15525. this.i18nEnd(null, true);
  15526. }
  15527. return null;
  15528. }
  15529. allocateDataSlot() { return this._dataIndex++; }
  15530. getConstCount() { return this._dataIndex; }
  15531. getVarCount() { return this._pureFunctionSlots; }
  15532. getNgContentSelectors() {
  15533. return this._ngContentReservedSlots.length ?
  15534. this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
  15535. null;
  15536. }
  15537. bindingContext() { return `${this._bindingContext++}`; }
  15538. templatePropertyBindings(templateIndex, attrs) {
  15539. const propertyBindings = [];
  15540. attrs.forEach(input => {
  15541. if (input instanceof BoundAttribute) {
  15542. const value = input.value.visit(this._valueConverter);
  15543. if (value !== undefined) {
  15544. this.allocateBindingSlots(value);
  15545. propertyBindings.push({
  15546. name: input.name,
  15547. sourceSpan: input.sourceSpan,
  15548. value: () => this.convertPropertyBinding(value)
  15549. });
  15550. }
  15551. }
  15552. });
  15553. if (propertyBindings.length > 0) {
  15554. this.updateInstructionChain(templateIndex, Identifiers$1.property, propertyBindings);
  15555. }
  15556. }
  15557. // Bindings must only be resolved after all local refs have been visited, so all
  15558. // instructions are queued in callbacks that execute once the initial pass has completed.
  15559. // Otherwise, we wouldn't be able to support local refs that are defined after their
  15560. // bindings. e.g. {{ foo }} <div #foo></div>
  15561. instructionFn(fns, span, reference, paramsOrFn, prepend = false) {
  15562. fns[prepend ? 'unshift' : 'push'](() => {
  15563. const params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
  15564. return instruction(span, reference, params).toStmt();
  15565. });
  15566. }
  15567. processStylingInstruction(elementIndex, instruction, createMode) {
  15568. if (instruction) {
  15569. const paramsFn = () => instruction.buildParams(value => this.convertPropertyBinding(value));
  15570. if (createMode) {
  15571. this.creationInstruction(instruction.sourceSpan, instruction.reference, paramsFn);
  15572. }
  15573. else {
  15574. this.updateInstruction(elementIndex, instruction.sourceSpan, instruction.reference, paramsFn);
  15575. }
  15576. }
  15577. }
  15578. creationInstruction(span, reference, paramsOrFn, prepend) {
  15579. this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
  15580. }
  15581. updateInstruction(nodeIndex, span, reference, paramsOrFn) {
  15582. this.addSelectInstructionIfNecessary(nodeIndex, span);
  15583. this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
  15584. }
  15585. updateInstructionChain(nodeIndex, reference, bindings) {
  15586. const span = bindings.length ? bindings[0].sourceSpan : null;
  15587. this.addSelectInstructionIfNecessary(nodeIndex, span);
  15588. this._updateCodeFns.push(() => {
  15589. const calls = bindings.map(property => {
  15590. const fnParams = [property.value(), ...(property.params || [])];
  15591. if (property.name) {
  15592. fnParams.unshift(literal(property.name));
  15593. }
  15594. return fnParams;
  15595. });
  15596. return chainedInstruction(span, reference, calls).toStmt();
  15597. });
  15598. }
  15599. addSelectInstructionIfNecessary(nodeIndex, span) {
  15600. if (this._lastNodeIndexWithFlush < nodeIndex) {
  15601. if (nodeIndex > 0) {
  15602. this.instructionFn(this._updateCodeFns, span, Identifiers$1.select, [literal(nodeIndex)]);
  15603. }
  15604. this._lastNodeIndexWithFlush = nodeIndex;
  15605. }
  15606. }
  15607. allocatePureFunctionSlots(numSlots) {
  15608. const originalSlots = this._pureFunctionSlots;
  15609. this._pureFunctionSlots += numSlots;
  15610. return originalSlots;
  15611. }
  15612. allocateBindingSlots(value) {
  15613. this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
  15614. }
  15615. /**
  15616. * Gets an expression that refers to the implicit receiver. The implicit
  15617. * receiver is always the root level context.
  15618. */
  15619. getImplicitReceiverExpr() {
  15620. if (this._implicitReceiverExpr) {
  15621. return this._implicitReceiverExpr;
  15622. }
  15623. return this._implicitReceiverExpr = this.level === 0 ?
  15624. variable(CONTEXT_NAME) :
  15625. this._bindingScope.getOrCreateSharedContextVar(0);
  15626. }
  15627. convertExpressionBinding(value) {
  15628. const convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple);
  15629. return convertedPropertyBinding.currValExpr;
  15630. }
  15631. convertPropertyBinding(value) {
  15632. const interpolationFn = value instanceof Interpolation ? interpolate : () => error('Unexpected interpolation');
  15633. const convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple, interpolationFn);
  15634. const valExpr = convertedPropertyBinding.currValExpr;
  15635. this._tempVariables.push(...convertedPropertyBinding.stmts);
  15636. return valExpr;
  15637. }
  15638. /**
  15639. * Gets a list of argument expressions to pass to an update instruction expression. Also updates
  15640. * the temp variables state with temp variables that were identified as needing to be created
  15641. * while visiting the arguments.
  15642. * @param value The original expression we will be resolving an arguments list from.
  15643. */
  15644. getUpdateInstructionArguments(value) {
  15645. const { args, stmts } = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext());
  15646. this._tempVariables.push(...stmts);
  15647. return args;
  15648. }
  15649. matchDirectives(tagName, elOrTpl) {
  15650. if (this.directiveMatcher) {
  15651. const selector = createCssSelector(tagName, getAttrsForDirectiveMatching(elOrTpl));
  15652. this.directiveMatcher.match(selector, (cssSelector, staticType) => { this.directives.add(staticType); });
  15653. }
  15654. }
  15655. /**
  15656. * Prepares all attribute expression values for the `TAttributes` array.
  15657. *
  15658. * The purpose of this function is to properly construct an attributes array that
  15659. * is passed into the `elementStart` (or just `element`) functions. Because there
  15660. * are many different types of attributes, the array needs to be constructed in a
  15661. * special way so that `elementStart` can properly evaluate them.
  15662. *
  15663. * The format looks like this:
  15664. *
  15665. * ```
  15666. * attrs = [prop, value, prop2, value2,
  15667. * CLASSES, class1, class2,
  15668. * STYLES, style1, value1, style2, value2,
  15669. * BINDINGS, name1, name2, name3,
  15670. * TEMPLATE, name4, name5, name6,
  15671. * I18N, name7, name8, ...]
  15672. * ```
  15673. *
  15674. * Note that this function will fully ignore all synthetic (@foo) attribute values
  15675. * because those values are intended to always be generated as property instructions.
  15676. */
  15677. prepareNonRenderAttrs(inputs, outputs, styles, templateAttrs = [], i18nAttrs = []) {
  15678. const alreadySeen = new Set();
  15679. const attrExprs = [];
  15680. function addAttrExpr(key, value) {
  15681. if (typeof key === 'string') {
  15682. if (!alreadySeen.has(key)) {
  15683. attrExprs.push(...getAttributeNameLiterals(key));
  15684. value !== undefined && attrExprs.push(value);
  15685. alreadySeen.add(key);
  15686. }
  15687. }
  15688. else {
  15689. attrExprs.push(literal(key));
  15690. }
  15691. }
  15692. // it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
  15693. // comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
  15694. // as single property value cell by cell.
  15695. if (styles) {
  15696. styles.populateInitialStylingAttrs(attrExprs);
  15697. }
  15698. if (inputs.length || outputs.length) {
  15699. const attrsStartIndex = attrExprs.length;
  15700. for (let i = 0; i < inputs.length; i++) {
  15701. const input = inputs[i];
  15702. if (input.type !== 4 /* Animation */) {
  15703. addAttrExpr(input.name);
  15704. }
  15705. }
  15706. for (let i = 0; i < outputs.length; i++) {
  15707. const output = outputs[i];
  15708. if (output.type !== 1 /* Animation */) {
  15709. addAttrExpr(output.name);
  15710. }
  15711. }
  15712. // this is a cheap way of adding the marker only after all the input/output
  15713. // values have been filtered (by not including the animation ones) and added
  15714. // to the expressions. The marker is important because it tells the runtime
  15715. // code that this is where attributes without values start...
  15716. if (attrExprs.length) {
  15717. attrExprs.splice(attrsStartIndex, 0, literal(3 /* Bindings */));
  15718. }
  15719. }
  15720. if (templateAttrs.length) {
  15721. attrExprs.push(literal(4 /* Template */));
  15722. templateAttrs.forEach(attr => addAttrExpr(attr.name));
  15723. }
  15724. if (i18nAttrs.length) {
  15725. attrExprs.push(literal(6 /* I18n */));
  15726. i18nAttrs.forEach(attr => addAttrExpr(attr.name));
  15727. }
  15728. return attrExprs;
  15729. }
  15730. toAttrsParam(attrsExprs) {
  15731. return attrsExprs.length > 0 ?
  15732. this.constantPool.getConstLiteral(literalArr(attrsExprs), true) :
  15733. TYPED_NULL_EXPR;
  15734. }
  15735. prepareRefsParameter(references) {
  15736. if (!references || references.length === 0) {
  15737. return TYPED_NULL_EXPR;
  15738. }
  15739. const refsParam = flatten(references.map(reference => {
  15740. const slot = this.allocateDataSlot();
  15741. // Generate the update temporary.
  15742. const variableName = this._bindingScope.freshReferenceName();
  15743. const retrievalLevel = this.level;
  15744. const lhs = variable(variableName);
  15745. this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, (scope, relativeLevel) => {
  15746. // e.g. nextContext(2);
  15747. const nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
  15748. // e.g. const $foo$ = reference(1);
  15749. const refExpr = lhs.set(importExpr(Identifiers$1.reference).callFn([literal(slot)]));
  15750. return nextContextStmt.concat(refExpr.toConstDecl());
  15751. }, true);
  15752. return [reference.name, reference.value];
  15753. }));
  15754. return this.constantPool.getConstLiteral(asLiteral(refsParam), true);
  15755. }
  15756. prepareListenerParameter(tagName, outputAst, index) {
  15757. return () => {
  15758. const eventName = outputAst.name;
  15759. const bindingFnName = outputAst.type === 1 /* Animation */ ?
  15760. // synthetic @listener.foo values are treated the exact same as are standard listeners
  15761. prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
  15762. sanitizeIdentifier(eventName);
  15763. const handlerName = `${this.templateName}_${tagName}_${bindingFnName}_${index}_listener`;
  15764. const scope = this._bindingScope.nestedScope(this._bindingScope.bindingLevel);
  15765. return prepareEventListenerParameters(outputAst, handlerName, scope);
  15766. };
  15767. }
  15768. }
  15769. class ValueConverter extends AstMemoryEfficientTransformer {
  15770. constructor(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
  15771. super();
  15772. this.constantPool = constantPool;
  15773. this.allocateSlot = allocateSlot;
  15774. this.allocatePureFunctionSlots = allocatePureFunctionSlots;
  15775. this.definePipe = definePipe;
  15776. this._pipeBindExprs = [];
  15777. }
  15778. // AstMemoryEfficientTransformer
  15779. visitPipe(pipe, context) {
  15780. // Allocate a slot to create the pipe
  15781. const slot = this.allocateSlot();
  15782. const slotPseudoLocal = `PIPE:${slot}`;
  15783. // Allocate one slot for the result plus one slot per pipe argument
  15784. const pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
  15785. const target = new PropertyRead(pipe.span, new ImplicitReceiver(pipe.span), slotPseudoLocal);
  15786. const { identifier, isVarLength } = pipeBindingCallInfo(pipe.args);
  15787. this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
  15788. const args = [pipe.exp, ...pipe.args];
  15789. const convertedArgs = isVarLength ? this.visitAll([new LiteralArray(pipe.span, args)]) : this.visitAll(args);
  15790. const pipeBindExpr = new FunctionCall(pipe.span, target, [
  15791. new LiteralPrimitive(pipe.span, slot),
  15792. new LiteralPrimitive(pipe.span, pureFunctionSlot),
  15793. ...convertedArgs,
  15794. ]);
  15795. this._pipeBindExprs.push(pipeBindExpr);
  15796. return pipeBindExpr;
  15797. }
  15798. updatePipeSlotOffsets(bindingSlots) {
  15799. this._pipeBindExprs.forEach((pipe) => {
  15800. // update the slot offset arg (index 1) to account for binding slots
  15801. const slotOffset = pipe.args[1];
  15802. slotOffset.value += bindingSlots;
  15803. });
  15804. }
  15805. visitLiteralArray(array, context) {
  15806. return new BuiltinFunctionCall(array.span, this.visitAll(array.expressions), values => {
  15807. // If the literal has calculated (non-literal) elements transform it into
  15808. // calls to literal factories that compose the literal and will cache intermediate
  15809. // values. Otherwise, just return an literal array that contains the values.
  15810. const literal = literalArr(values);
  15811. return values.every(a => a.isConstant()) ?
  15812. this.constantPool.getConstLiteral(literal, true) :
  15813. getLiteralFactory(this.constantPool, literal, this.allocatePureFunctionSlots);
  15814. });
  15815. }
  15816. visitLiteralMap(map, context) {
  15817. return new BuiltinFunctionCall(map.span, this.visitAll(map.values), values => {
  15818. // If the literal has calculated (non-literal) elements transform it into
  15819. // calls to literal factories that compose the literal and will cache intermediate
  15820. // values. Otherwise, just return an literal array that contains the values.
  15821. const literal = literalMap(values.map((value, index) => ({ key: map.keys[index].key, value, quoted: map.keys[index].quoted })));
  15822. return values.every(a => a.isConstant()) ?
  15823. this.constantPool.getConstLiteral(literal, true) :
  15824. getLiteralFactory(this.constantPool, literal, this.allocatePureFunctionSlots);
  15825. });
  15826. }
  15827. }
  15828. // Pipes always have at least one parameter, the value they operate on
  15829. const pipeBindingIdentifiers = [Identifiers$1.pipeBind1, Identifiers$1.pipeBind2, Identifiers$1.pipeBind3, Identifiers$1.pipeBind4];
  15830. function pipeBindingCallInfo(args) {
  15831. const identifier = pipeBindingIdentifiers[args.length];
  15832. return {
  15833. identifier: identifier || Identifiers$1.pipeBindV,
  15834. isVarLength: !identifier,
  15835. };
  15836. }
  15837. const pureFunctionIdentifiers = [
  15838. Identifiers$1.pureFunction0, Identifiers$1.pureFunction1, Identifiers$1.pureFunction2, Identifiers$1.pureFunction3, Identifiers$1.pureFunction4,
  15839. Identifiers$1.pureFunction5, Identifiers$1.pureFunction6, Identifiers$1.pureFunction7, Identifiers$1.pureFunction8
  15840. ];
  15841. function pureFunctionCallInfo(args) {
  15842. const identifier = pureFunctionIdentifiers[args.length];
  15843. return {
  15844. identifier: identifier || Identifiers$1.pureFunctionV,
  15845. isVarLength: !identifier,
  15846. };
  15847. }
  15848. function instruction(span, reference, params) {
  15849. return importExpr(reference, null, span).callFn(params, span);
  15850. }
  15851. function chainedInstruction(span, reference, calls) {
  15852. let expression = importExpr(reference, null, span);
  15853. if (calls.length > 0) {
  15854. for (let i = 0; i < calls.length; i++) {
  15855. expression = expression.callFn(calls[i], span);
  15856. }
  15857. }
  15858. else {
  15859. // Add a blank invocation, in case the `calls` array is empty.
  15860. expression = expression.callFn([], span);
  15861. }
  15862. return expression;
  15863. }
  15864. // e.g. x(2);
  15865. function generateNextContextExpr(relativeLevelDiff) {
  15866. return importExpr(Identifiers$1.nextContext)
  15867. .callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
  15868. }
  15869. function getLiteralFactory(constantPool, literal$1, allocateSlots) {
  15870. const { literalFactory, literalFactoryArguments } = constantPool.getLiteralFactory(literal$1);
  15871. // Allocate 1 slot for the result plus 1 per argument
  15872. const startSlot = allocateSlots(1 + literalFactoryArguments.length);
  15873. literalFactoryArguments.length > 0 || error(`Expected arguments to a literal factory function`);
  15874. const { identifier, isVarLength } = pureFunctionCallInfo(literalFactoryArguments);
  15875. // Literal factories are pure functions that only need to be re-invoked when the parameters
  15876. // change.
  15877. const args = [
  15878. literal(startSlot),
  15879. literalFactory,
  15880. ];
  15881. if (isVarLength) {
  15882. args.push(literalArr(literalFactoryArguments));
  15883. }
  15884. else {
  15885. args.push(...literalFactoryArguments);
  15886. }
  15887. return importExpr(identifier).callFn(args);
  15888. }
  15889. /**
  15890. * Gets an array of literals that can be added to an expression
  15891. * to represent the name and namespace of an attribute. E.g.
  15892. * `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
  15893. *
  15894. * @param name Name of the attribute, including the namespace.
  15895. */
  15896. function getAttributeNameLiterals(name) {
  15897. const [attributeNamespace, attributeName] = splitNsName(name);
  15898. const nameLiteral = literal(attributeName);
  15899. if (attributeNamespace) {
  15900. return [
  15901. literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
  15902. ];
  15903. }
  15904. return [nameLiteral];
  15905. }
  15906. /** The prefix used to get a shared context in BindingScope's map. */
  15907. const SHARED_CONTEXT_KEY = '$$shared_ctx$$';
  15908. class BindingScope {
  15909. constructor(bindingLevel = 0, parent = null) {
  15910. this.bindingLevel = bindingLevel;
  15911. this.parent = parent;
  15912. /** Keeps a map from local variables to their BindingData. */
  15913. this.map = new Map();
  15914. this.referenceNameIndex = 0;
  15915. this.restoreViewVariable = null;
  15916. }
  15917. static get ROOT_SCOPE() {
  15918. if (!BindingScope._ROOT_SCOPE) {
  15919. BindingScope._ROOT_SCOPE = new BindingScope().set(0, '$event', variable('$event'));
  15920. }
  15921. return BindingScope._ROOT_SCOPE;
  15922. }
  15923. get(name) {
  15924. let current = this;
  15925. while (current) {
  15926. let value = current.map.get(name);
  15927. if (value != null) {
  15928. if (current !== this) {
  15929. // make a local copy and reset the `declare` state
  15930. value = {
  15931. retrievalLevel: value.retrievalLevel,
  15932. lhs: value.lhs,
  15933. declareLocalCallback: value.declareLocalCallback,
  15934. declare: false,
  15935. priority: value.priority,
  15936. localRef: value.localRef
  15937. };
  15938. // Cache the value locally.
  15939. this.map.set(name, value);
  15940. // Possibly generate a shared context var
  15941. this.maybeGenerateSharedContextVar(value);
  15942. this.maybeRestoreView(value.retrievalLevel, value.localRef);
  15943. }
  15944. if (value.declareLocalCallback && !value.declare) {
  15945. value.declare = true;
  15946. }
  15947. return value.lhs;
  15948. }
  15949. current = current.parent;
  15950. }
  15951. // If we get to this point, we are looking for a property on the top level component
  15952. // - If level === 0, we are on the top and don't need to re-declare `ctx`.
  15953. // - If level > 0, we are in an embedded view. We need to retrieve the name of the
  15954. // local var we used to store the component context, e.g. const $comp$ = x();
  15955. return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
  15956. }
  15957. /**
  15958. * Create a local variable for later reference.
  15959. *
  15960. * @param retrievalLevel The level from which this value can be retrieved
  15961. * @param name Name of the variable.
  15962. * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
  15963. * @param priority The sorting priority of this var
  15964. * @param declareLocalCallback The callback to invoke when declaring this local var
  15965. * @param localRef Whether or not this is a local ref
  15966. */
  15967. set(retrievalLevel, name, lhs, priority = 0 /* DEFAULT */, declareLocalCallback, localRef) {
  15968. if (this.map.has(name)) {
  15969. if (localRef) {
  15970. // Do not throw an error if it's a local ref and do not update existing value,
  15971. // so the first defined ref is always returned.
  15972. return this;
  15973. }
  15974. error(`The name ${name} is already defined in scope to be ${this.map.get(name)}`);
  15975. }
  15976. this.map.set(name, {
  15977. retrievalLevel: retrievalLevel,
  15978. lhs: lhs,
  15979. declare: false,
  15980. declareLocalCallback: declareLocalCallback,
  15981. priority: priority,
  15982. localRef: localRef || false
  15983. });
  15984. return this;
  15985. }
  15986. // Implemented as part of LocalResolver.
  15987. getLocal(name) { return this.get(name); }
  15988. // Implemented as part of LocalResolver.
  15989. notifyImplicitReceiverUse() {
  15990. if (this.bindingLevel !== 0) {
  15991. // Since the implicit receiver is accessed in an embedded view, we need to
  15992. // ensure that we declare a shared context variable for the current template
  15993. // in the update variables.
  15994. this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
  15995. }
  15996. }
  15997. nestedScope(level) {
  15998. const newScope = new BindingScope(level, this);
  15999. if (level > 0)
  16000. newScope.generateSharedContextVar(0);
  16001. return newScope;
  16002. }
  16003. /**
  16004. * Gets or creates a shared context variable and returns its expression. Note that
  16005. * this does not mean that the shared variable will be declared. Variables in the
  16006. * binding scope will be only declared if they are used.
  16007. */
  16008. getOrCreateSharedContextVar(retrievalLevel) {
  16009. const bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
  16010. if (!this.map.has(bindingKey)) {
  16011. this.generateSharedContextVar(retrievalLevel);
  16012. }
  16013. return this.map.get(bindingKey).lhs;
  16014. }
  16015. getSharedContextName(retrievalLevel) {
  16016. const sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
  16017. return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
  16018. }
  16019. maybeGenerateSharedContextVar(value) {
  16020. if (value.priority === 1 /* CONTEXT */ &&
  16021. value.retrievalLevel < this.bindingLevel) {
  16022. const sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
  16023. if (sharedCtxObj) {
  16024. sharedCtxObj.declare = true;
  16025. }
  16026. else {
  16027. this.generateSharedContextVar(value.retrievalLevel);
  16028. }
  16029. }
  16030. }
  16031. generateSharedContextVar(retrievalLevel) {
  16032. const lhs = variable(CONTEXT_NAME + this.freshReferenceName());
  16033. this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
  16034. retrievalLevel: retrievalLevel,
  16035. lhs: lhs,
  16036. declareLocalCallback: (scope, relativeLevel) => {
  16037. // const ctx_r0 = nextContext(2);
  16038. return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
  16039. },
  16040. declare: false,
  16041. priority: 2 /* SHARED_CONTEXT */,
  16042. localRef: false
  16043. });
  16044. }
  16045. getComponentProperty(name) {
  16046. const componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
  16047. componentValue.declare = true;
  16048. this.maybeRestoreView(0, false);
  16049. return componentValue.lhs.prop(name);
  16050. }
  16051. maybeRestoreView(retrievalLevel, localRefLookup) {
  16052. // We want to restore the current view in listener fns if:
  16053. // 1 - we are accessing a value in a parent view, which requires walking the view tree rather
  16054. // than using the ctx arg. In this case, the retrieval and binding level will be different.
  16055. // 2 - we are looking up a local ref, which requires restoring the view where the local
  16056. // ref is stored
  16057. if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
  16058. if (!this.parent.restoreViewVariable) {
  16059. // parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
  16060. this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
  16061. }
  16062. this.restoreViewVariable = this.parent.restoreViewVariable;
  16063. }
  16064. }
  16065. restoreViewStatement() {
  16066. // restoreView($state$);
  16067. return this.restoreViewVariable ?
  16068. [instruction(null, Identifiers$1.restoreView, [this.restoreViewVariable]).toStmt()] :
  16069. [];
  16070. }
  16071. viewSnapshotStatements() {
  16072. // const $state$ = getCurrentView();
  16073. const getCurrentViewInstruction = instruction(null, Identifiers$1.getCurrentView, []);
  16074. return this.restoreViewVariable ?
  16075. [this.restoreViewVariable.set(getCurrentViewInstruction).toConstDecl()] :
  16076. [];
  16077. }
  16078. isListenerScope() { return this.parent && this.parent.bindingLevel === this.bindingLevel; }
  16079. variableDeclarations() {
  16080. let currentContextLevel = 0;
  16081. return Array.from(this.map.values())
  16082. .filter(value => value.declare)
  16083. .sort((a, b) => b.retrievalLevel - a.retrievalLevel || b.priority - a.priority)
  16084. .reduce((stmts, value) => {
  16085. const levelDiff = this.bindingLevel - value.retrievalLevel;
  16086. const currStmts = value.declareLocalCallback(this, levelDiff - currentContextLevel);
  16087. currentContextLevel = levelDiff;
  16088. return stmts.concat(currStmts);
  16089. }, []);
  16090. }
  16091. freshReferenceName() {
  16092. let current = this;
  16093. // Find the top scope as it maintains the global reference count
  16094. while (current.parent)
  16095. current = current.parent;
  16096. const ref = `${REFERENCE_PREFIX}${current.referenceNameIndex++}`;
  16097. return ref;
  16098. }
  16099. }
  16100. /**
  16101. * Creates a `CssSelector` given a tag name and a map of attributes
  16102. */
  16103. function createCssSelector(tag, attributes) {
  16104. const cssSelector = new CssSelector();
  16105. cssSelector.setElement(tag);
  16106. Object.getOwnPropertyNames(attributes).forEach((name) => {
  16107. const value = attributes[name];
  16108. cssSelector.addAttribute(name, value);
  16109. if (name.toLowerCase() === 'class') {
  16110. const classes = value.trim().split(/\s+/);
  16111. classes.forEach(className => cssSelector.addClassName(className));
  16112. }
  16113. });
  16114. return cssSelector;
  16115. }
  16116. /**
  16117. * Creates an array of expressions out of an `ngProjectAs` attributes
  16118. * which can be added to the instruction parameters.
  16119. */
  16120. function getNgProjectAsLiteral(attribute) {
  16121. // Parse the attribute value into a CssSelectorList. Note that we only take the
  16122. // first selector, because we don't support multiple selectors in ngProjectAs.
  16123. const parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
  16124. return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
  16125. }
  16126. function interpolate(args) {
  16127. args = args.slice(1); // Ignore the length prefix added for render2
  16128. switch (args.length) {
  16129. case 3:
  16130. return importExpr(Identifiers$1.interpolation1).callFn(args);
  16131. case 5:
  16132. return importExpr(Identifiers$1.interpolation2).callFn(args);
  16133. case 7:
  16134. return importExpr(Identifiers$1.interpolation3).callFn(args);
  16135. case 9:
  16136. return importExpr(Identifiers$1.interpolation4).callFn(args);
  16137. case 11:
  16138. return importExpr(Identifiers$1.interpolation5).callFn(args);
  16139. case 13:
  16140. return importExpr(Identifiers$1.interpolation6).callFn(args);
  16141. case 15:
  16142. return importExpr(Identifiers$1.interpolation7).callFn(args);
  16143. case 17:
  16144. return importExpr(Identifiers$1.interpolation8).callFn(args);
  16145. }
  16146. (args.length >= 19 && args.length % 2 == 1) ||
  16147. error(`Invalid interpolation argument length ${args.length}`);
  16148. return importExpr(Identifiers$1.interpolationV).callFn([literalArr(args)]);
  16149. }
  16150. /**
  16151. * Gets the instruction to generate for an interpolated property
  16152. * @param interpolation An Interpolation AST
  16153. */
  16154. function getPropertyInterpolationExpression(interpolation) {
  16155. switch (getInterpolationArgsLength(interpolation)) {
  16156. case 1:
  16157. return Identifiers$1.propertyInterpolate;
  16158. case 3:
  16159. return Identifiers$1.propertyInterpolate1;
  16160. case 5:
  16161. return Identifiers$1.propertyInterpolate2;
  16162. case 7:
  16163. return Identifiers$1.propertyInterpolate3;
  16164. case 9:
  16165. return Identifiers$1.propertyInterpolate4;
  16166. case 11:
  16167. return Identifiers$1.propertyInterpolate5;
  16168. case 13:
  16169. return Identifiers$1.propertyInterpolate6;
  16170. case 15:
  16171. return Identifiers$1.propertyInterpolate7;
  16172. case 17:
  16173. return Identifiers$1.propertyInterpolate8;
  16174. default:
  16175. return Identifiers$1.propertyInterpolateV;
  16176. }
  16177. }
  16178. /**
  16179. * Gets the instruction to generate for an interpolated attribute
  16180. * @param interpolation An Interpolation AST
  16181. */
  16182. function getAttributeInterpolationExpression(interpolation) {
  16183. switch (getInterpolationArgsLength(interpolation)) {
  16184. case 3:
  16185. return Identifiers$1.attributeInterpolate1;
  16186. case 5:
  16187. return Identifiers$1.attributeInterpolate2;
  16188. case 7:
  16189. return Identifiers$1.attributeInterpolate3;
  16190. case 9:
  16191. return Identifiers$1.attributeInterpolate4;
  16192. case 11:
  16193. return Identifiers$1.attributeInterpolate5;
  16194. case 13:
  16195. return Identifiers$1.attributeInterpolate6;
  16196. case 15:
  16197. return Identifiers$1.attributeInterpolate7;
  16198. case 17:
  16199. return Identifiers$1.attributeInterpolate8;
  16200. default:
  16201. return Identifiers$1.attributeInterpolateV;
  16202. }
  16203. }
  16204. /**
  16205. * Gets the instruction to generate for interpolated text.
  16206. * @param interpolation An Interpolation AST
  16207. */
  16208. function getTextInterpolationExpression(interpolation) {
  16209. switch (getInterpolationArgsLength(interpolation)) {
  16210. case 1:
  16211. return Identifiers$1.textInterpolate;
  16212. case 3:
  16213. return Identifiers$1.textInterpolate1;
  16214. case 5:
  16215. return Identifiers$1.textInterpolate2;
  16216. case 7:
  16217. return Identifiers$1.textInterpolate3;
  16218. case 9:
  16219. return Identifiers$1.textInterpolate4;
  16220. case 11:
  16221. return Identifiers$1.textInterpolate5;
  16222. case 13:
  16223. return Identifiers$1.textInterpolate6;
  16224. case 15:
  16225. return Identifiers$1.textInterpolate7;
  16226. case 17:
  16227. return Identifiers$1.textInterpolate8;
  16228. default:
  16229. return Identifiers$1.textInterpolateV;
  16230. }
  16231. }
  16232. /**
  16233. * Gets the number of arguments expected to be passed to a generated instruction in the case of
  16234. * interpolation instructions.
  16235. * @param interpolation An interpolation ast
  16236. */
  16237. function getInterpolationArgsLength(interpolation) {
  16238. const { expressions, strings } = interpolation;
  16239. if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
  16240. // If the interpolation has one interpolated value, but the prefix and suffix are both empty
  16241. // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
  16242. // `textInterpolate`.
  16243. return 1;
  16244. }
  16245. else {
  16246. return expressions.length + strings.length;
  16247. }
  16248. }
  16249. /**
  16250. * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
  16251. *
  16252. * @param template text of the template to parse
  16253. * @param templateUrl URL to use for source mapping of the parsed template
  16254. * @param options options to modify how the template is parsed
  16255. */
  16256. function parseTemplate(template, templateUrl, options = {}) {
  16257. const { interpolationConfig, preserveWhitespaces } = options;
  16258. const bindingParser = makeBindingParser(interpolationConfig);
  16259. const htmlParser = new HtmlParser();
  16260. const parseResult = htmlParser.parse(template, templateUrl, Object.assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options, { tokenizeExpansionForms: true }));
  16261. if (parseResult.errors && parseResult.errors.length > 0) {
  16262. return { errors: parseResult.errors, nodes: [], styleUrls: [], styles: [] };
  16263. }
  16264. let rootNodes = parseResult.rootNodes;
  16265. // process i18n meta information (scan attributes, generate ids)
  16266. // before we run whitespace removal process, because existing i18n
  16267. // extraction process (ng xi18n) relies on a raw content to generate
  16268. // message ids
  16269. rootNodes =
  16270. visitAll$1(new I18nMetaVisitor(interpolationConfig, !preserveWhitespaces), rootNodes);
  16271. if (!preserveWhitespaces) {
  16272. rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
  16273. // run i18n meta visitor again in case we remove whitespaces, because
  16274. // that might affect generated i18n message content. During this pass
  16275. // i18n IDs generated at the first pass will be preserved, so we can mimic
  16276. // existing extraction process (ng xi18n)
  16277. rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
  16278. }
  16279. const { nodes, errors, styleUrls, styles } = htmlAstToRender3Ast(rootNodes, bindingParser);
  16280. if (errors && errors.length > 0) {
  16281. return { errors, nodes: [], styleUrls: [], styles: [] };
  16282. }
  16283. return { nodes, styleUrls, styles };
  16284. }
  16285. /**
  16286. * Construct a `BindingParser` with a default configuration.
  16287. */
  16288. function makeBindingParser(interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
  16289. return new BindingParser(new Parser$1(new Lexer()), interpolationConfig, new DomElementSchemaRegistry(), null, []);
  16290. }
  16291. function resolveSanitizationFn(context, isAttribute) {
  16292. switch (context) {
  16293. case SecurityContext.HTML:
  16294. return importExpr(Identifiers$1.sanitizeHtml);
  16295. case SecurityContext.SCRIPT:
  16296. return importExpr(Identifiers$1.sanitizeScript);
  16297. case SecurityContext.STYLE:
  16298. // the compiler does not fill in an instruction for [style.prop?] binding
  16299. // values because the style algorithm knows internally what props are subject
  16300. // to sanitization (only [attr.style] values are explicitly sanitized)
  16301. return isAttribute ? importExpr(Identifiers$1.sanitizeStyle) : null;
  16302. case SecurityContext.URL:
  16303. return importExpr(Identifiers$1.sanitizeUrl);
  16304. case SecurityContext.RESOURCE_URL:
  16305. return importExpr(Identifiers$1.sanitizeResourceUrl);
  16306. default:
  16307. return null;
  16308. }
  16309. }
  16310. function isSingleElementTemplate(children) {
  16311. return children.length === 1 && children[0] instanceof Element;
  16312. }
  16313. function isTextNode(node) {
  16314. return node instanceof Text || node instanceof BoundText || node instanceof Icu;
  16315. }
  16316. function hasTextChildrenOnly(children) {
  16317. return children.every(isTextNode);
  16318. }
  16319. /**
  16320. * @license
  16321. * Copyright Google Inc. All Rights Reserved.
  16322. *
  16323. * Use of this source code is governed by an MIT-style license that can be
  16324. * found in the LICENSE file at https://angular.io/license
  16325. */
  16326. const EMPTY_ARRAY = [];
  16327. // This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
  16328. // If there is a match, the first matching group will contain the attribute name to bind.
  16329. const ATTR_REGEX = /attr\.([^\]]+)/;
  16330. function getStylingPrefix(name) {
  16331. return name.substring(0, 5); // style or class
  16332. }
  16333. function baseDirectiveFields(meta, constantPool, bindingParser) {
  16334. const definitionMap = new DefinitionMap();
  16335. // e.g. `type: MyDirective`
  16336. definitionMap.set('type', meta.type);
  16337. // e.g. `selectors: [['', 'someDir', '']]`
  16338. definitionMap.set('selectors', createDirectiveSelector(meta.selector));
  16339. // e.g. `factory: () => new MyApp(directiveInject(ElementRef))`
  16340. const result = compileFactoryFunction({
  16341. name: meta.name,
  16342. type: meta.type,
  16343. deps: meta.deps,
  16344. injectFn: Identifiers$1.directiveInject,
  16345. });
  16346. definitionMap.set('factory', result.factory);
  16347. if (meta.queries.length > 0) {
  16348. // e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
  16349. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
  16350. }
  16351. if (meta.viewQueries.length) {
  16352. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
  16353. }
  16354. // e.g. `hostBindings: (rf, ctx, elIndex) => { ... }
  16355. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name));
  16356. // e.g 'inputs: {a: 'a'}`
  16357. definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
  16358. // e.g 'outputs: {a: 'a'}`
  16359. definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
  16360. if (meta.exportAs !== null) {
  16361. definitionMap.set('exportAs', literalArr(meta.exportAs.map(e => literal(e))));
  16362. }
  16363. return { definitionMap, statements: result.statements };
  16364. }
  16365. /**
  16366. * Add features to the definition map.
  16367. */
  16368. function addFeatures(definitionMap, meta) {
  16369. // e.g. `features: [NgOnChangesFeature()]`
  16370. const features = [];
  16371. const providers = meta.providers;
  16372. const viewProviders = meta.viewProviders;
  16373. if (providers || viewProviders) {
  16374. const args = [providers || new LiteralArrayExpr([])];
  16375. if (viewProviders) {
  16376. args.push(viewProviders);
  16377. }
  16378. features.push(importExpr(Identifiers$1.ProvidersFeature).callFn(args));
  16379. }
  16380. if (meta.usesInheritance) {
  16381. features.push(importExpr(Identifiers$1.InheritDefinitionFeature));
  16382. }
  16383. if (meta.lifecycle.usesOnChanges) {
  16384. features.push(importExpr(Identifiers$1.NgOnChangesFeature).callFn(EMPTY_ARRAY));
  16385. }
  16386. if (features.length) {
  16387. definitionMap.set('features', literalArr(features));
  16388. }
  16389. }
  16390. /**
  16391. * Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
  16392. */
  16393. function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
  16394. const { definitionMap, statements } = baseDirectiveFields(meta, constantPool, bindingParser);
  16395. addFeatures(definitionMap, meta);
  16396. const expression = importExpr(Identifiers$1.defineDirective).callFn([definitionMap.toLiteralMap()]);
  16397. if (!meta.selector) {
  16398. throw new Error(`Directive ${meta.name} has no selector, please add it!`);
  16399. }
  16400. const type = createTypeForDef(meta, Identifiers$1.DirectiveDefWithMeta);
  16401. return { expression, type, statements };
  16402. }
  16403. /**
  16404. * Compile a base definition for the render3 runtime as defined by {@link R3BaseRefMetadata}
  16405. * @param meta the metadata used for compilation.
  16406. */
  16407. function compileBaseDefFromMetadata(meta, constantPool, bindingParser) {
  16408. const definitionMap = new DefinitionMap();
  16409. if (meta.inputs) {
  16410. const inputs = meta.inputs;
  16411. const inputsMap = Object.keys(inputs).map(key => {
  16412. const v = inputs[key];
  16413. const value = Array.isArray(v) ? literalArr(v.map(vx => literal(vx))) : literal(v);
  16414. return { key, value, quoted: false };
  16415. });
  16416. definitionMap.set('inputs', literalMap(inputsMap));
  16417. }
  16418. if (meta.outputs) {
  16419. const outputs = meta.outputs;
  16420. const outputsMap = Object.keys(outputs).map(key => {
  16421. const value = literal(outputs[key]);
  16422. return { key, value, quoted: false };
  16423. });
  16424. definitionMap.set('outputs', literalMap(outputsMap));
  16425. }
  16426. if (meta.viewQueries && meta.viewQueries.length > 0) {
  16427. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool));
  16428. }
  16429. if (meta.queries && meta.queries.length > 0) {
  16430. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool));
  16431. }
  16432. if (meta.host) {
  16433. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.name));
  16434. }
  16435. const expression = importExpr(Identifiers$1.defineBase).callFn([definitionMap.toLiteralMap()]);
  16436. const type = new ExpressionType(importExpr(Identifiers$1.BaseDef));
  16437. return { expression, type };
  16438. }
  16439. /**
  16440. * Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
  16441. */
  16442. function compileComponentFromMetadata(meta, constantPool, bindingParser) {
  16443. const { definitionMap, statements } = baseDirectiveFields(meta, constantPool, bindingParser);
  16444. addFeatures(definitionMap, meta);
  16445. const selector = meta.selector && CssSelector.parse(meta.selector);
  16446. const firstSelector = selector && selector[0];
  16447. // e.g. `attr: ["class", ".my.app"]`
  16448. // This is optional an only included if the first selector of a component specifies attributes.
  16449. if (firstSelector) {
  16450. const selectorAttributes = firstSelector.getAttrs();
  16451. if (selectorAttributes.length) {
  16452. definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(value => value != null ? literal(value) : literal(undefined))),
  16453. /* forceShared */ true));
  16454. }
  16455. }
  16456. // Generate the CSS matcher that recognize directive
  16457. let directiveMatcher = null;
  16458. if (meta.directives.length > 0) {
  16459. const matcher = new SelectorMatcher();
  16460. for (const { selector, expression } of meta.directives) {
  16461. matcher.addSelectables(CssSelector.parse(selector), expression);
  16462. }
  16463. directiveMatcher = matcher;
  16464. }
  16465. // e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
  16466. const templateTypeName = meta.name;
  16467. const templateName = templateTypeName ? `${templateTypeName}_Template` : null;
  16468. const directivesUsed = new Set();
  16469. const pipesUsed = new Set();
  16470. const changeDetection = meta.changeDetection;
  16471. const template = meta.template;
  16472. const templateBuilder = new TemplateDefinitionBuilder(constantPool, BindingScope.ROOT_SCOPE, 0, templateTypeName, null, null, templateName, directiveMatcher, directivesUsed, meta.pipes, pipesUsed, Identifiers$1.namespaceHTML, meta.relativeContextFilePath, meta.i18nUseExternalIds);
  16473. const templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
  16474. // We need to provide this so that dynamically generated components know what
  16475. // projected content blocks to pass through to the component when it is instantiated.
  16476. const ngContentSelectors = templateBuilder.getNgContentSelectors();
  16477. if (ngContentSelectors) {
  16478. definitionMap.set('ngContentSelectors', ngContentSelectors);
  16479. }
  16480. // e.g. `consts: 2`
  16481. definitionMap.set('consts', literal(templateBuilder.getConstCount()));
  16482. // e.g. `vars: 2`
  16483. definitionMap.set('vars', literal(templateBuilder.getVarCount()));
  16484. definitionMap.set('template', templateFunctionExpression);
  16485. // e.g. `directives: [MyDirective]`
  16486. if (directivesUsed.size) {
  16487. let directivesExpr = literalArr(Array.from(directivesUsed));
  16488. if (meta.wrapDirectivesAndPipesInClosure) {
  16489. directivesExpr = fn([], [new ReturnStatement(directivesExpr)]);
  16490. }
  16491. definitionMap.set('directives', directivesExpr);
  16492. }
  16493. // e.g. `pipes: [MyPipe]`
  16494. if (pipesUsed.size) {
  16495. let pipesExpr = literalArr(Array.from(pipesUsed));
  16496. if (meta.wrapDirectivesAndPipesInClosure) {
  16497. pipesExpr = fn([], [new ReturnStatement(pipesExpr)]);
  16498. }
  16499. definitionMap.set('pipes', pipesExpr);
  16500. }
  16501. if (meta.encapsulation === null) {
  16502. meta.encapsulation = ViewEncapsulation.Emulated;
  16503. }
  16504. // e.g. `styles: [str1, str2]`
  16505. if (meta.styles && meta.styles.length) {
  16506. const styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
  16507. compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
  16508. meta.styles;
  16509. const strings = styleValues.map(str => literal(str));
  16510. definitionMap.set('styles', literalArr(strings));
  16511. }
  16512. else if (meta.encapsulation === ViewEncapsulation.Emulated) {
  16513. // If there is no style, don't generate css selectors on elements
  16514. meta.encapsulation = ViewEncapsulation.None;
  16515. }
  16516. // Only set view encapsulation if it's not the default value
  16517. if (meta.encapsulation !== ViewEncapsulation.Emulated) {
  16518. definitionMap.set('encapsulation', literal(meta.encapsulation));
  16519. }
  16520. // e.g. `animation: [trigger('123', [])]`
  16521. if (meta.animations !== null) {
  16522. definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
  16523. }
  16524. // Only set the change detection flag if it's defined and it's not the default.
  16525. if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
  16526. definitionMap.set('changeDetection', literal(changeDetection));
  16527. }
  16528. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  16529. // string literal, which must be on one line.
  16530. const selectorForType = (meta.selector || '').replace(/\n/g, '');
  16531. const expression = importExpr(Identifiers$1.defineComponent).callFn([definitionMap.toLiteralMap()]);
  16532. const type = createTypeForDef(meta, Identifiers$1.ComponentDefWithMeta);
  16533. return { expression, type, statements };
  16534. }
  16535. /**
  16536. * A wrapper around `compileDirective` which depends on render2 global analysis data as its input
  16537. * instead of the `R3DirectiveMetadata`.
  16538. *
  16539. * `R3DirectiveMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
  16540. * information.
  16541. */
  16542. function compileDirectiveFromRender2(outputCtx, directive, reflector, bindingParser) {
  16543. const name = identifierName(directive.type);
  16544. name || error(`Cannot resolver the name of ${directive.type}`);
  16545. const definitionField = outputCtx.constantPool.propertyNameOf(1 /* Directive */);
  16546. const meta = directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector);
  16547. const res = compileDirectiveFromMetadata(meta, outputCtx.constantPool, bindingParser);
  16548. // Create the partial class to be merged with the actual class.
  16549. outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
  16550. }
  16551. /**
  16552. * A wrapper around `compileComponent` which depends on render2 global analysis data as its input
  16553. * instead of the `R3DirectiveMetadata`.
  16554. *
  16555. * `R3ComponentMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
  16556. * information.
  16557. */
  16558. function compileComponentFromRender2(outputCtx, component, render3Ast, reflector, bindingParser, directiveTypeBySel, pipeTypeByName) {
  16559. const name = identifierName(component.type);
  16560. name || error(`Cannot resolver the name of ${component.type}`);
  16561. const definitionField = outputCtx.constantPool.propertyNameOf(2 /* Component */);
  16562. const summary = component.toSummary();
  16563. // Compute the R3ComponentMetadata from the CompileDirectiveMetadata
  16564. const meta = Object.assign({}, directiveMetadataFromGlobalMetadata(component, outputCtx, reflector), { selector: component.selector, template: { nodes: render3Ast.nodes }, directives: [], pipes: typeMapToExpressionMap(pipeTypeByName, outputCtx), viewQueries: queriesFromGlobalMetadata(component.viewQueries, outputCtx), wrapDirectivesAndPipesInClosure: false, styles: (summary.template && summary.template.styles) || EMPTY_ARRAY, encapsulation: (summary.template && summary.template.encapsulation) || ViewEncapsulation.Emulated, interpolation: DEFAULT_INTERPOLATION_CONFIG, animations: null, viewProviders: component.viewProviders.length > 0 ? new WrappedNodeExpr(component.viewProviders) : null, relativeContextFilePath: '', i18nUseExternalIds: true });
  16565. const res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser);
  16566. // Create the partial class to be merged with the actual class.
  16567. outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
  16568. }
  16569. /**
  16570. * Compute `R3DirectiveMetadata` given `CompileDirectiveMetadata` and a `CompileReflector`.
  16571. */
  16572. function directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector) {
  16573. // The global-analysis based Ivy mode in ngc is no longer utilized/supported.
  16574. throw new Error('unsupported');
  16575. }
  16576. /**
  16577. * Convert `CompileQueryMetadata` into `R3QueryMetadata`.
  16578. */
  16579. function queriesFromGlobalMetadata(queries, outputCtx) {
  16580. return queries.map(query => {
  16581. let read = null;
  16582. if (query.read && query.read.identifier) {
  16583. read = outputCtx.importExpr(query.read.identifier.reference);
  16584. }
  16585. return {
  16586. propertyName: query.propertyName,
  16587. first: query.first,
  16588. predicate: selectorsFromGlobalMetadata(query.selectors, outputCtx),
  16589. descendants: query.descendants, read,
  16590. static: !!query.static
  16591. };
  16592. });
  16593. }
  16594. /**
  16595. * Convert `CompileTokenMetadata` for query selectors into either an expression for a predicate
  16596. * type, or a list of string predicates.
  16597. */
  16598. function selectorsFromGlobalMetadata(selectors, outputCtx) {
  16599. if (selectors.length > 1 || (selectors.length == 1 && selectors[0].value)) {
  16600. const selectorStrings = selectors.map(value => value.value);
  16601. selectorStrings.some(value => !value) &&
  16602. error('Found a type among the string selectors expected');
  16603. return outputCtx.constantPool.getConstLiteral(literalArr(selectorStrings.map(value => literal(value))));
  16604. }
  16605. if (selectors.length == 1) {
  16606. const first = selectors[0];
  16607. if (first.identifier) {
  16608. return outputCtx.importExpr(first.identifier.reference);
  16609. }
  16610. }
  16611. error('Unexpected query form');
  16612. return NULL_EXPR;
  16613. }
  16614. function prepareQueryParams(query, constantPool) {
  16615. const parameters = [
  16616. getQueryPredicate(query, constantPool),
  16617. literal(query.descendants),
  16618. query.read || literal(null),
  16619. ];
  16620. return parameters;
  16621. }
  16622. // Turn a directive selector into an R3-compatible selector for directive def
  16623. function createDirectiveSelector(selector) {
  16624. return asLiteral(parseSelectorToR3Selector(selector));
  16625. }
  16626. function convertAttributesToExpressions(attributes) {
  16627. const values = [];
  16628. for (let key of Object.getOwnPropertyNames(attributes)) {
  16629. const value = attributes[key];
  16630. values.push(literal(key), value);
  16631. }
  16632. return values;
  16633. }
  16634. // Define and update any content queries
  16635. function createContentQueriesFunction(queries, constantPool, name) {
  16636. const createStatements = [];
  16637. const updateStatements = [];
  16638. const tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  16639. for (const query of queries) {
  16640. // creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
  16641. const args = [variable('dirIndex'), ...prepareQueryParams(query, constantPool)];
  16642. const queryInstruction = query.static ? Identifiers$1.staticContentQuery : Identifiers$1.contentQuery;
  16643. createStatements.push(importExpr(queryInstruction).callFn(args).toStmt());
  16644. // update, e.g. (r3.queryRefresh(tmp = r3.loadContentQuery()) && (ctx.someDir = tmp));
  16645. const temporary = tempAllocator();
  16646. const getQueryList = importExpr(Identifiers$1.loadContentQuery).callFn([]);
  16647. const refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  16648. const updateDirective = variable(CONTEXT_NAME)
  16649. .prop(query.propertyName)
  16650. .set(query.first ? temporary.prop('first') : temporary);
  16651. updateStatements.push(refresh.and(updateDirective).toStmt());
  16652. }
  16653. const contentQueriesFnName = name ? `${name}_ContentQueries` : null;
  16654. return fn([
  16655. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  16656. new FnParam('dirIndex', null)
  16657. ], [
  16658. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  16659. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  16660. ], INFERRED_TYPE, null, contentQueriesFnName);
  16661. }
  16662. function stringAsType(str) {
  16663. return expressionType(literal(str));
  16664. }
  16665. function stringMapAsType(map) {
  16666. const mapValues = Object.keys(map).map(key => {
  16667. const value = Array.isArray(map[key]) ? map[key][0] : map[key];
  16668. return {
  16669. key,
  16670. value: literal(value),
  16671. quoted: true,
  16672. };
  16673. });
  16674. return expressionType(literalMap(mapValues));
  16675. }
  16676. function stringArrayAsType(arr) {
  16677. return arr.length > 0 ? expressionType(literalArr(arr.map(value => literal(value)))) :
  16678. NONE_TYPE;
  16679. }
  16680. function createTypeForDef(meta, typeBase) {
  16681. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  16682. // string literal, which must be on one line.
  16683. const selectorForType = (meta.selector || '').replace(/\n/g, '');
  16684. return expressionType(importExpr(typeBase, [
  16685. typeWithParameters(meta.type, meta.typeArgumentCount),
  16686. stringAsType(selectorForType),
  16687. meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
  16688. stringMapAsType(meta.inputs),
  16689. stringMapAsType(meta.outputs),
  16690. stringArrayAsType(meta.queries.map(q => q.propertyName)),
  16691. ]));
  16692. }
  16693. // Define and update any view queries
  16694. function createViewQueriesFunction(viewQueries, constantPool, name) {
  16695. const createStatements = [];
  16696. const updateStatements = [];
  16697. const tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  16698. viewQueries.forEach((query) => {
  16699. const queryInstruction = query.static ? Identifiers$1.staticViewQuery : Identifiers$1.viewQuery;
  16700. // creation, e.g. r3.viewQuery(somePredicate, true);
  16701. const queryDefinition = importExpr(queryInstruction).callFn(prepareQueryParams(query, constantPool));
  16702. createStatements.push(queryDefinition.toStmt());
  16703. // update, e.g. (r3.queryRefresh(tmp = r3.loadViewQuery()) && (ctx.someDir = tmp));
  16704. const temporary = tempAllocator();
  16705. const getQueryList = importExpr(Identifiers$1.loadViewQuery).callFn([]);
  16706. const refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  16707. const updateDirective = variable(CONTEXT_NAME)
  16708. .prop(query.propertyName)
  16709. .set(query.first ? temporary.prop('first') : temporary);
  16710. updateStatements.push(refresh.and(updateDirective).toStmt());
  16711. });
  16712. const viewQueryFnName = name ? `${name}_Query` : null;
  16713. return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
  16714. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  16715. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  16716. ], INFERRED_TYPE, null, viewQueryFnName);
  16717. }
  16718. // Return a host binding function or null if one is not necessary.
  16719. function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name) {
  16720. // Initialize hostVarsCount to number of bound host properties (interpolations illegal),
  16721. // except 'style' and 'class' properties, since they should *not* allocate host var slots
  16722. const hostVarsCount = Object.keys(hostBindingsMetadata.properties)
  16723. .filter(name => {
  16724. const prefix = getStylingPrefix(name);
  16725. return prefix !== 'style' && prefix !== 'class';
  16726. })
  16727. .length;
  16728. const elVarExp = variable('elIndex');
  16729. const bindingContext = variable(CONTEXT_NAME);
  16730. const styleBuilder = new StylingBuilder(elVarExp, bindingContext);
  16731. const { styleAttr, classAttr } = hostBindingsMetadata.specialAttributes;
  16732. if (styleAttr !== undefined) {
  16733. styleBuilder.registerStyleAttr(styleAttr);
  16734. }
  16735. if (classAttr !== undefined) {
  16736. styleBuilder.registerClassAttr(classAttr);
  16737. }
  16738. const createStatements = [];
  16739. const updateStatements = [];
  16740. let totalHostVarsCount = hostVarsCount;
  16741. const hostBindingSourceSpan = typeSourceSpan;
  16742. const directiveSummary = metadataAsSummary(hostBindingsMetadata);
  16743. let valueConverter;
  16744. const getValueConverter = () => {
  16745. if (!valueConverter) {
  16746. const hostVarsCountFn = (numSlots) => {
  16747. const originalVarsCount = totalHostVarsCount;
  16748. totalHostVarsCount += numSlots;
  16749. return originalVarsCount;
  16750. };
  16751. valueConverter = new ValueConverter(constantPool, () => error('Unexpected node'), // new nodes are illegal here
  16752. hostVarsCountFn, () => error('Unexpected pipe')); // pipes are illegal here
  16753. }
  16754. return valueConverter;
  16755. };
  16756. // Calculate host event bindings
  16757. const eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
  16758. if (eventBindings && eventBindings.length) {
  16759. const listeners = createHostListeners(eventBindings, name);
  16760. createStatements.push(...listeners);
  16761. }
  16762. // Calculate the host property bindings
  16763. const bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
  16764. (bindings || []).forEach((binding) => {
  16765. const name = binding.name;
  16766. const stylingInputWasSet = styleBuilder.registerInputBasedOnName(name, binding.expression, binding.sourceSpan);
  16767. if (!stylingInputWasSet) {
  16768. // resolve literal arrays and literal objects
  16769. const value = binding.expression.visit(getValueConverter());
  16770. const bindingExpr = bindingFn(bindingContext, value);
  16771. const { bindingName, instruction, isAttribute } = getBindingNameAndInstruction(binding);
  16772. const securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
  16773. .filter(context => context !== SecurityContext.NONE);
  16774. let sanitizerFn = null;
  16775. if (securityContexts.length) {
  16776. if (securityContexts.length === 2 &&
  16777. securityContexts.indexOf(SecurityContext.URL) > -1 &&
  16778. securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
  16779. // Special case for some URL attributes (such as "src" and "href") that may be a part
  16780. // of different security contexts. In this case we use special santitization function and
  16781. // select the actual sanitizer at runtime based on a tag name that is provided while
  16782. // invoking sanitization function.
  16783. sanitizerFn = importExpr(Identifiers$1.sanitizeUrlOrResourceUrl);
  16784. }
  16785. else {
  16786. sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
  16787. }
  16788. }
  16789. const instructionParams = [literal(bindingName), bindingExpr.currValExpr];
  16790. if (sanitizerFn) {
  16791. instructionParams.push(sanitizerFn);
  16792. }
  16793. if (!isAttribute) {
  16794. if (!sanitizerFn) {
  16795. // append `null` in front of `nativeOnly` flag if no sanitizer fn defined
  16796. instructionParams.push(literal(null));
  16797. }
  16798. // host bindings must have nativeOnly prop set to true
  16799. instructionParams.push(literal(true));
  16800. }
  16801. updateStatements.push(...bindingExpr.stmts);
  16802. updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
  16803. }
  16804. });
  16805. // since we're dealing with directives/components and both have hostBinding
  16806. // functions, we need to generate a special hostAttrs instruction that deals
  16807. // with both the assignment of styling as well as static attributes to the host
  16808. // element. The instruction below will instruct all initial styling (styling
  16809. // that is inside of a host binding within a directive/component) to be attached
  16810. // to the host element alongside any of the provided host attributes that were
  16811. // collected earlier.
  16812. const hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
  16813. const hostInstruction = styleBuilder.buildHostAttrsInstruction(null, hostAttrs, constantPool);
  16814. if (hostInstruction) {
  16815. createStatements.push(createStylingStmt(hostInstruction, bindingContext, bindingFn));
  16816. }
  16817. if (styleBuilder.hasBindings) {
  16818. // singular style/class bindings (things like `[style.prop]` and `[class.name]`)
  16819. // MUST be registered on a given element within the component/directive
  16820. // templateFn/hostBindingsFn functions. The instruction below will figure out
  16821. // what all the bindings are and then generate the statements required to register
  16822. // those bindings to the element via `styling`.
  16823. const stylingInstruction = styleBuilder.buildStylingInstruction(null, constantPool);
  16824. if (stylingInstruction) {
  16825. createStatements.push(createStylingStmt(stylingInstruction, bindingContext, bindingFn));
  16826. }
  16827. // finally each binding that was registered in the statement above will need to be added to
  16828. // the update block of a component/directive templateFn/hostBindingsFn so that the bindings
  16829. // are evaluated and updated for the element.
  16830. styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(instruction => {
  16831. totalHostVarsCount += instruction.allocateBindingSlots;
  16832. updateStatements.push(createStylingStmt(instruction, bindingContext, bindingFn));
  16833. });
  16834. }
  16835. if (totalHostVarsCount) {
  16836. createStatements.unshift(importExpr(Identifiers$1.allocHostVars).callFn([literal(totalHostVarsCount)]).toStmt());
  16837. }
  16838. if (createStatements.length > 0 || updateStatements.length > 0) {
  16839. const hostBindingsFnName = name ? `${name}_HostBindings` : null;
  16840. const statements = [];
  16841. if (createStatements.length > 0) {
  16842. statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
  16843. }
  16844. if (updateStatements.length > 0) {
  16845. statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
  16846. }
  16847. return fn([
  16848. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  16849. new FnParam(elVarExp.name, NUMBER_TYPE)
  16850. ], statements, INFERRED_TYPE, null, hostBindingsFnName);
  16851. }
  16852. return null;
  16853. }
  16854. function bindingFn(implicit, value) {
  16855. return convertPropertyBinding(null, implicit, value, 'b', BindingForm.TrySimple, () => error('Unexpected interpolation'));
  16856. }
  16857. function createStylingStmt(instruction, bindingContext, bindingFn) {
  16858. const params = instruction.buildParams(value => bindingFn(bindingContext, value).currValExpr);
  16859. return importExpr(instruction.reference, null, instruction.sourceSpan)
  16860. .callFn(params, instruction.sourceSpan)
  16861. .toStmt();
  16862. }
  16863. function getBindingNameAndInstruction(binding) {
  16864. let bindingName = binding.name;
  16865. let instruction;
  16866. // Check to see if this is an attr binding or a property binding
  16867. const attrMatches = bindingName.match(ATTR_REGEX);
  16868. if (attrMatches) {
  16869. bindingName = attrMatches[1];
  16870. instruction = Identifiers$1.attribute;
  16871. }
  16872. else {
  16873. if (binding.isAnimation) {
  16874. bindingName = prepareSyntheticPropertyName(bindingName);
  16875. // host bindings that have a synthetic property (e.g. @foo) should always be rendered
  16876. // in the context of the component and not the parent. Therefore there is a special
  16877. // compatibility instruction available for this purpose.
  16878. instruction = Identifiers$1.updateSyntheticHostBinding;
  16879. }
  16880. else {
  16881. instruction = Identifiers$1.property;
  16882. }
  16883. }
  16884. return { bindingName, instruction, isAttribute: !!attrMatches };
  16885. }
  16886. function createHostListeners(eventBindings, name) {
  16887. return eventBindings.map(binding => {
  16888. let bindingName = binding.name && sanitizeIdentifier(binding.name);
  16889. const bindingFnName = binding.type === 1 /* Animation */ ?
  16890. prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
  16891. bindingName;
  16892. const handlerName = name && bindingName ? `${name}_${bindingFnName}_HostBindingHandler` : null;
  16893. const params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
  16894. const instruction = binding.type == 1 /* Animation */ ? Identifiers$1.componentHostSyntheticListener : Identifiers$1.listener;
  16895. return importExpr(instruction).callFn(params).toStmt();
  16896. });
  16897. }
  16898. function metadataAsSummary(meta) {
  16899. // clang-format off
  16900. return {
  16901. // This is used by the BindingParser, which only deals with listeners and properties. There's no
  16902. // need to pass attributes to it.
  16903. hostAttributes: {},
  16904. hostListeners: meta.listeners,
  16905. hostProperties: meta.properties,
  16906. };
  16907. // clang-format on
  16908. }
  16909. function typeMapToExpressionMap(map, outputCtx) {
  16910. // Convert each map entry into another entry where the value is an expression importing the type.
  16911. const entries = Array.from(map).map(([key, type]) => [key, outputCtx.importExpr(type)]);
  16912. return new Map(entries);
  16913. }
  16914. const HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
  16915. function parseHostBindings(host) {
  16916. const attributes = {};
  16917. const listeners = {};
  16918. const properties = {};
  16919. const specialAttributes = {};
  16920. for (const key of Object.keys(host)) {
  16921. const value = host[key];
  16922. const matches = key.match(HOST_REG_EXP$1);
  16923. if (matches === null) {
  16924. switch (key) {
  16925. case 'class':
  16926. if (typeof value !== 'string') {
  16927. // TODO(alxhub): make this a diagnostic.
  16928. throw new Error(`Class binding must be string`);
  16929. }
  16930. specialAttributes.classAttr = value;
  16931. break;
  16932. case 'style':
  16933. if (typeof value !== 'string') {
  16934. // TODO(alxhub): make this a diagnostic.
  16935. throw new Error(`Style binding must be string`);
  16936. }
  16937. specialAttributes.styleAttr = value;
  16938. break;
  16939. default:
  16940. if (typeof value === 'string') {
  16941. attributes[key] = literal(value);
  16942. }
  16943. else {
  16944. attributes[key] = value;
  16945. }
  16946. }
  16947. }
  16948. else if (matches[1 /* Binding */] != null) {
  16949. if (typeof value !== 'string') {
  16950. // TODO(alxhub): make this a diagnostic.
  16951. throw new Error(`Property binding must be string`);
  16952. }
  16953. // synthetic properties (the ones that have a `@` as a prefix)
  16954. // are still treated the same as regular properties. Therefore
  16955. // there is no point in storing them in a separate map.
  16956. properties[matches[1 /* Binding */]] = value;
  16957. }
  16958. else if (matches[2 /* Event */] != null) {
  16959. if (typeof value !== 'string') {
  16960. // TODO(alxhub): make this a diagnostic.
  16961. throw new Error(`Event binding must be string`);
  16962. }
  16963. listeners[matches[2 /* Event */]] = value;
  16964. }
  16965. }
  16966. return { attributes, listeners, properties, specialAttributes };
  16967. }
  16968. /**
  16969. * Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
  16970. * given set of host bindings has no errors.
  16971. *
  16972. * @param bindings set of host bindings to verify.
  16973. * @param sourceSpan source span where host bindings were defined.
  16974. * @returns array of errors associated with a given set of host bindings.
  16975. */
  16976. function verifyHostBindings(bindings, sourceSpan) {
  16977. const summary = metadataAsSummary(bindings);
  16978. // TODO: abstract out host bindings verification logic and use it instead of
  16979. // creating events and properties ASTs to detect errors (FW-996)
  16980. const bindingParser = makeBindingParser();
  16981. bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
  16982. bindingParser.createBoundHostProperties(summary, sourceSpan);
  16983. return bindingParser.errors;
  16984. }
  16985. function compileStyles(styles, selector, hostSelector) {
  16986. const shadowCss = new ShadowCss();
  16987. return styles.map(style => { return shadowCss.shimCssText(style, selector, hostSelector); });
  16988. }
  16989. /**
  16990. * @license
  16991. * Copyright Google Inc. All Rights Reserved.
  16992. *
  16993. * Use of this source code is governed by an MIT-style license that can be
  16994. * found in the LICENSE file at https://angular.io/license
  16995. */
  16996. /**
  16997. * An interface for retrieving documents by URL that the compiler uses
  16998. * to load templates.
  16999. */
  17000. class ResourceLoader {
  17001. get(url) { return ''; }
  17002. }
  17003. /**
  17004. * @license
  17005. * Copyright Google Inc. All Rights Reserved.
  17006. *
  17007. * Use of this source code is governed by an MIT-style license that can be
  17008. * found in the LICENSE file at https://angular.io/license
  17009. */
  17010. class CompilerFacadeImpl {
  17011. constructor(jitEvaluator = new JitEvaluator()) {
  17012. this.jitEvaluator = jitEvaluator;
  17013. this.R3ResolvedDependencyType = R3ResolvedDependencyType;
  17014. this.ResourceLoader = ResourceLoader;
  17015. this.elementSchemaRegistry = new DomElementSchemaRegistry();
  17016. }
  17017. compilePipe(angularCoreEnv, sourceMapUrl, facade) {
  17018. const res = compilePipeFromMetadata({
  17019. name: facade.name,
  17020. type: new WrappedNodeExpr(facade.type),
  17021. typeArgumentCount: facade.typeArgumentCount,
  17022. deps: convertR3DependencyMetadataArray(facade.deps),
  17023. pipeName: facade.pipeName,
  17024. pure: facade.pure,
  17025. });
  17026. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  17027. }
  17028. compileInjectable(angularCoreEnv, sourceMapUrl, facade) {
  17029. const { expression, statements } = compileInjectable({
  17030. name: facade.name,
  17031. type: new WrappedNodeExpr(facade.type),
  17032. typeArgumentCount: facade.typeArgumentCount,
  17033. providedIn: computeProvidedIn(facade.providedIn),
  17034. useClass: wrapExpression(facade, USE_CLASS),
  17035. useFactory: wrapExpression(facade, USE_FACTORY),
  17036. useValue: wrapExpression(facade, USE_VALUE),
  17037. useExisting: wrapExpression(facade, USE_EXISTING),
  17038. ctorDeps: convertR3DependencyMetadataArray(facade.ctorDeps),
  17039. userDeps: convertR3DependencyMetadataArray(facade.userDeps) || undefined,
  17040. });
  17041. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
  17042. }
  17043. compileInjector(angularCoreEnv, sourceMapUrl, facade) {
  17044. const meta = {
  17045. name: facade.name,
  17046. type: new WrappedNodeExpr(facade.type),
  17047. deps: convertR3DependencyMetadataArray(facade.deps),
  17048. providers: new WrappedNodeExpr(facade.providers),
  17049. imports: facade.imports.map(i => new WrappedNodeExpr(i)),
  17050. };
  17051. const res = compileInjector(meta);
  17052. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  17053. }
  17054. compileNgModule(angularCoreEnv, sourceMapUrl, facade) {
  17055. const meta = {
  17056. type: new WrappedNodeExpr(facade.type),
  17057. bootstrap: facade.bootstrap.map(wrapReference),
  17058. declarations: facade.declarations.map(wrapReference),
  17059. imports: facade.imports.map(wrapReference),
  17060. exports: facade.exports.map(wrapReference),
  17061. emitInline: true,
  17062. containsForwardDecls: false,
  17063. schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
  17064. id: facade.id ? new WrappedNodeExpr(facade.id) : null,
  17065. };
  17066. const res = compileNgModule(meta);
  17067. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  17068. }
  17069. compileDirective(angularCoreEnv, sourceMapUrl, facade) {
  17070. const constantPool = new ConstantPool();
  17071. const bindingParser = makeBindingParser();
  17072. const meta = convertDirectiveFacadeToMetadata(facade);
  17073. const res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
  17074. const preStatements = [...constantPool.statements, ...res.statements];
  17075. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, preStatements);
  17076. }
  17077. compileComponent(angularCoreEnv, sourceMapUrl, facade) {
  17078. // The ConstantPool is a requirement of the JIT'er.
  17079. const constantPool = new ConstantPool();
  17080. const interpolationConfig = facade.interpolation ?
  17081. InterpolationConfig.fromArray(facade.interpolation) :
  17082. DEFAULT_INTERPOLATION_CONFIG;
  17083. // Parse the template and check for errors.
  17084. const template = parseTemplate(facade.template, sourceMapUrl, { preserveWhitespaces: facade.preserveWhitespaces, interpolationConfig });
  17085. if (template.errors !== undefined) {
  17086. const errors = template.errors.map(err => err.toString()).join(', ');
  17087. throw new Error(`Errors during JIT compilation of template for ${facade.name}: ${errors}`);
  17088. }
  17089. // Compile the component metadata, including template, into an expression.
  17090. // TODO(alxhub): implement inputs, outputs, queries, etc.
  17091. const res = compileComponentFromMetadata(Object.assign({}, facade, convertDirectiveFacadeToMetadata(facade), { selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(), 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) :
  17092. null, relativeContextFilePath: '', i18nUseExternalIds: true }), constantPool, makeBindingParser(interpolationConfig));
  17093. const preStatements = [...constantPool.statements, ...res.statements];
  17094. return this.jitExpression(res.expression, angularCoreEnv, `ng:///${facade.name}.js`, preStatements);
  17095. }
  17096. compileBase(angularCoreEnv, sourceMapUrl, facade) {
  17097. const constantPool = new ConstantPool();
  17098. const typeSourceSpan = this.createParseSourceSpan('Base', facade.name, `ng:///${facade.name}.js`);
  17099. const meta = Object.assign({}, facade, { typeSourceSpan, viewQueries: facade.viewQueries ? facade.viewQueries.map(convertToR3QueryMetadata) :
  17100. facade.viewQueries, queries: facade.queries ? facade.queries.map(convertToR3QueryMetadata) : facade.queries, host: extractHostBindings(facade.propMetadata, typeSourceSpan) });
  17101. const res = compileBaseDefFromMetadata(meta, constantPool, makeBindingParser());
  17102. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
  17103. }
  17104. createParseSourceSpan(kind, typeName, sourceUrl) {
  17105. return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
  17106. }
  17107. /**
  17108. * JIT compiles an expression and returns the result of executing that expression.
  17109. *
  17110. * @param def the definition which will be compiled and executed to get the value to patch
  17111. * @param context an object map of @angular/core symbol names to symbols which will be available
  17112. * in the context of the compiled expression
  17113. * @param sourceUrl a URL to use for the source map of the compiled expression
  17114. * @param preStatements a collection of statements that should be evaluated before the expression.
  17115. */
  17116. jitExpression(def, context, sourceUrl, preStatements) {
  17117. // The ConstantPool may contain Statements which declare variables used in the final expression.
  17118. // Therefore, its statements need to precede the actual JIT operation. The final statement is a
  17119. // declaration of $def which is set to the expression being compiled.
  17120. const statements = [
  17121. ...preStatements,
  17122. new DeclareVarStmt('$def', def, undefined, [StmtModifier.Exported]),
  17123. ];
  17124. const res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
  17125. return res['$def'];
  17126. }
  17127. }
  17128. const USE_CLASS = Object.keys({ useClass: null })[0];
  17129. const USE_FACTORY = Object.keys({ useFactory: null })[0];
  17130. const USE_VALUE = Object.keys({ useValue: null })[0];
  17131. const USE_EXISTING = Object.keys({ useExisting: null })[0];
  17132. const wrapReference = function (value) {
  17133. const wrapped = new WrappedNodeExpr(value);
  17134. return { value: wrapped, type: wrapped };
  17135. };
  17136. function convertToR3QueryMetadata(facade) {
  17137. return Object.assign({}, facade, { predicate: Array.isArray(facade.predicate) ? facade.predicate :
  17138. new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static });
  17139. }
  17140. function convertDirectiveFacadeToMetadata(facade) {
  17141. const inputsFromMetadata = parseInputOutputs(facade.inputs || []);
  17142. const outputsFromMetadata = parseInputOutputs(facade.outputs || []);
  17143. const propMetadata = facade.propMetadata;
  17144. const inputsFromType = {};
  17145. const outputsFromType = {};
  17146. for (const field in propMetadata) {
  17147. if (propMetadata.hasOwnProperty(field)) {
  17148. propMetadata[field].forEach(ann => {
  17149. if (isInput(ann)) {
  17150. inputsFromType[field] =
  17151. ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
  17152. }
  17153. else if (isOutput(ann)) {
  17154. outputsFromType[field] = ann.bindingPropertyName || field;
  17155. }
  17156. });
  17157. }
  17158. }
  17159. return Object.assign({}, facade, { typeSourceSpan: facade.typeSourceSpan, type: new WrappedNodeExpr(facade.type), deps: convertR3DependencyMetadataArray(facade.deps), host: extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host), inputs: Object.assign({}, inputsFromMetadata, inputsFromType), outputs: Object.assign({}, outputsFromMetadata, outputsFromType), queries: facade.queries.map(convertToR3QueryMetadata), providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null, viewQueries: facade.viewQueries.map(convertToR3QueryMetadata) });
  17160. }
  17161. function wrapExpression(obj, property) {
  17162. if (obj.hasOwnProperty(property)) {
  17163. return new WrappedNodeExpr(obj[property]);
  17164. }
  17165. else {
  17166. return undefined;
  17167. }
  17168. }
  17169. function computeProvidedIn(providedIn) {
  17170. if (providedIn == null || typeof providedIn === 'string') {
  17171. return new LiteralExpr(providedIn);
  17172. }
  17173. else {
  17174. return new WrappedNodeExpr(providedIn);
  17175. }
  17176. }
  17177. function convertR3DependencyMetadata(facade) {
  17178. let tokenExpr;
  17179. if (facade.token === null) {
  17180. tokenExpr = new LiteralExpr(null);
  17181. }
  17182. else if (facade.resolved === R3ResolvedDependencyType.Attribute) {
  17183. tokenExpr = new LiteralExpr(facade.token);
  17184. }
  17185. else {
  17186. tokenExpr = new WrappedNodeExpr(facade.token);
  17187. }
  17188. return {
  17189. token: tokenExpr,
  17190. resolved: facade.resolved,
  17191. host: facade.host,
  17192. optional: facade.optional,
  17193. self: facade.self,
  17194. skipSelf: facade.skipSelf
  17195. };
  17196. }
  17197. function convertR3DependencyMetadataArray(facades) {
  17198. return facades == null ? null : facades.map(convertR3DependencyMetadata);
  17199. }
  17200. function extractHostBindings(propMetadata, sourceSpan, host) {
  17201. // First parse the declarations from the metadata.
  17202. const bindings = parseHostBindings(host || {});
  17203. // After that check host bindings for errors
  17204. const errors = verifyHostBindings(bindings, sourceSpan);
  17205. if (errors.length) {
  17206. throw new Error(errors.map((error) => error.msg).join('\n'));
  17207. }
  17208. // Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
  17209. for (const field in propMetadata) {
  17210. if (propMetadata.hasOwnProperty(field)) {
  17211. propMetadata[field].forEach(ann => {
  17212. if (isHostBinding(ann)) {
  17213. bindings.properties[ann.hostPropertyName || field] = field;
  17214. }
  17215. else if (isHostListener(ann)) {
  17216. bindings.listeners[ann.eventName || field] = `${field}(${(ann.args || []).join(',')})`;
  17217. }
  17218. });
  17219. }
  17220. }
  17221. return bindings;
  17222. }
  17223. function isHostBinding(value) {
  17224. return value.ngMetadataName === 'HostBinding';
  17225. }
  17226. function isHostListener(value) {
  17227. return value.ngMetadataName === 'HostListener';
  17228. }
  17229. function isInput(value) {
  17230. return value.ngMetadataName === 'Input';
  17231. }
  17232. function isOutput(value) {
  17233. return value.ngMetadataName === 'Output';
  17234. }
  17235. function parseInputOutputs(values) {
  17236. return values.reduce((map, value) => {
  17237. const [field, property] = value.split(',').map(piece => piece.trim());
  17238. map[field] = property || field;
  17239. return map;
  17240. }, {});
  17241. }
  17242. function publishFacade(global) {
  17243. const ng = global.ng || (global.ng = {});
  17244. ng.ɵcompilerFacade = new CompilerFacadeImpl();
  17245. }
  17246. /**
  17247. * @license
  17248. * Copyright Google Inc. All Rights Reserved.
  17249. *
  17250. * Use of this source code is governed by an MIT-style license that can be
  17251. * found in the LICENSE file at https://angular.io/license
  17252. */
  17253. const VERSION$1 = new Version('8.1.0');
  17254. /**
  17255. * @license
  17256. * Copyright Google Inc. All Rights Reserved.
  17257. *
  17258. * Use of this source code is governed by an MIT-style license that can be
  17259. * found in the LICENSE file at https://angular.io/license
  17260. */
  17261. class CompilerConfig {
  17262. constructor({ defaultEncapsulation = ViewEncapsulation.Emulated, useJit = true, jitDevMode = false, missingTranslation = null, preserveWhitespaces, strictInjectionParameters } = {}) {
  17263. this.defaultEncapsulation = defaultEncapsulation;
  17264. this.useJit = !!useJit;
  17265. this.jitDevMode = !!jitDevMode;
  17266. this.missingTranslation = missingTranslation;
  17267. this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
  17268. this.strictInjectionParameters = strictInjectionParameters === true;
  17269. }
  17270. }
  17271. function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting = false) {
  17272. return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
  17273. }
  17274. /**
  17275. * @license
  17276. * Copyright Google Inc. All Rights Reserved.
  17277. *
  17278. * Use of this source code is governed by an MIT-style license that can be
  17279. * found in the LICENSE file at https://angular.io/license
  17280. */
  17281. class DirectiveNormalizer {
  17282. constructor(_resourceLoader, _urlResolver, _htmlParser, _config) {
  17283. this._resourceLoader = _resourceLoader;
  17284. this._urlResolver = _urlResolver;
  17285. this._htmlParser = _htmlParser;
  17286. this._config = _config;
  17287. this._resourceLoaderCache = new Map();
  17288. }
  17289. clearCache() { this._resourceLoaderCache.clear(); }
  17290. clearCacheFor(normalizedDirective) {
  17291. if (!normalizedDirective.isComponent) {
  17292. return;
  17293. }
  17294. const template = normalizedDirective.template;
  17295. this._resourceLoaderCache.delete(template.templateUrl);
  17296. template.externalStylesheets.forEach((stylesheet) => { this._resourceLoaderCache.delete(stylesheet.moduleUrl); });
  17297. }
  17298. _fetch(url) {
  17299. let result = this._resourceLoaderCache.get(url);
  17300. if (!result) {
  17301. result = this._resourceLoader.get(url);
  17302. this._resourceLoaderCache.set(url, result);
  17303. }
  17304. return result;
  17305. }
  17306. normalizeTemplate(prenormData) {
  17307. if (isDefined(prenormData.template)) {
  17308. if (isDefined(prenormData.templateUrl)) {
  17309. throw syntaxError(`'${stringify(prenormData.componentType)}' component cannot define both template and templateUrl`);
  17310. }
  17311. if (typeof prenormData.template !== 'string') {
  17312. throw syntaxError(`The template specified for component ${stringify(prenormData.componentType)} is not a string`);
  17313. }
  17314. }
  17315. else if (isDefined(prenormData.templateUrl)) {
  17316. if (typeof prenormData.templateUrl !== 'string') {
  17317. throw syntaxError(`The templateUrl specified for component ${stringify(prenormData.componentType)} is not a string`);
  17318. }
  17319. }
  17320. else {
  17321. throw syntaxError(`No template specified for component ${stringify(prenormData.componentType)}`);
  17322. }
  17323. if (isDefined(prenormData.preserveWhitespaces) &&
  17324. typeof prenormData.preserveWhitespaces !== 'boolean') {
  17325. throw syntaxError(`The preserveWhitespaces option for component ${stringify(prenormData.componentType)} must be a boolean`);
  17326. }
  17327. return SyncAsync.then(this._preParseTemplate(prenormData), (preparsedTemplate) => this._normalizeTemplateMetadata(prenormData, preparsedTemplate));
  17328. }
  17329. _preParseTemplate(prenomData) {
  17330. let template;
  17331. let templateUrl;
  17332. if (prenomData.template != null) {
  17333. template = prenomData.template;
  17334. templateUrl = prenomData.moduleUrl;
  17335. }
  17336. else {
  17337. templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
  17338. template = this._fetch(templateUrl);
  17339. }
  17340. return SyncAsync.then(template, (template) => this._preparseLoadedTemplate(prenomData, template, templateUrl));
  17341. }
  17342. _preparseLoadedTemplate(prenormData, template, templateAbsUrl) {
  17343. const isInline = !!prenormData.template;
  17344. const interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
  17345. const templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline, templateUrl: templateAbsUrl });
  17346. const rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig });
  17347. if (rootNodesAndErrors.errors.length > 0) {
  17348. const errorString = rootNodesAndErrors.errors.join('\n');
  17349. throw syntaxError(`Template parse errors:\n${errorString}`);
  17350. }
  17351. const templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
  17352. const visitor = new TemplatePreparseVisitor();
  17353. visitAll$1(visitor, rootNodesAndErrors.rootNodes);
  17354. const templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
  17355. const styles = templateMetadataStyles.styles.concat(templateStyles.styles);
  17356. const inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
  17357. const styleUrls = this
  17358. ._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
  17359. .styleUrls;
  17360. return {
  17361. template,
  17362. templateUrl: templateAbsUrl, isInline,
  17363. htmlAst: rootNodesAndErrors, styles, inlineStyleUrls, styleUrls,
  17364. ngContentSelectors: visitor.ngContentSelectors,
  17365. };
  17366. }
  17367. _normalizeTemplateMetadata(prenormData, preparsedTemplate) {
  17368. return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), (externalStylesheets) => this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets));
  17369. }
  17370. _normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, stylesheets) {
  17371. // Algorithm:
  17372. // - produce exactly 1 entry per original styleUrl in
  17373. // CompileTemplateMetadata.externalStylesheets with all styles inlined
  17374. // - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
  17375. // Reason: be able to determine how many stylesheets there are even without loading
  17376. // the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
  17377. // (as resource loading may be async)
  17378. const styles = [...preparsedTemplate.styles];
  17379. this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
  17380. const styleUrls = preparsedTemplate.styleUrls;
  17381. const externalStylesheets = styleUrls.map(styleUrl => {
  17382. const stylesheet = stylesheets.get(styleUrl);
  17383. const styles = [...stylesheet.styles];
  17384. this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
  17385. return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
  17386. });
  17387. let encapsulation = prenormData.encapsulation;
  17388. if (encapsulation == null) {
  17389. encapsulation = this._config.defaultEncapsulation;
  17390. }
  17391. if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
  17392. styleUrls.length === 0) {
  17393. encapsulation = ViewEncapsulation.None;
  17394. }
  17395. return new CompileTemplateMetadata({
  17396. encapsulation,
  17397. template: preparsedTemplate.template,
  17398. templateUrl: preparsedTemplate.templateUrl,
  17399. htmlAst: preparsedTemplate.htmlAst, styles, styleUrls,
  17400. ngContentSelectors: preparsedTemplate.ngContentSelectors,
  17401. animations: prenormData.animations,
  17402. interpolation: prenormData.interpolation,
  17403. isInline: preparsedTemplate.isInline, externalStylesheets,
  17404. preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
  17405. });
  17406. }
  17407. _inlineStyles(styleUrls, stylesheets, targetStyles) {
  17408. styleUrls.forEach(styleUrl => {
  17409. const stylesheet = stylesheets.get(styleUrl);
  17410. stylesheet.styles.forEach(style => targetStyles.push(style));
  17411. this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
  17412. });
  17413. }
  17414. _loadMissingExternalStylesheets(styleUrls, loadedStylesheets = new Map()) {
  17415. return SyncAsync.then(SyncAsync.all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl))
  17416. .map(styleUrl => SyncAsync.then(this._fetch(styleUrl), (loadedStyle) => {
  17417. const stylesheet = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
  17418. loadedStylesheets.set(styleUrl, stylesheet);
  17419. return this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
  17420. }))), (_) => loadedStylesheets);
  17421. }
  17422. _normalizeStylesheet(stylesheet) {
  17423. const moduleUrl = stylesheet.moduleUrl;
  17424. const allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
  17425. .map(url => this._urlResolver.resolve(moduleUrl, url));
  17426. const allStyles = stylesheet.styles.map(style => {
  17427. const styleWithImports = extractStyleUrls(this._urlResolver, moduleUrl, style);
  17428. allStyleUrls.push(...styleWithImports.styleUrls);
  17429. return styleWithImports.style;
  17430. });
  17431. return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
  17432. }
  17433. }
  17434. class TemplatePreparseVisitor {
  17435. constructor() {
  17436. this.ngContentSelectors = [];
  17437. this.styles = [];
  17438. this.styleUrls = [];
  17439. this.ngNonBindableStackCount = 0;
  17440. }
  17441. visitElement(ast, context) {
  17442. const preparsedElement = preparseElement(ast);
  17443. switch (preparsedElement.type) {
  17444. case PreparsedElementType.NG_CONTENT:
  17445. if (this.ngNonBindableStackCount === 0) {
  17446. this.ngContentSelectors.push(preparsedElement.selectAttr);
  17447. }
  17448. break;
  17449. case PreparsedElementType.STYLE:
  17450. let textContent = '';
  17451. ast.children.forEach(child => {
  17452. if (child instanceof Text$3) {
  17453. textContent += child.value;
  17454. }
  17455. });
  17456. this.styles.push(textContent);
  17457. break;
  17458. case PreparsedElementType.STYLESHEET:
  17459. this.styleUrls.push(preparsedElement.hrefAttr);
  17460. break;
  17461. default:
  17462. break;
  17463. }
  17464. if (preparsedElement.nonBindable) {
  17465. this.ngNonBindableStackCount++;
  17466. }
  17467. visitAll$1(this, ast.children);
  17468. if (preparsedElement.nonBindable) {
  17469. this.ngNonBindableStackCount--;
  17470. }
  17471. return null;
  17472. }
  17473. visitExpansion(ast, context) { visitAll$1(this, ast.cases); }
  17474. visitExpansionCase(ast, context) {
  17475. visitAll$1(this, ast.expression);
  17476. }
  17477. visitComment(ast, context) { return null; }
  17478. visitAttribute(ast, context) { return null; }
  17479. visitText(ast, context) { return null; }
  17480. }
  17481. /**
  17482. * @license
  17483. * Copyright Google Inc. All Rights Reserved.
  17484. *
  17485. * Use of this source code is governed by an MIT-style license that can be
  17486. * found in the LICENSE file at https://angular.io/license
  17487. */
  17488. const QUERY_METADATA_IDENTIFIERS = [
  17489. createViewChild,
  17490. createViewChildren,
  17491. createContentChild,
  17492. createContentChildren,
  17493. ];
  17494. /*
  17495. * Resolve a `Type` for {@link Directive}.
  17496. *
  17497. * This interface can be overridden by the application developer to create custom behavior.
  17498. *
  17499. * See {@link Compiler}
  17500. */
  17501. class DirectiveResolver {
  17502. constructor(_reflector) {
  17503. this._reflector = _reflector;
  17504. }
  17505. isDirective(type) {
  17506. const typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  17507. return typeMetadata && typeMetadata.some(isDirectiveMetadata);
  17508. }
  17509. resolve(type, throwIfNotFound = true) {
  17510. const typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  17511. if (typeMetadata) {
  17512. const metadata = findLast(typeMetadata, isDirectiveMetadata);
  17513. if (metadata) {
  17514. const propertyMetadata = this._reflector.propMetadata(type);
  17515. const guards = this._reflector.guards(type);
  17516. return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
  17517. }
  17518. }
  17519. if (throwIfNotFound) {
  17520. throw new Error(`No Directive annotation found on ${stringify(type)}`);
  17521. }
  17522. return null;
  17523. }
  17524. _mergeWithPropertyMetadata(dm, propertyMetadata, guards, directiveType) {
  17525. const inputs = [];
  17526. const outputs = [];
  17527. const host = {};
  17528. const queries = {};
  17529. Object.keys(propertyMetadata).forEach((propName) => {
  17530. const input = findLast(propertyMetadata[propName], (a) => createInput.isTypeOf(a));
  17531. if (input) {
  17532. if (input.bindingPropertyName) {
  17533. inputs.push(`${propName}: ${input.bindingPropertyName}`);
  17534. }
  17535. else {
  17536. inputs.push(propName);
  17537. }
  17538. }
  17539. const output = findLast(propertyMetadata[propName], (a) => createOutput.isTypeOf(a));
  17540. if (output) {
  17541. if (output.bindingPropertyName) {
  17542. outputs.push(`${propName}: ${output.bindingPropertyName}`);
  17543. }
  17544. else {
  17545. outputs.push(propName);
  17546. }
  17547. }
  17548. const hostBindings = propertyMetadata[propName].filter(a => createHostBinding.isTypeOf(a));
  17549. hostBindings.forEach(hostBinding => {
  17550. if (hostBinding.hostPropertyName) {
  17551. const startWith = hostBinding.hostPropertyName[0];
  17552. if (startWith === '(') {
  17553. throw new Error(`@HostBinding can not bind to events. Use @HostListener instead.`);
  17554. }
  17555. else if (startWith === '[') {
  17556. throw new Error(`@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.`);
  17557. }
  17558. host[`[${hostBinding.hostPropertyName}]`] = propName;
  17559. }
  17560. else {
  17561. host[`[${propName}]`] = propName;
  17562. }
  17563. });
  17564. const hostListeners = propertyMetadata[propName].filter(a => createHostListener.isTypeOf(a));
  17565. hostListeners.forEach(hostListener => {
  17566. const args = hostListener.args || [];
  17567. host[`(${hostListener.eventName})`] = `${propName}(${args.join(',')})`;
  17568. });
  17569. const query = findLast(propertyMetadata[propName], (a) => QUERY_METADATA_IDENTIFIERS.some(i => i.isTypeOf(a)));
  17570. if (query) {
  17571. queries[propName] = query;
  17572. }
  17573. });
  17574. return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
  17575. }
  17576. _extractPublicName(def) { return splitAtColon(def, [null, def])[1].trim(); }
  17577. _dedupeBindings(bindings) {
  17578. const names = new Set();
  17579. const publicNames = new Set();
  17580. const reversedResult = [];
  17581. // go last to first to allow later entries to overwrite previous entries
  17582. for (let i = bindings.length - 1; i >= 0; i--) {
  17583. const binding = bindings[i];
  17584. const name = this._extractPublicName(binding);
  17585. publicNames.add(name);
  17586. if (!names.has(name)) {
  17587. names.add(name);
  17588. reversedResult.push(binding);
  17589. }
  17590. }
  17591. return reversedResult.reverse();
  17592. }
  17593. _merge(directive, inputs, outputs, host, queries, guards, directiveType) {
  17594. const mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
  17595. const mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
  17596. const mergedHost = directive.host ? Object.assign({}, directive.host, host) : host;
  17597. const mergedQueries = directive.queries ? Object.assign({}, directive.queries, queries) : queries;
  17598. if (createComponent.isTypeOf(directive)) {
  17599. const comp = directive;
  17600. return createComponent({
  17601. selector: comp.selector,
  17602. inputs: mergedInputs,
  17603. outputs: mergedOutputs,
  17604. host: mergedHost,
  17605. exportAs: comp.exportAs,
  17606. moduleId: comp.moduleId,
  17607. queries: mergedQueries,
  17608. changeDetection: comp.changeDetection,
  17609. providers: comp.providers,
  17610. viewProviders: comp.viewProviders,
  17611. entryComponents: comp.entryComponents,
  17612. template: comp.template,
  17613. templateUrl: comp.templateUrl,
  17614. styles: comp.styles,
  17615. styleUrls: comp.styleUrls,
  17616. encapsulation: comp.encapsulation,
  17617. animations: comp.animations,
  17618. interpolation: comp.interpolation,
  17619. preserveWhitespaces: directive.preserveWhitespaces,
  17620. });
  17621. }
  17622. else {
  17623. return createDirective({
  17624. selector: directive.selector,
  17625. inputs: mergedInputs,
  17626. outputs: mergedOutputs,
  17627. host: mergedHost,
  17628. exportAs: directive.exportAs,
  17629. queries: mergedQueries,
  17630. providers: directive.providers, guards
  17631. });
  17632. }
  17633. }
  17634. }
  17635. function isDirectiveMetadata(type) {
  17636. return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
  17637. }
  17638. function findLast(arr, condition) {
  17639. for (let i = arr.length - 1; i >= 0; i--) {
  17640. if (condition(arr[i])) {
  17641. return arr[i];
  17642. }
  17643. }
  17644. return null;
  17645. }
  17646. /**
  17647. * @license
  17648. * Copyright Google Inc. All Rights Reserved.
  17649. *
  17650. * Use of this source code is governed by an MIT-style license that can be
  17651. * found in the LICENSE file at https://angular.io/license
  17652. */
  17653. /**
  17654. * An i18n error.
  17655. */
  17656. class I18nError extends ParseError {
  17657. constructor(span, msg) { super(span, msg); }
  17658. }
  17659. /**
  17660. * @license
  17661. * Copyright Google Inc. All Rights Reserved.
  17662. *
  17663. * Use of this source code is governed by an MIT-style license that can be
  17664. * found in the LICENSE file at https://angular.io/license
  17665. */
  17666. const _I18N_ATTR = 'i18n';
  17667. const _I18N_ATTR_PREFIX = 'i18n-';
  17668. const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
  17669. const MEANING_SEPARATOR = '|';
  17670. const ID_SEPARATOR = '@@';
  17671. let i18nCommentsWarned = false;
  17672. /**
  17673. * Extract translatable messages from an html AST
  17674. */
  17675. function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
  17676. const visitor = new _Visitor$2(implicitTags, implicitAttrs);
  17677. return visitor.extract(nodes, interpolationConfig);
  17678. }
  17679. function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
  17680. const visitor = new _Visitor$2(implicitTags, implicitAttrs);
  17681. return visitor.merge(nodes, translations, interpolationConfig);
  17682. }
  17683. class ExtractionResult {
  17684. constructor(messages, errors) {
  17685. this.messages = messages;
  17686. this.errors = errors;
  17687. }
  17688. }
  17689. var _VisitorMode;
  17690. (function (_VisitorMode) {
  17691. _VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
  17692. _VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
  17693. })(_VisitorMode || (_VisitorMode = {}));
  17694. /**
  17695. * This Visitor is used:
  17696. * 1. to extract all the translatable strings from an html AST (see `extract()`),
  17697. * 2. to replace the translatable strings with the actual translations (see `merge()`)
  17698. *
  17699. * @internal
  17700. */
  17701. class _Visitor$2 {
  17702. constructor(_implicitTags, _implicitAttrs) {
  17703. this._implicitTags = _implicitTags;
  17704. this._implicitAttrs = _implicitAttrs;
  17705. }
  17706. /**
  17707. * Extracts the messages from the tree
  17708. */
  17709. extract(nodes, interpolationConfig) {
  17710. this._init(_VisitorMode.Extract, interpolationConfig);
  17711. nodes.forEach(node => node.visit(this, null));
  17712. if (this._inI18nBlock) {
  17713. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  17714. }
  17715. return new ExtractionResult(this._messages, this._errors);
  17716. }
  17717. /**
  17718. * Returns a tree where all translatable nodes are translated
  17719. */
  17720. merge(nodes, translations, interpolationConfig) {
  17721. this._init(_VisitorMode.Merge, interpolationConfig);
  17722. this._translations = translations;
  17723. // Construct a single fake root element
  17724. const wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
  17725. const translatedNode = wrapper.visit(this, null);
  17726. if (this._inI18nBlock) {
  17727. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  17728. }
  17729. return new ParseTreeResult(translatedNode.children, this._errors);
  17730. }
  17731. visitExpansionCase(icuCase, context) {
  17732. // Parse cases for translatable html attributes
  17733. const expression = visitAll$1(this, icuCase.expression, context);
  17734. if (this._mode === _VisitorMode.Merge) {
  17735. return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
  17736. }
  17737. }
  17738. visitExpansion(icu, context) {
  17739. this._mayBeAddBlockChildren(icu);
  17740. const wasInIcu = this._inIcu;
  17741. if (!this._inIcu) {
  17742. // nested ICU messages should not be extracted but top-level translated as a whole
  17743. if (this._isInTranslatableSection) {
  17744. this._addMessage([icu]);
  17745. }
  17746. this._inIcu = true;
  17747. }
  17748. const cases = visitAll$1(this, icu.cases, context);
  17749. if (this._mode === _VisitorMode.Merge) {
  17750. icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
  17751. }
  17752. this._inIcu = wasInIcu;
  17753. return icu;
  17754. }
  17755. visitComment(comment, context) {
  17756. const isOpening = _isOpeningComment(comment);
  17757. if (isOpening && this._isInTranslatableSection) {
  17758. this._reportError(comment, 'Could not start a block inside a translatable section');
  17759. return;
  17760. }
  17761. const isClosing = _isClosingComment(comment);
  17762. if (isClosing && !this._inI18nBlock) {
  17763. this._reportError(comment, 'Trying to close an unopened block');
  17764. return;
  17765. }
  17766. if (!this._inI18nNode && !this._inIcu) {
  17767. if (!this._inI18nBlock) {
  17768. if (isOpening) {
  17769. // deprecated from v5 you should use <ng-container i18n> instead of i18n comments
  17770. if (!i18nCommentsWarned && console && console.warn) {
  17771. i18nCommentsWarned = true;
  17772. const details = comment.sourceSpan.details ? `, ${comment.sourceSpan.details}` : '';
  17773. // TODO(ocombe): use a log service once there is a public one available
  17774. console.warn(`I18n comments are deprecated, use an <ng-container> element instead (${comment.sourceSpan.start}${details})`);
  17775. }
  17776. this._inI18nBlock = true;
  17777. this._blockStartDepth = this._depth;
  17778. this._blockChildren = [];
  17779. this._blockMeaningAndDesc =
  17780. comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
  17781. this._openTranslatableSection(comment);
  17782. }
  17783. }
  17784. else {
  17785. if (isClosing) {
  17786. if (this._depth == this._blockStartDepth) {
  17787. this._closeTranslatableSection(comment, this._blockChildren);
  17788. this._inI18nBlock = false;
  17789. const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
  17790. // merge attributes in sections
  17791. const nodes = this._translateMessage(comment, message);
  17792. return visitAll$1(this, nodes);
  17793. }
  17794. else {
  17795. this._reportError(comment, 'I18N blocks should not cross element boundaries');
  17796. return;
  17797. }
  17798. }
  17799. }
  17800. }
  17801. }
  17802. visitText(text, context) {
  17803. if (this._isInTranslatableSection) {
  17804. this._mayBeAddBlockChildren(text);
  17805. }
  17806. return text;
  17807. }
  17808. visitElement(el, context) {
  17809. this._mayBeAddBlockChildren(el);
  17810. this._depth++;
  17811. const wasInI18nNode = this._inI18nNode;
  17812. const wasInImplicitNode = this._inImplicitNode;
  17813. let childNodes = [];
  17814. let translatedChildNodes = undefined;
  17815. // Extract:
  17816. // - top level nodes with the (implicit) "i18n" attribute if not already in a section
  17817. // - ICU messages
  17818. const i18nAttr = _getI18nAttr(el);
  17819. const i18nMeta = i18nAttr ? i18nAttr.value : '';
  17820. const isImplicit = this._implicitTags.some(tag => el.name === tag) && !this._inIcu &&
  17821. !this._isInTranslatableSection;
  17822. const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
  17823. this._inImplicitNode = wasInImplicitNode || isImplicit;
  17824. if (!this._isInTranslatableSection && !this._inIcu) {
  17825. if (i18nAttr || isTopLevelImplicit) {
  17826. this._inI18nNode = true;
  17827. const message = this._addMessage(el.children, i18nMeta);
  17828. translatedChildNodes = this._translateMessage(el, message);
  17829. }
  17830. if (this._mode == _VisitorMode.Extract) {
  17831. const isTranslatable = i18nAttr || isTopLevelImplicit;
  17832. if (isTranslatable)
  17833. this._openTranslatableSection(el);
  17834. visitAll$1(this, el.children);
  17835. if (isTranslatable)
  17836. this._closeTranslatableSection(el, el.children);
  17837. }
  17838. }
  17839. else {
  17840. if (i18nAttr || isTopLevelImplicit) {
  17841. this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
  17842. }
  17843. if (this._mode == _VisitorMode.Extract) {
  17844. // Descend into child nodes for extraction
  17845. visitAll$1(this, el.children);
  17846. }
  17847. }
  17848. if (this._mode === _VisitorMode.Merge) {
  17849. const visitNodes = translatedChildNodes || el.children;
  17850. visitNodes.forEach(child => {
  17851. const visited = child.visit(this, context);
  17852. if (visited && !this._isInTranslatableSection) {
  17853. // Do not add the children from translatable sections (= i18n blocks here)
  17854. // They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
  17855. childNodes = childNodes.concat(visited);
  17856. }
  17857. });
  17858. }
  17859. this._visitAttributesOf(el);
  17860. this._depth--;
  17861. this._inI18nNode = wasInI18nNode;
  17862. this._inImplicitNode = wasInImplicitNode;
  17863. if (this._mode === _VisitorMode.Merge) {
  17864. const translatedAttrs = this._translateAttributes(el);
  17865. return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
  17866. }
  17867. return null;
  17868. }
  17869. visitAttribute(attribute, context) {
  17870. throw new Error('unreachable code');
  17871. }
  17872. _init(mode, interpolationConfig) {
  17873. this._mode = mode;
  17874. this._inI18nBlock = false;
  17875. this._inI18nNode = false;
  17876. this._depth = 0;
  17877. this._inIcu = false;
  17878. this._msgCountAtSectionStart = undefined;
  17879. this._errors = [];
  17880. this._messages = [];
  17881. this._inImplicitNode = false;
  17882. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  17883. }
  17884. // looks for translatable attributes
  17885. _visitAttributesOf(el) {
  17886. const explicitAttrNameToValue = {};
  17887. const implicitAttrNames = this._implicitAttrs[el.name] || [];
  17888. el.attrs.filter(attr => attr.name.startsWith(_I18N_ATTR_PREFIX))
  17889. .forEach(attr => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  17890. attr.value);
  17891. el.attrs.forEach(attr => {
  17892. if (attr.name in explicitAttrNameToValue) {
  17893. this._addMessage([attr], explicitAttrNameToValue[attr.name]);
  17894. }
  17895. else if (implicitAttrNames.some(name => attr.name === name)) {
  17896. this._addMessage([attr]);
  17897. }
  17898. });
  17899. }
  17900. // add a translatable message
  17901. _addMessage(ast, msgMeta) {
  17902. if (ast.length == 0 ||
  17903. ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
  17904. // Do not create empty messages
  17905. return null;
  17906. }
  17907. const { meaning, description, id } = _parseMessageMeta(msgMeta);
  17908. const message = this._createI18nMessage(ast, meaning, description, id);
  17909. this._messages.push(message);
  17910. return message;
  17911. }
  17912. // Translates the given message given the `TranslationBundle`
  17913. // This is used for translating elements / blocks - see `_translateAttributes` for attributes
  17914. // no-op when called in extraction mode (returns [])
  17915. _translateMessage(el, message) {
  17916. if (message && this._mode === _VisitorMode.Merge) {
  17917. const nodes = this._translations.get(message);
  17918. if (nodes) {
  17919. return nodes;
  17920. }
  17921. this._reportError(el, `Translation unavailable for message id="${this._translations.digest(message)}"`);
  17922. }
  17923. return [];
  17924. }
  17925. // translate the attributes of an element and remove i18n specific attributes
  17926. _translateAttributes(el) {
  17927. const attributes = el.attrs;
  17928. const i18nParsedMessageMeta = {};
  17929. attributes.forEach(attr => {
  17930. if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  17931. i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  17932. _parseMessageMeta(attr.value);
  17933. }
  17934. });
  17935. const translatedAttributes = [];
  17936. attributes.forEach((attr) => {
  17937. if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  17938. // strip i18n specific attributes
  17939. return;
  17940. }
  17941. if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
  17942. const { meaning, description, id } = i18nParsedMessageMeta[attr.name];
  17943. const message = this._createI18nMessage([attr], meaning, description, id);
  17944. const nodes = this._translations.get(message);
  17945. if (nodes) {
  17946. if (nodes.length == 0) {
  17947. translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan));
  17948. }
  17949. else if (nodes[0] instanceof Text$3) {
  17950. const value = nodes[0].value;
  17951. translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan));
  17952. }
  17953. else {
  17954. this._reportError(el, `Unexpected translation for attribute "${attr.name}" (id="${id || this._translations.digest(message)}")`);
  17955. }
  17956. }
  17957. else {
  17958. this._reportError(el, `Translation unavailable for attribute "${attr.name}" (id="${id || this._translations.digest(message)}")`);
  17959. }
  17960. }
  17961. else {
  17962. translatedAttributes.push(attr);
  17963. }
  17964. });
  17965. return translatedAttributes;
  17966. }
  17967. /**
  17968. * Add the node as a child of the block when:
  17969. * - we are in a block,
  17970. * - we are not inside a ICU message (those are handled separately),
  17971. * - the node is a "direct child" of the block
  17972. */
  17973. _mayBeAddBlockChildren(node) {
  17974. if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
  17975. this._blockChildren.push(node);
  17976. }
  17977. }
  17978. /**
  17979. * Marks the start of a section, see `_closeTranslatableSection`
  17980. */
  17981. _openTranslatableSection(node) {
  17982. if (this._isInTranslatableSection) {
  17983. this._reportError(node, 'Unexpected section start');
  17984. }
  17985. else {
  17986. this._msgCountAtSectionStart = this._messages.length;
  17987. }
  17988. }
  17989. /**
  17990. * A translatable section could be:
  17991. * - the content of translatable element,
  17992. * - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
  17993. */
  17994. get _isInTranslatableSection() {
  17995. return this._msgCountAtSectionStart !== void 0;
  17996. }
  17997. /**
  17998. * Terminates a section.
  17999. *
  18000. * If a section has only one significant children (comments not significant) then we should not
  18001. * keep the message from this children:
  18002. *
  18003. * `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
  18004. * - one for the <p> content with meaning and description,
  18005. * - another one for the ICU message.
  18006. *
  18007. * In this case the last message is discarded as it contains less information (the AST is
  18008. * otherwise identical).
  18009. *
  18010. * Note that we should still keep messages extracted from attributes inside the section (ie in the
  18011. * ICU message here)
  18012. */
  18013. _closeTranslatableSection(node, directChildren) {
  18014. if (!this._isInTranslatableSection) {
  18015. this._reportError(node, 'Unexpected section end');
  18016. return;
  18017. }
  18018. const startIndex = this._msgCountAtSectionStart;
  18019. const significantChildren = directChildren.reduce((count, node) => count + (node instanceof Comment ? 0 : 1), 0);
  18020. if (significantChildren == 1) {
  18021. for (let i = this._messages.length - 1; i >= startIndex; i--) {
  18022. const ast = this._messages[i].nodes;
  18023. if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
  18024. this._messages.splice(i, 1);
  18025. break;
  18026. }
  18027. }
  18028. }
  18029. this._msgCountAtSectionStart = undefined;
  18030. }
  18031. _reportError(node, msg) {
  18032. this._errors.push(new I18nError(node.sourceSpan, msg));
  18033. }
  18034. }
  18035. function _isOpeningComment(n) {
  18036. return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
  18037. }
  18038. function _isClosingComment(n) {
  18039. return !!(n instanceof Comment && n.value && n.value === '/i18n');
  18040. }
  18041. function _getI18nAttr(p) {
  18042. return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
  18043. }
  18044. function _parseMessageMeta(i18n) {
  18045. if (!i18n)
  18046. return { meaning: '', description: '', id: '' };
  18047. const idIndex = i18n.indexOf(ID_SEPARATOR);
  18048. const descIndex = i18n.indexOf(MEANING_SEPARATOR);
  18049. const [meaningAndDesc, id] = (idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''];
  18050. const [meaning, description] = (descIndex > -1) ?
  18051. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  18052. ['', meaningAndDesc];
  18053. return { meaning, description, id };
  18054. }
  18055. /**
  18056. * @license
  18057. * Copyright Google Inc. All Rights Reserved.
  18058. *
  18059. * Use of this source code is governed by an MIT-style license that can be
  18060. * found in the LICENSE file at https://angular.io/license
  18061. */
  18062. class XmlTagDefinition {
  18063. constructor() {
  18064. this.closedByParent = false;
  18065. this.contentType = TagContentType.PARSABLE_DATA;
  18066. this.isVoid = false;
  18067. this.ignoreFirstLf = false;
  18068. this.canSelfClose = true;
  18069. }
  18070. requireExtraParent(currentParent) { return false; }
  18071. isClosedByChild(name) { return false; }
  18072. }
  18073. const _TAG_DEFINITION = new XmlTagDefinition();
  18074. function getXmlTagDefinition(tagName) {
  18075. return _TAG_DEFINITION;
  18076. }
  18077. /**
  18078. * @license
  18079. * Copyright Google Inc. All Rights Reserved.
  18080. *
  18081. * Use of this source code is governed by an MIT-style license that can be
  18082. * found in the LICENSE file at https://angular.io/license
  18083. */
  18084. class XmlParser extends Parser {
  18085. constructor() { super(getXmlTagDefinition); }
  18086. parse(source, url, options) {
  18087. return super.parse(source, url, options);
  18088. }
  18089. }
  18090. /**
  18091. * @license
  18092. * Copyright Google Inc. All Rights Reserved.
  18093. *
  18094. * Use of this source code is governed by an MIT-style license that can be
  18095. * found in the LICENSE file at https://angular.io/license
  18096. */
  18097. const _VERSION = '1.2';
  18098. const _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
  18099. // TODO(vicb): make this a param (s/_/-/)
  18100. const _DEFAULT_SOURCE_LANG = 'en';
  18101. const _PLACEHOLDER_TAG$1 = 'x';
  18102. const _MARKER_TAG = 'mrk';
  18103. const _FILE_TAG = 'file';
  18104. const _SOURCE_TAG$1 = 'source';
  18105. const _SEGMENT_SOURCE_TAG = 'seg-source';
  18106. const _TARGET_TAG = 'target';
  18107. const _UNIT_TAG = 'trans-unit';
  18108. const _CONTEXT_GROUP_TAG = 'context-group';
  18109. const _CONTEXT_TAG = 'context';
  18110. // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
  18111. // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
  18112. class Xliff extends Serializer {
  18113. write(messages, locale) {
  18114. const visitor = new _WriteVisitor();
  18115. const transUnits = [];
  18116. messages.forEach(message => {
  18117. let contextTags = [];
  18118. message.sources.forEach((source) => {
  18119. let contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
  18120. 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));
  18121. contextTags.push(new CR(8), contextGroupTag);
  18122. });
  18123. const transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
  18124. transUnit.children.push(new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes)), ...contextTags);
  18125. if (message.description) {
  18126. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
  18127. }
  18128. if (message.meaning) {
  18129. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
  18130. }
  18131. transUnit.children.push(new CR(6));
  18132. transUnits.push(new CR(6), transUnit);
  18133. });
  18134. const body = new Tag('body', {}, [...transUnits, new CR(4)]);
  18135. const file = new Tag('file', {
  18136. 'source-language': locale || _DEFAULT_SOURCE_LANG,
  18137. datatype: 'plaintext',
  18138. original: 'ng2.template',
  18139. }, [new CR(4), body, new CR(2)]);
  18140. const xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
  18141. return serialize([
  18142. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  18143. ]);
  18144. }
  18145. load(content, url) {
  18146. // xliff to xml nodes
  18147. const xliffParser = new XliffParser();
  18148. const { locale, msgIdToHtml, errors } = xliffParser.parse(content, url);
  18149. // xml nodes to i18n nodes
  18150. const i18nNodesByMsgId = {};
  18151. const converter = new XmlToI18n();
  18152. Object.keys(msgIdToHtml).forEach(msgId => {
  18153. const { i18nNodes, errors: e } = converter.convert(msgIdToHtml[msgId], url);
  18154. errors.push(...e);
  18155. i18nNodesByMsgId[msgId] = i18nNodes;
  18156. });
  18157. if (errors.length) {
  18158. throw new Error(`xliff parse errors:\n${errors.join('\n')}`);
  18159. }
  18160. return { locale: locale, i18nNodesByMsgId };
  18161. }
  18162. digest(message) { return digest(message); }
  18163. }
  18164. class _WriteVisitor {
  18165. visitText(text, context) { return [new Text$2(text.value)]; }
  18166. visitContainer(container, context) {
  18167. const nodes = [];
  18168. container.children.forEach((node) => nodes.push(...node.visit(this)));
  18169. return nodes;
  18170. }
  18171. visitIcu(icu, context) {
  18172. const nodes = [new Text$2(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
  18173. Object.keys(icu.cases).forEach((c) => {
  18174. nodes.push(new Text$2(`${c} {`), ...icu.cases[c].visit(this), new Text$2(`} `));
  18175. });
  18176. nodes.push(new Text$2(`}`));
  18177. return nodes;
  18178. }
  18179. visitTagPlaceholder(ph, context) {
  18180. const ctype = getCtypeForTag(ph.tag);
  18181. if (ph.isVoid) {
  18182. // void tags have no children nor closing tags
  18183. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype, 'equiv-text': `<${ph.tag}/>` })];
  18184. }
  18185. const startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype, 'equiv-text': `<${ph.tag}>` });
  18186. const closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype, 'equiv-text': `</${ph.tag}>` });
  18187. return [startTagPh, ...this.serialize(ph.children), closeTagPh];
  18188. }
  18189. visitPlaceholder(ph, context) {
  18190. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': `{{${ph.value}}}` })];
  18191. }
  18192. visitIcuPlaceholder(ph, context) {
  18193. const equivText = `{${ph.value.expression}, ${ph.value.type}, ${Object.keys(ph.value.cases).map((value) => value + ' {...}').join(' ')}}`;
  18194. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
  18195. }
  18196. serialize(nodes) {
  18197. return [].concat(...nodes.map(node => node.visit(this)));
  18198. }
  18199. }
  18200. // TODO(vicb): add error management (structure)
  18201. // Extract messages as xml nodes from the xliff file
  18202. class XliffParser {
  18203. constructor() {
  18204. this._locale = null;
  18205. }
  18206. parse(xliff, url) {
  18207. this._unitMlString = null;
  18208. this._msgIdToHtml = {};
  18209. const xml = new XmlParser().parse(xliff, url);
  18210. this._errors = xml.errors;
  18211. visitAll$1(this, xml.rootNodes, null);
  18212. return {
  18213. msgIdToHtml: this._msgIdToHtml,
  18214. errors: this._errors,
  18215. locale: this._locale,
  18216. };
  18217. }
  18218. visitElement(element, context) {
  18219. switch (element.name) {
  18220. case _UNIT_TAG:
  18221. this._unitMlString = null;
  18222. const idAttr = element.attrs.find((attr) => attr.name === 'id');
  18223. if (!idAttr) {
  18224. this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`);
  18225. }
  18226. else {
  18227. const id = idAttr.value;
  18228. if (this._msgIdToHtml.hasOwnProperty(id)) {
  18229. this._addError(element, `Duplicated translations for msg ${id}`);
  18230. }
  18231. else {
  18232. visitAll$1(this, element.children, null);
  18233. if (typeof this._unitMlString === 'string') {
  18234. this._msgIdToHtml[id] = this._unitMlString;
  18235. }
  18236. else {
  18237. this._addError(element, `Message ${id} misses a translation`);
  18238. }
  18239. }
  18240. }
  18241. break;
  18242. // ignore those tags
  18243. case _SOURCE_TAG$1:
  18244. case _SEGMENT_SOURCE_TAG:
  18245. break;
  18246. case _TARGET_TAG:
  18247. const innerTextStart = element.startSourceSpan.end.offset;
  18248. const innerTextEnd = element.endSourceSpan.start.offset;
  18249. const content = element.startSourceSpan.start.file.content;
  18250. const innerText = content.slice(innerTextStart, innerTextEnd);
  18251. this._unitMlString = innerText;
  18252. break;
  18253. case _FILE_TAG:
  18254. const localeAttr = element.attrs.find((attr) => attr.name === 'target-language');
  18255. if (localeAttr) {
  18256. this._locale = localeAttr.value;
  18257. }
  18258. visitAll$1(this, element.children, null);
  18259. break;
  18260. default:
  18261. // TODO(vicb): assert file structure, xliff version
  18262. // For now only recurse on unhandled nodes
  18263. visitAll$1(this, element.children, null);
  18264. }
  18265. }
  18266. visitAttribute(attribute, context) { }
  18267. visitText(text, context) { }
  18268. visitComment(comment, context) { }
  18269. visitExpansion(expansion, context) { }
  18270. visitExpansionCase(expansionCase, context) { }
  18271. _addError(node, message) {
  18272. this._errors.push(new I18nError(node.sourceSpan, message));
  18273. }
  18274. }
  18275. // Convert ml nodes (xliff syntax) to i18n nodes
  18276. class XmlToI18n {
  18277. convert(message, url) {
  18278. const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  18279. this._errors = xmlIcu.errors;
  18280. const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  18281. [] :
  18282. [].concat(...visitAll$1(this, xmlIcu.rootNodes));
  18283. return {
  18284. i18nNodes: i18nNodes,
  18285. errors: this._errors,
  18286. };
  18287. }
  18288. visitText(text, context) { return new Text$1(text.value, text.sourceSpan); }
  18289. visitElement(el, context) {
  18290. if (el.name === _PLACEHOLDER_TAG$1) {
  18291. const nameAttr = el.attrs.find((attr) => attr.name === 'id');
  18292. if (nameAttr) {
  18293. return new Placeholder('', nameAttr.value, el.sourceSpan);
  18294. }
  18295. this._addError(el, `<${_PLACEHOLDER_TAG$1}> misses the "id" attribute`);
  18296. return null;
  18297. }
  18298. if (el.name === _MARKER_TAG) {
  18299. return [].concat(...visitAll$1(this, el.children));
  18300. }
  18301. this._addError(el, `Unexpected tag`);
  18302. return null;
  18303. }
  18304. visitExpansion(icu, context) {
  18305. const caseMap = {};
  18306. visitAll$1(this, icu.cases).forEach((c) => {
  18307. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  18308. });
  18309. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  18310. }
  18311. visitExpansionCase(icuCase, context) {
  18312. return {
  18313. value: icuCase.value,
  18314. nodes: visitAll$1(this, icuCase.expression),
  18315. };
  18316. }
  18317. visitComment(comment, context) { }
  18318. visitAttribute(attribute, context) { }
  18319. _addError(node, message) {
  18320. this._errors.push(new I18nError(node.sourceSpan, message));
  18321. }
  18322. }
  18323. function getCtypeForTag(tag) {
  18324. switch (tag.toLowerCase()) {
  18325. case 'br':
  18326. return 'lb';
  18327. case 'img':
  18328. return 'image';
  18329. default:
  18330. return `x-${tag}`;
  18331. }
  18332. }
  18333. /**
  18334. * @license
  18335. * Copyright Google Inc. All Rights Reserved.
  18336. *
  18337. * Use of this source code is governed by an MIT-style license that can be
  18338. * found in the LICENSE file at https://angular.io/license
  18339. */
  18340. const _VERSION$1 = '2.0';
  18341. const _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
  18342. // TODO(vicb): make this a param (s/_/-/)
  18343. const _DEFAULT_SOURCE_LANG$1 = 'en';
  18344. const _PLACEHOLDER_TAG$2 = 'ph';
  18345. const _PLACEHOLDER_SPANNING_TAG = 'pc';
  18346. const _MARKER_TAG$1 = 'mrk';
  18347. const _XLIFF_TAG = 'xliff';
  18348. const _SOURCE_TAG$2 = 'source';
  18349. const _TARGET_TAG$1 = 'target';
  18350. const _UNIT_TAG$1 = 'unit';
  18351. // http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
  18352. class Xliff2 extends Serializer {
  18353. write(messages, locale) {
  18354. const visitor = new _WriteVisitor$1();
  18355. const units = [];
  18356. messages.forEach(message => {
  18357. const unit = new Tag(_UNIT_TAG$1, { id: message.id });
  18358. const notes = new Tag('notes');
  18359. if (message.description || message.meaning) {
  18360. if (message.description) {
  18361. notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
  18362. }
  18363. if (message.meaning) {
  18364. notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
  18365. }
  18366. }
  18367. message.sources.forEach((source) => {
  18368. notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
  18369. new Text$2(`${source.filePath}:${source.startLine}${source.endLine !== source.startLine ? ',' + source.endLine : ''}`)
  18370. ]));
  18371. });
  18372. notes.children.push(new CR(6));
  18373. unit.children.push(new CR(6), notes);
  18374. const segment = new Tag('segment');
  18375. segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
  18376. unit.children.push(new CR(6), segment, new CR(4));
  18377. units.push(new CR(4), unit);
  18378. });
  18379. const file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, [...units, new CR(2)]);
  18380. const xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
  18381. return serialize([
  18382. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  18383. ]);
  18384. }
  18385. load(content, url) {
  18386. // xliff to xml nodes
  18387. const xliff2Parser = new Xliff2Parser();
  18388. const { locale, msgIdToHtml, errors } = xliff2Parser.parse(content, url);
  18389. // xml nodes to i18n nodes
  18390. const i18nNodesByMsgId = {};
  18391. const converter = new XmlToI18n$1();
  18392. Object.keys(msgIdToHtml).forEach(msgId => {
  18393. const { i18nNodes, errors: e } = converter.convert(msgIdToHtml[msgId], url);
  18394. errors.push(...e);
  18395. i18nNodesByMsgId[msgId] = i18nNodes;
  18396. });
  18397. if (errors.length) {
  18398. throw new Error(`xliff2 parse errors:\n${errors.join('\n')}`);
  18399. }
  18400. return { locale: locale, i18nNodesByMsgId };
  18401. }
  18402. digest(message) { return decimalDigest(message); }
  18403. }
  18404. class _WriteVisitor$1 {
  18405. visitText(text, context) { return [new Text$2(text.value)]; }
  18406. visitContainer(container, context) {
  18407. const nodes = [];
  18408. container.children.forEach((node) => nodes.push(...node.visit(this)));
  18409. return nodes;
  18410. }
  18411. visitIcu(icu, context) {
  18412. const nodes = [new Text$2(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
  18413. Object.keys(icu.cases).forEach((c) => {
  18414. nodes.push(new Text$2(`${c} {`), ...icu.cases[c].visit(this), new Text$2(`} `));
  18415. });
  18416. nodes.push(new Text$2(`}`));
  18417. return nodes;
  18418. }
  18419. visitTagPlaceholder(ph, context) {
  18420. const type = getTypeForTag(ph.tag);
  18421. if (ph.isVoid) {
  18422. const tagPh = new Tag(_PLACEHOLDER_TAG$2, {
  18423. id: (this._nextPlaceholderId++).toString(),
  18424. equiv: ph.startName,
  18425. type: type,
  18426. disp: `<${ph.tag}/>`,
  18427. });
  18428. return [tagPh];
  18429. }
  18430. const tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
  18431. id: (this._nextPlaceholderId++).toString(),
  18432. equivStart: ph.startName,
  18433. equivEnd: ph.closeName,
  18434. type: type,
  18435. dispStart: `<${ph.tag}>`,
  18436. dispEnd: `</${ph.tag}>`,
  18437. });
  18438. const nodes = [].concat(...ph.children.map(node => node.visit(this)));
  18439. if (nodes.length) {
  18440. nodes.forEach((node) => tagPc.children.push(node));
  18441. }
  18442. else {
  18443. tagPc.children.push(new Text$2(''));
  18444. }
  18445. return [tagPc];
  18446. }
  18447. visitPlaceholder(ph, context) {
  18448. const idStr = (this._nextPlaceholderId++).toString();
  18449. return [new Tag(_PLACEHOLDER_TAG$2, {
  18450. id: idStr,
  18451. equiv: ph.name,
  18452. disp: `{{${ph.value}}}`,
  18453. })];
  18454. }
  18455. visitIcuPlaceholder(ph, context) {
  18456. const cases = Object.keys(ph.value.cases).map((value) => value + ' {...}').join(' ');
  18457. const idStr = (this._nextPlaceholderId++).toString();
  18458. return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: `{${ph.value.expression}, ${ph.value.type}, ${cases}}` })];
  18459. }
  18460. serialize(nodes) {
  18461. this._nextPlaceholderId = 0;
  18462. return [].concat(...nodes.map(node => node.visit(this)));
  18463. }
  18464. }
  18465. // Extract messages as xml nodes from the xliff file
  18466. class Xliff2Parser {
  18467. constructor() {
  18468. this._locale = null;
  18469. }
  18470. parse(xliff, url) {
  18471. this._unitMlString = null;
  18472. this._msgIdToHtml = {};
  18473. const xml = new XmlParser().parse(xliff, url);
  18474. this._errors = xml.errors;
  18475. visitAll$1(this, xml.rootNodes, null);
  18476. return {
  18477. msgIdToHtml: this._msgIdToHtml,
  18478. errors: this._errors,
  18479. locale: this._locale,
  18480. };
  18481. }
  18482. visitElement(element, context) {
  18483. switch (element.name) {
  18484. case _UNIT_TAG$1:
  18485. this._unitMlString = null;
  18486. const idAttr = element.attrs.find((attr) => attr.name === 'id');
  18487. if (!idAttr) {
  18488. this._addError(element, `<${_UNIT_TAG$1}> misses the "id" attribute`);
  18489. }
  18490. else {
  18491. const id = idAttr.value;
  18492. if (this._msgIdToHtml.hasOwnProperty(id)) {
  18493. this._addError(element, `Duplicated translations for msg ${id}`);
  18494. }
  18495. else {
  18496. visitAll$1(this, element.children, null);
  18497. if (typeof this._unitMlString === 'string') {
  18498. this._msgIdToHtml[id] = this._unitMlString;
  18499. }
  18500. else {
  18501. this._addError(element, `Message ${id} misses a translation`);
  18502. }
  18503. }
  18504. }
  18505. break;
  18506. case _SOURCE_TAG$2:
  18507. // ignore source message
  18508. break;
  18509. case _TARGET_TAG$1:
  18510. const innerTextStart = element.startSourceSpan.end.offset;
  18511. const innerTextEnd = element.endSourceSpan.start.offset;
  18512. const content = element.startSourceSpan.start.file.content;
  18513. const innerText = content.slice(innerTextStart, innerTextEnd);
  18514. this._unitMlString = innerText;
  18515. break;
  18516. case _XLIFF_TAG:
  18517. const localeAttr = element.attrs.find((attr) => attr.name === 'trgLang');
  18518. if (localeAttr) {
  18519. this._locale = localeAttr.value;
  18520. }
  18521. const versionAttr = element.attrs.find((attr) => attr.name === 'version');
  18522. if (versionAttr) {
  18523. const version = versionAttr.value;
  18524. if (version !== '2.0') {
  18525. this._addError(element, `The XLIFF file version ${version} is not compatible with XLIFF 2.0 serializer`);
  18526. }
  18527. else {
  18528. visitAll$1(this, element.children, null);
  18529. }
  18530. }
  18531. break;
  18532. default:
  18533. visitAll$1(this, element.children, null);
  18534. }
  18535. }
  18536. visitAttribute(attribute, context) { }
  18537. visitText(text, context) { }
  18538. visitComment(comment, context) { }
  18539. visitExpansion(expansion, context) { }
  18540. visitExpansionCase(expansionCase, context) { }
  18541. _addError(node, message) {
  18542. this._errors.push(new I18nError(node.sourceSpan, message));
  18543. }
  18544. }
  18545. // Convert ml nodes (xliff syntax) to i18n nodes
  18546. class XmlToI18n$1 {
  18547. convert(message, url) {
  18548. const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  18549. this._errors = xmlIcu.errors;
  18550. const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  18551. [] :
  18552. [].concat(...visitAll$1(this, xmlIcu.rootNodes));
  18553. return {
  18554. i18nNodes,
  18555. errors: this._errors,
  18556. };
  18557. }
  18558. visitText(text, context) { return new Text$1(text.value, text.sourceSpan); }
  18559. visitElement(el, context) {
  18560. switch (el.name) {
  18561. case _PLACEHOLDER_TAG$2:
  18562. const nameAttr = el.attrs.find((attr) => attr.name === 'equiv');
  18563. if (nameAttr) {
  18564. return [new Placeholder('', nameAttr.value, el.sourceSpan)];
  18565. }
  18566. this._addError(el, `<${_PLACEHOLDER_TAG$2}> misses the "equiv" attribute`);
  18567. break;
  18568. case _PLACEHOLDER_SPANNING_TAG:
  18569. const startAttr = el.attrs.find((attr) => attr.name === 'equivStart');
  18570. const endAttr = el.attrs.find((attr) => attr.name === 'equivEnd');
  18571. if (!startAttr) {
  18572. this._addError(el, `<${_PLACEHOLDER_TAG$2}> misses the "equivStart" attribute`);
  18573. }
  18574. else if (!endAttr) {
  18575. this._addError(el, `<${_PLACEHOLDER_TAG$2}> misses the "equivEnd" attribute`);
  18576. }
  18577. else {
  18578. const startId = startAttr.value;
  18579. const endId = endAttr.value;
  18580. const nodes = [];
  18581. return nodes.concat(new Placeholder('', startId, el.sourceSpan), ...el.children.map(node => node.visit(this, null)), new Placeholder('', endId, el.sourceSpan));
  18582. }
  18583. break;
  18584. case _MARKER_TAG$1:
  18585. return [].concat(...visitAll$1(this, el.children));
  18586. default:
  18587. this._addError(el, `Unexpected tag`);
  18588. }
  18589. return null;
  18590. }
  18591. visitExpansion(icu, context) {
  18592. const caseMap = {};
  18593. visitAll$1(this, icu.cases).forEach((c) => {
  18594. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  18595. });
  18596. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  18597. }
  18598. visitExpansionCase(icuCase, context) {
  18599. return {
  18600. value: icuCase.value,
  18601. nodes: [].concat(...visitAll$1(this, icuCase.expression)),
  18602. };
  18603. }
  18604. visitComment(comment, context) { }
  18605. visitAttribute(attribute, context) { }
  18606. _addError(node, message) {
  18607. this._errors.push(new I18nError(node.sourceSpan, message));
  18608. }
  18609. }
  18610. function getTypeForTag(tag) {
  18611. switch (tag.toLowerCase()) {
  18612. case 'br':
  18613. case 'b':
  18614. case 'i':
  18615. case 'u':
  18616. return 'fmt';
  18617. case 'img':
  18618. return 'image';
  18619. case 'a':
  18620. return 'link';
  18621. default:
  18622. return 'other';
  18623. }
  18624. }
  18625. /**
  18626. * @license
  18627. * Copyright Google Inc. All Rights Reserved.
  18628. *
  18629. * Use of this source code is governed by an MIT-style license that can be
  18630. * found in the LICENSE file at https://angular.io/license
  18631. */
  18632. const _TRANSLATIONS_TAG = 'translationbundle';
  18633. const _TRANSLATION_TAG = 'translation';
  18634. const _PLACEHOLDER_TAG$3 = 'ph';
  18635. class Xtb extends Serializer {
  18636. write(messages, locale) { throw new Error('Unsupported'); }
  18637. load(content, url) {
  18638. // xtb to xml nodes
  18639. const xtbParser = new XtbParser();
  18640. const { locale, msgIdToHtml, errors } = xtbParser.parse(content, url);
  18641. // xml nodes to i18n nodes
  18642. const i18nNodesByMsgId = {};
  18643. const converter = new XmlToI18n$2();
  18644. // Because we should be able to load xtb files that rely on features not supported by angular,
  18645. // we need to delay the conversion of html to i18n nodes so that non angular messages are not
  18646. // converted
  18647. Object.keys(msgIdToHtml).forEach(msgId => {
  18648. const valueFn = function () {
  18649. const { i18nNodes, errors } = converter.convert(msgIdToHtml[msgId], url);
  18650. if (errors.length) {
  18651. throw new Error(`xtb parse errors:\n${errors.join('\n')}`);
  18652. }
  18653. return i18nNodes;
  18654. };
  18655. createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
  18656. });
  18657. if (errors.length) {
  18658. throw new Error(`xtb parse errors:\n${errors.join('\n')}`);
  18659. }
  18660. return { locale: locale, i18nNodesByMsgId };
  18661. }
  18662. digest(message) { return digest$1(message); }
  18663. createNameMapper(message) {
  18664. return new SimplePlaceholderMapper(message, toPublicName);
  18665. }
  18666. }
  18667. function createLazyProperty(messages, id, valueFn) {
  18668. Object.defineProperty(messages, id, {
  18669. configurable: true,
  18670. enumerable: true,
  18671. get: function () {
  18672. const value = valueFn();
  18673. Object.defineProperty(messages, id, { enumerable: true, value });
  18674. return value;
  18675. },
  18676. set: _ => { throw new Error('Could not overwrite an XTB translation'); },
  18677. });
  18678. }
  18679. // Extract messages as xml nodes from the xtb file
  18680. class XtbParser {
  18681. constructor() {
  18682. this._locale = null;
  18683. }
  18684. parse(xtb, url) {
  18685. this._bundleDepth = 0;
  18686. this._msgIdToHtml = {};
  18687. // We can not parse the ICU messages at this point as some messages might not originate
  18688. // from Angular that could not be lex'd.
  18689. const xml = new XmlParser().parse(xtb, url);
  18690. this._errors = xml.errors;
  18691. visitAll$1(this, xml.rootNodes);
  18692. return {
  18693. msgIdToHtml: this._msgIdToHtml,
  18694. errors: this._errors,
  18695. locale: this._locale,
  18696. };
  18697. }
  18698. visitElement(element, context) {
  18699. switch (element.name) {
  18700. case _TRANSLATIONS_TAG:
  18701. this._bundleDepth++;
  18702. if (this._bundleDepth > 1) {
  18703. this._addError(element, `<${_TRANSLATIONS_TAG}> elements can not be nested`);
  18704. }
  18705. const langAttr = element.attrs.find((attr) => attr.name === 'lang');
  18706. if (langAttr) {
  18707. this._locale = langAttr.value;
  18708. }
  18709. visitAll$1(this, element.children, null);
  18710. this._bundleDepth--;
  18711. break;
  18712. case _TRANSLATION_TAG:
  18713. const idAttr = element.attrs.find((attr) => attr.name === 'id');
  18714. if (!idAttr) {
  18715. this._addError(element, `<${_TRANSLATION_TAG}> misses the "id" attribute`);
  18716. }
  18717. else {
  18718. const id = idAttr.value;
  18719. if (this._msgIdToHtml.hasOwnProperty(id)) {
  18720. this._addError(element, `Duplicated translations for msg ${id}`);
  18721. }
  18722. else {
  18723. const innerTextStart = element.startSourceSpan.end.offset;
  18724. const innerTextEnd = element.endSourceSpan.start.offset;
  18725. const content = element.startSourceSpan.start.file.content;
  18726. const innerText = content.slice(innerTextStart, innerTextEnd);
  18727. this._msgIdToHtml[id] = innerText;
  18728. }
  18729. }
  18730. break;
  18731. default:
  18732. this._addError(element, 'Unexpected tag');
  18733. }
  18734. }
  18735. visitAttribute(attribute, context) { }
  18736. visitText(text, context) { }
  18737. visitComment(comment, context) { }
  18738. visitExpansion(expansion, context) { }
  18739. visitExpansionCase(expansionCase, context) { }
  18740. _addError(node, message) {
  18741. this._errors.push(new I18nError(node.sourceSpan, message));
  18742. }
  18743. }
  18744. // Convert ml nodes (xtb syntax) to i18n nodes
  18745. class XmlToI18n$2 {
  18746. convert(message, url) {
  18747. const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  18748. this._errors = xmlIcu.errors;
  18749. const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  18750. [] :
  18751. visitAll$1(this, xmlIcu.rootNodes);
  18752. return {
  18753. i18nNodes,
  18754. errors: this._errors,
  18755. };
  18756. }
  18757. visitText(text, context) { return new Text$1(text.value, text.sourceSpan); }
  18758. visitExpansion(icu, context) {
  18759. const caseMap = {};
  18760. visitAll$1(this, icu.cases).forEach(c => {
  18761. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  18762. });
  18763. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  18764. }
  18765. visitExpansionCase(icuCase, context) {
  18766. return {
  18767. value: icuCase.value,
  18768. nodes: visitAll$1(this, icuCase.expression),
  18769. };
  18770. }
  18771. visitElement(el, context) {
  18772. if (el.name === _PLACEHOLDER_TAG$3) {
  18773. const nameAttr = el.attrs.find((attr) => attr.name === 'name');
  18774. if (nameAttr) {
  18775. return new Placeholder('', nameAttr.value, el.sourceSpan);
  18776. }
  18777. this._addError(el, `<${_PLACEHOLDER_TAG$3}> misses the "name" attribute`);
  18778. }
  18779. else {
  18780. this._addError(el, `Unexpected tag`);
  18781. }
  18782. return null;
  18783. }
  18784. visitComment(comment, context) { }
  18785. visitAttribute(attribute, context) { }
  18786. _addError(node, message) {
  18787. this._errors.push(new I18nError(node.sourceSpan, message));
  18788. }
  18789. }
  18790. /**
  18791. * @license
  18792. * Copyright Google Inc. All Rights Reserved.
  18793. *
  18794. * Use of this source code is governed by an MIT-style license that can be
  18795. * found in the LICENSE file at https://angular.io/license
  18796. */
  18797. /**
  18798. * A container for translated messages
  18799. */
  18800. class TranslationBundle {
  18801. constructor(_i18nNodesByMsgId = {}, locale, digest, mapperFactory, missingTranslationStrategy = MissingTranslationStrategy.Warning, console) {
  18802. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  18803. this.digest = digest;
  18804. this.mapperFactory = mapperFactory;
  18805. this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
  18806. }
  18807. // Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
  18808. static load(content, url, serializer, missingTranslationStrategy, console) {
  18809. const { locale, i18nNodesByMsgId } = serializer.load(content, url);
  18810. const digestFn = (m) => serializer.digest(m);
  18811. const mapperFactory = (m) => serializer.createNameMapper(m);
  18812. return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
  18813. }
  18814. // Returns the translation as HTML nodes from the given source message.
  18815. get(srcMsg) {
  18816. const html = this._i18nToHtml.convert(srcMsg);
  18817. if (html.errors.length) {
  18818. throw new Error(html.errors.join('\n'));
  18819. }
  18820. return html.nodes;
  18821. }
  18822. has(srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; }
  18823. }
  18824. class I18nToHtmlVisitor {
  18825. constructor(_i18nNodesByMsgId = {}, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
  18826. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  18827. this._locale = _locale;
  18828. this._digest = _digest;
  18829. this._mapperFactory = _mapperFactory;
  18830. this._missingTranslationStrategy = _missingTranslationStrategy;
  18831. this._console = _console;
  18832. this._contextStack = [];
  18833. this._errors = [];
  18834. }
  18835. convert(srcMsg) {
  18836. this._contextStack.length = 0;
  18837. this._errors.length = 0;
  18838. // i18n to text
  18839. const text = this._convertToText(srcMsg);
  18840. // text to html
  18841. const url = srcMsg.nodes[0].sourceSpan.start.file.url;
  18842. const html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
  18843. return {
  18844. nodes: html.rootNodes,
  18845. errors: [...this._errors, ...html.errors],
  18846. };
  18847. }
  18848. visitText(text, context) {
  18849. // `convert()` uses an `HtmlParser` to return `html.Node`s
  18850. // we should then make sure that any special characters are escaped
  18851. return escapeXml(text.value);
  18852. }
  18853. visitContainer(container, context) {
  18854. return container.children.map(n => n.visit(this)).join('');
  18855. }
  18856. visitIcu(icu, context) {
  18857. const cases = Object.keys(icu.cases).map(k => `${k} {${icu.cases[k].visit(this)}}`);
  18858. // TODO(vicb): Once all format switch to using expression placeholders
  18859. // we should throw when the placeholder is not in the source message
  18860. const exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
  18861. this._srcMsg.placeholders[icu.expression] :
  18862. icu.expression;
  18863. return `{${exp}, ${icu.type}, ${cases.join(' ')}}`;
  18864. }
  18865. visitPlaceholder(ph, context) {
  18866. const phName = this._mapper(ph.name);
  18867. if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
  18868. return this._srcMsg.placeholders[phName];
  18869. }
  18870. if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
  18871. return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
  18872. }
  18873. this._addError(ph, `Unknown placeholder "${ph.name}"`);
  18874. return '';
  18875. }
  18876. // Loaded message contains only placeholders (vs tag and icu placeholders).
  18877. // However when a translation can not be found, we need to serialize the source message
  18878. // which can contain tag placeholders
  18879. visitTagPlaceholder(ph, context) {
  18880. const tag = `${ph.tag}`;
  18881. const attrs = Object.keys(ph.attrs).map(name => `${name}="${ph.attrs[name]}"`).join(' ');
  18882. if (ph.isVoid) {
  18883. return `<${tag} ${attrs}/>`;
  18884. }
  18885. const children = ph.children.map((c) => c.visit(this)).join('');
  18886. return `<${tag} ${attrs}>${children}</${tag}>`;
  18887. }
  18888. // Loaded message contains only placeholders (vs tag and icu placeholders).
  18889. // However when a translation can not be found, we need to serialize the source message
  18890. // which can contain tag placeholders
  18891. visitIcuPlaceholder(ph, context) {
  18892. // An ICU placeholder references the source message to be serialized
  18893. return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
  18894. }
  18895. /**
  18896. * Convert a source message to a translated text string:
  18897. * - text nodes are replaced with their translation,
  18898. * - placeholders are replaced with their content,
  18899. * - ICU nodes are converted to ICU expressions.
  18900. */
  18901. _convertToText(srcMsg) {
  18902. const id = this._digest(srcMsg);
  18903. const mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
  18904. let nodes;
  18905. this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
  18906. this._srcMsg = srcMsg;
  18907. if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
  18908. // When there is a translation use its nodes as the source
  18909. // And create a mapper to convert serialized placeholder names to internal names
  18910. nodes = this._i18nNodesByMsgId[id];
  18911. this._mapper = (name) => mapper ? mapper.toInternalName(name) : name;
  18912. }
  18913. else {
  18914. // When no translation has been found
  18915. // - report an error / a warning / nothing,
  18916. // - use the nodes from the original message
  18917. // - placeholders are already internal and need no mapper
  18918. if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
  18919. const ctx = this._locale ? ` for locale "${this._locale}"` : '';
  18920. this._addError(srcMsg.nodes[0], `Missing translation for message "${id}"${ctx}`);
  18921. }
  18922. else if (this._console &&
  18923. this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
  18924. const ctx = this._locale ? ` for locale "${this._locale}"` : '';
  18925. this._console.warn(`Missing translation for message "${id}"${ctx}`);
  18926. }
  18927. nodes = srcMsg.nodes;
  18928. this._mapper = (name) => name;
  18929. }
  18930. const text = nodes.map(node => node.visit(this)).join('');
  18931. const context = this._contextStack.pop();
  18932. this._srcMsg = context.msg;
  18933. this._mapper = context.mapper;
  18934. return text;
  18935. }
  18936. _addError(el, msg) {
  18937. this._errors.push(new I18nError(el.sourceSpan, msg));
  18938. }
  18939. }
  18940. /**
  18941. * @license
  18942. * Copyright Google Inc. All Rights Reserved.
  18943. *
  18944. * Use of this source code is governed by an MIT-style license that can be
  18945. * found in the LICENSE file at https://angular.io/license
  18946. */
  18947. class I18NHtmlParser {
  18948. constructor(_htmlParser, translations, translationsFormat, missingTranslation = MissingTranslationStrategy.Warning, console) {
  18949. this._htmlParser = _htmlParser;
  18950. if (translations) {
  18951. const serializer = createSerializer(translationsFormat);
  18952. this._translationBundle =
  18953. TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
  18954. }
  18955. else {
  18956. this._translationBundle =
  18957. new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
  18958. }
  18959. }
  18960. parse(source, url, options = {}) {
  18961. const interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  18962. const parseResult = this._htmlParser.parse(source, url, Object.assign({ interpolationConfig }, options));
  18963. if (parseResult.errors.length) {
  18964. return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
  18965. }
  18966. return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
  18967. }
  18968. }
  18969. function createSerializer(format) {
  18970. format = (format || 'xlf').toLowerCase();
  18971. switch (format) {
  18972. case 'xmb':
  18973. return new Xmb();
  18974. case 'xtb':
  18975. return new Xtb();
  18976. case 'xliff2':
  18977. case 'xlf2':
  18978. return new Xliff2();
  18979. case 'xliff':
  18980. case 'xlf':
  18981. default:
  18982. return new Xliff();
  18983. }
  18984. }
  18985. /**
  18986. * @license
  18987. * Copyright Google Inc. All Rights Reserved.
  18988. *
  18989. * Use of this source code is governed by an MIT-style license that can be
  18990. * found in the LICENSE file at https://angular.io/license
  18991. */
  18992. const QUOTED_KEYS = '$quoted$';
  18993. function convertValueToOutputAst(ctx, value, type = null) {
  18994. return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
  18995. }
  18996. class _ValueOutputAstTransformer {
  18997. constructor(ctx) {
  18998. this.ctx = ctx;
  18999. }
  19000. visitArray(arr, type) {
  19001. return literalArr(arr.map(value => visitValue(value, this, null)), type);
  19002. }
  19003. visitStringMap(map, type) {
  19004. const entries = [];
  19005. const quotedSet = new Set(map && map[QUOTED_KEYS]);
  19006. Object.keys(map).forEach(key => {
  19007. entries.push(new LiteralMapEntry(key, visitValue(map[key], this, null), quotedSet.has(key)));
  19008. });
  19009. return new LiteralMapExpr(entries, type);
  19010. }
  19011. visitPrimitive(value, type) { return literal(value, type); }
  19012. visitOther(value, type) {
  19013. if (value instanceof Expression) {
  19014. return value;
  19015. }
  19016. else {
  19017. return this.ctx.importExpr(value);
  19018. }
  19019. }
  19020. }
  19021. /**
  19022. * @license
  19023. * Copyright Google Inc. All Rights Reserved.
  19024. *
  19025. * Use of this source code is governed by an MIT-style license that can be
  19026. * found in the LICENSE file at https://angular.io/license
  19027. */
  19028. function mapEntry(key, value) {
  19029. return { key, value, quoted: false };
  19030. }
  19031. class InjectableCompiler {
  19032. constructor(reflector, alwaysGenerateDef) {
  19033. this.reflector = reflector;
  19034. this.alwaysGenerateDef = alwaysGenerateDef;
  19035. this.tokenInjector = reflector.resolveExternalReference(Identifiers.Injector);
  19036. }
  19037. depsArray(deps, ctx) {
  19038. return deps.map(dep => {
  19039. let token = dep;
  19040. let args = [token];
  19041. let flags = 0 /* Default */;
  19042. if (Array.isArray(dep)) {
  19043. for (let i = 0; i < dep.length; i++) {
  19044. const v = dep[i];
  19045. if (v) {
  19046. if (v.ngMetadataName === 'Optional') {
  19047. flags |= 8 /* Optional */;
  19048. }
  19049. else if (v.ngMetadataName === 'SkipSelf') {
  19050. flags |= 4 /* SkipSelf */;
  19051. }
  19052. else if (v.ngMetadataName === 'Self') {
  19053. flags |= 2 /* Self */;
  19054. }
  19055. else if (v.ngMetadataName === 'Inject') {
  19056. token = v.token;
  19057. }
  19058. else {
  19059. token = v;
  19060. }
  19061. }
  19062. }
  19063. }
  19064. let tokenExpr;
  19065. if (typeof token === 'string') {
  19066. tokenExpr = literal(token);
  19067. }
  19068. else if (token === this.tokenInjector) {
  19069. tokenExpr = importExpr(Identifiers.INJECTOR);
  19070. }
  19071. else {
  19072. tokenExpr = ctx.importExpr(token);
  19073. }
  19074. if (flags !== 0 /* Default */) {
  19075. args = [tokenExpr, literal(flags)];
  19076. }
  19077. else {
  19078. args = [tokenExpr];
  19079. }
  19080. return importExpr(Identifiers.inject).callFn(args);
  19081. });
  19082. }
  19083. factoryFor(injectable, ctx) {
  19084. let retValue;
  19085. if (injectable.useExisting) {
  19086. retValue = importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
  19087. }
  19088. else if (injectable.useFactory) {
  19089. const deps = injectable.deps || [];
  19090. if (deps.length > 0) {
  19091. retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
  19092. }
  19093. else {
  19094. return ctx.importExpr(injectable.useFactory);
  19095. }
  19096. }
  19097. else if (injectable.useValue) {
  19098. retValue = convertValueToOutputAst(ctx, injectable.useValue);
  19099. }
  19100. else {
  19101. const clazz = injectable.useClass || injectable.symbol;
  19102. const depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
  19103. retValue = new InstantiateExpr(ctx.importExpr(clazz), depArgs);
  19104. }
  19105. return fn([], [new ReturnStatement(retValue)], undefined, undefined, injectable.symbol.name + '_Factory');
  19106. }
  19107. injectableDef(injectable, ctx) {
  19108. let providedIn = NULL_EXPR;
  19109. if (injectable.providedIn !== undefined) {
  19110. if (injectable.providedIn === null) {
  19111. providedIn = NULL_EXPR;
  19112. }
  19113. else if (typeof injectable.providedIn === 'string') {
  19114. providedIn = literal(injectable.providedIn);
  19115. }
  19116. else {
  19117. providedIn = ctx.importExpr(injectable.providedIn);
  19118. }
  19119. }
  19120. const def = [
  19121. mapEntry('factory', this.factoryFor(injectable, ctx)),
  19122. mapEntry('token', ctx.importExpr(injectable.type.reference)),
  19123. mapEntry('providedIn', providedIn),
  19124. ];
  19125. return importExpr(Identifiers.ɵɵdefineInjectable).callFn([literalMap(def)]);
  19126. }
  19127. compile(injectable, ctx) {
  19128. if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
  19129. const className = identifierName(injectable.type);
  19130. const clazz = new ClassStmt(className, null, [
  19131. new ClassField('ngInjectableDef', INFERRED_TYPE, [StmtModifier.Static], this.injectableDef(injectable, ctx)),
  19132. ], [], new ClassMethod(null, [], []), []);
  19133. ctx.statements.push(clazz);
  19134. }
  19135. }
  19136. }
  19137. /**
  19138. * @license
  19139. * Copyright Google Inc. All Rights Reserved.
  19140. *
  19141. * Use of this source code is governed by an MIT-style license that can be
  19142. * found in the LICENSE file at https://angular.io/license
  19143. */
  19144. const STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
  19145. const GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
  19146. const JIT_SUMMARY_FILE = /\.ngsummary\./;
  19147. const JIT_SUMMARY_NAME = /NgSummary$/;
  19148. function ngfactoryFilePath(filePath, forceSourceFile = false) {
  19149. const urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
  19150. return `${urlWithSuffix[0]}.ngfactory${normalizeGenFileSuffix(urlWithSuffix[1])}`;
  19151. }
  19152. function stripGeneratedFileSuffix(filePath) {
  19153. return filePath.replace(GENERATED_FILE, '.');
  19154. }
  19155. function isGeneratedFile(filePath) {
  19156. return GENERATED_FILE.test(filePath);
  19157. }
  19158. function splitTypescriptSuffix(path, forceSourceFile = false) {
  19159. if (path.endsWith('.d.ts')) {
  19160. return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
  19161. }
  19162. const lastDot = path.lastIndexOf('.');
  19163. if (lastDot !== -1) {
  19164. return [path.substring(0, lastDot), path.substring(lastDot)];
  19165. }
  19166. return [path, ''];
  19167. }
  19168. function normalizeGenFileSuffix(srcFileSuffix) {
  19169. return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
  19170. }
  19171. function summaryFileName(fileName) {
  19172. const fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
  19173. return `${fileNameWithoutSuffix}.ngsummary.json`;
  19174. }
  19175. function summaryForJitFileName(fileName, forceSourceFile = false) {
  19176. const urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
  19177. return `${urlWithSuffix[0]}.ngsummary${urlWithSuffix[1]}`;
  19178. }
  19179. function stripSummaryForJitFileSuffix(filePath) {
  19180. return filePath.replace(JIT_SUMMARY_FILE, '.');
  19181. }
  19182. function summaryForJitName(symbolName) {
  19183. return `${symbolName}NgSummary`;
  19184. }
  19185. function stripSummaryForJitNameSuffix(symbolName) {
  19186. return symbolName.replace(JIT_SUMMARY_NAME, '');
  19187. }
  19188. const LOWERED_SYMBOL = /\u0275\d+/;
  19189. function isLoweredSymbol(name) {
  19190. return LOWERED_SYMBOL.test(name);
  19191. }
  19192. function createLoweredSymbol(id) {
  19193. return `\u0275${id}`;
  19194. }
  19195. /**
  19196. * @license
  19197. * Copyright Google Inc. All Rights Reserved.
  19198. *
  19199. * Use of this source code is governed by an MIT-style license that can be
  19200. * found in the LICENSE file at https://angular.io/license
  19201. */
  19202. var LifecycleHooks;
  19203. (function (LifecycleHooks) {
  19204. LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
  19205. LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
  19206. LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
  19207. LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
  19208. LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
  19209. LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
  19210. LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
  19211. LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
  19212. })(LifecycleHooks || (LifecycleHooks = {}));
  19213. const LIFECYCLE_HOOKS_VALUES = [
  19214. LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
  19215. LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
  19216. LifecycleHooks.AfterViewChecked
  19217. ];
  19218. function hasLifecycleHook(reflector, hook, token) {
  19219. return reflector.hasLifecycleHook(token, getHookName(hook));
  19220. }
  19221. function getAllLifecycleHooks(reflector, token) {
  19222. return LIFECYCLE_HOOKS_VALUES.filter(hook => hasLifecycleHook(reflector, hook, token));
  19223. }
  19224. function getHookName(hook) {
  19225. switch (hook) {
  19226. case LifecycleHooks.OnInit:
  19227. return 'ngOnInit';
  19228. case LifecycleHooks.OnDestroy:
  19229. return 'ngOnDestroy';
  19230. case LifecycleHooks.DoCheck:
  19231. return 'ngDoCheck';
  19232. case LifecycleHooks.OnChanges:
  19233. return 'ngOnChanges';
  19234. case LifecycleHooks.AfterContentInit:
  19235. return 'ngAfterContentInit';
  19236. case LifecycleHooks.AfterContentChecked:
  19237. return 'ngAfterContentChecked';
  19238. case LifecycleHooks.AfterViewInit:
  19239. return 'ngAfterViewInit';
  19240. case LifecycleHooks.AfterViewChecked:
  19241. return 'ngAfterViewChecked';
  19242. default:
  19243. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  19244. // However Closure Compiler does not understand that and reports an error in typed mode.
  19245. // The `throw new Error` below works around the problem, and the unexpected: never variable
  19246. // makes sure tsc still checks this code is unreachable.
  19247. const unexpected = hook;
  19248. throw new Error(`unexpected ${unexpected}`);
  19249. }
  19250. }
  19251. /**
  19252. * @license
  19253. * Copyright Google Inc. All Rights Reserved.
  19254. *
  19255. * Use of this source code is governed by an MIT-style license that can be
  19256. * found in the LICENSE file at https://angular.io/license
  19257. */
  19258. const ERROR_COMPONENT_TYPE = 'ngComponentType';
  19259. // Design notes:
  19260. // - don't lazily create metadata:
  19261. // For some metadata, we need to do async work sometimes,
  19262. // so the user has to kick off this loading.
  19263. // But we want to report errors even when the async work is
  19264. // not required to check that the user would have been able
  19265. // to wait correctly.
  19266. class CompileMetadataResolver {
  19267. constructor(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
  19268. this._config = _config;
  19269. this._htmlParser = _htmlParser;
  19270. this._ngModuleResolver = _ngModuleResolver;
  19271. this._directiveResolver = _directiveResolver;
  19272. this._pipeResolver = _pipeResolver;
  19273. this._summaryResolver = _summaryResolver;
  19274. this._schemaRegistry = _schemaRegistry;
  19275. this._directiveNormalizer = _directiveNormalizer;
  19276. this._console = _console;
  19277. this._staticSymbolCache = _staticSymbolCache;
  19278. this._reflector = _reflector;
  19279. this._errorCollector = _errorCollector;
  19280. this._nonNormalizedDirectiveCache = new Map();
  19281. this._directiveCache = new Map();
  19282. this._summaryCache = new Map();
  19283. this._pipeCache = new Map();
  19284. this._ngModuleCache = new Map();
  19285. this._ngModuleOfTypes = new Map();
  19286. this._shallowModuleCache = new Map();
  19287. }
  19288. getReflector() { return this._reflector; }
  19289. clearCacheFor(type) {
  19290. const dirMeta = this._directiveCache.get(type);
  19291. this._directiveCache.delete(type);
  19292. this._nonNormalizedDirectiveCache.delete(type);
  19293. this._summaryCache.delete(type);
  19294. this._pipeCache.delete(type);
  19295. this._ngModuleOfTypes.delete(type);
  19296. // Clear all of the NgModule as they contain transitive information!
  19297. this._ngModuleCache.clear();
  19298. if (dirMeta) {
  19299. this._directiveNormalizer.clearCacheFor(dirMeta);
  19300. }
  19301. }
  19302. clearCache() {
  19303. this._directiveCache.clear();
  19304. this._nonNormalizedDirectiveCache.clear();
  19305. this._summaryCache.clear();
  19306. this._pipeCache.clear();
  19307. this._ngModuleCache.clear();
  19308. this._ngModuleOfTypes.clear();
  19309. this._directiveNormalizer.clearCache();
  19310. }
  19311. _createProxyClass(baseType, name) {
  19312. let delegate = null;
  19313. const proxyClass = function () {
  19314. if (!delegate) {
  19315. throw new Error(`Illegal state: Class ${name} for type ${stringify(baseType)} is not compiled yet!`);
  19316. }
  19317. return delegate.apply(this, arguments);
  19318. };
  19319. proxyClass.setDelegate = (d) => {
  19320. delegate = d;
  19321. proxyClass.prototype = d.prototype;
  19322. };
  19323. // Make stringify work correctly
  19324. proxyClass.overriddenName = name;
  19325. return proxyClass;
  19326. }
  19327. getGeneratedClass(dirType, name) {
  19328. if (dirType instanceof StaticSymbol) {
  19329. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
  19330. }
  19331. else {
  19332. return this._createProxyClass(dirType, name);
  19333. }
  19334. }
  19335. getComponentViewClass(dirType) {
  19336. return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
  19337. }
  19338. getHostComponentViewClass(dirType) {
  19339. return this.getGeneratedClass(dirType, hostViewClassName(dirType));
  19340. }
  19341. getHostComponentType(dirType) {
  19342. const name = `${identifierName({ reference: dirType })}_Host`;
  19343. if (dirType instanceof StaticSymbol) {
  19344. return this._staticSymbolCache.get(dirType.filePath, name);
  19345. }
  19346. return this._createProxyClass(dirType, name);
  19347. }
  19348. getRendererType(dirType) {
  19349. if (dirType instanceof StaticSymbol) {
  19350. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
  19351. }
  19352. else {
  19353. // returning an object as proxy,
  19354. // that we fill later during runtime compilation.
  19355. return {};
  19356. }
  19357. }
  19358. getComponentFactory(selector, dirType, inputs, outputs) {
  19359. if (dirType instanceof StaticSymbol) {
  19360. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
  19361. }
  19362. else {
  19363. const hostView = this.getHostComponentViewClass(dirType);
  19364. // Note: ngContentSelectors will be filled later once the template is
  19365. // loaded.
  19366. const createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
  19367. return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
  19368. }
  19369. }
  19370. initComponentFactory(factory, ngContentSelectors) {
  19371. if (!(factory instanceof StaticSymbol)) {
  19372. factory.ngContentSelectors.push(...ngContentSelectors);
  19373. }
  19374. }
  19375. _loadSummary(type, kind) {
  19376. let typeSummary = this._summaryCache.get(type);
  19377. if (!typeSummary) {
  19378. const summary = this._summaryResolver.resolveSummary(type);
  19379. typeSummary = summary ? summary.type : null;
  19380. this._summaryCache.set(type, typeSummary || null);
  19381. }
  19382. return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
  19383. }
  19384. getHostComponentMetadata(compMeta, hostViewType) {
  19385. const hostType = this.getHostComponentType(compMeta.type.reference);
  19386. if (!hostViewType) {
  19387. hostViewType = this.getHostComponentViewClass(hostType);
  19388. }
  19389. // Note: ! is ok here as this method should only be called with normalized directive
  19390. // metadata, which always fills in the selector.
  19391. const template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
  19392. const templateUrl = '';
  19393. const htmlAst = this._htmlParser.parse(template, templateUrl);
  19394. return CompileDirectiveMetadata.create({
  19395. isHost: true,
  19396. type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
  19397. template: new CompileTemplateMetadata({
  19398. encapsulation: ViewEncapsulation.None,
  19399. template,
  19400. templateUrl,
  19401. htmlAst,
  19402. styles: [],
  19403. styleUrls: [],
  19404. ngContentSelectors: [],
  19405. animations: [],
  19406. isInline: true,
  19407. externalStylesheets: [],
  19408. interpolation: null,
  19409. preserveWhitespaces: false,
  19410. }),
  19411. exportAs: null,
  19412. changeDetection: ChangeDetectionStrategy.Default,
  19413. inputs: [],
  19414. outputs: [],
  19415. host: {},
  19416. isComponent: true,
  19417. selector: '*',
  19418. providers: [],
  19419. viewProviders: [],
  19420. queries: [],
  19421. guards: {},
  19422. viewQueries: [],
  19423. componentViewType: hostViewType,
  19424. rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
  19425. entryComponents: [],
  19426. componentFactory: null
  19427. });
  19428. }
  19429. loadDirectiveMetadata(ngModuleType, directiveType, isSync) {
  19430. if (this._directiveCache.has(directiveType)) {
  19431. return null;
  19432. }
  19433. directiveType = resolveForwardRef(directiveType);
  19434. const { annotation, metadata } = this.getNonNormalizedDirectiveMetadata(directiveType);
  19435. const createDirectiveMetadata = (templateMetadata) => {
  19436. const normalizedDirMeta = new CompileDirectiveMetadata({
  19437. isHost: false,
  19438. type: metadata.type,
  19439. isComponent: metadata.isComponent,
  19440. selector: metadata.selector,
  19441. exportAs: metadata.exportAs,
  19442. changeDetection: metadata.changeDetection,
  19443. inputs: metadata.inputs,
  19444. outputs: metadata.outputs,
  19445. hostListeners: metadata.hostListeners,
  19446. hostProperties: metadata.hostProperties,
  19447. hostAttributes: metadata.hostAttributes,
  19448. providers: metadata.providers,
  19449. viewProviders: metadata.viewProviders,
  19450. queries: metadata.queries,
  19451. guards: metadata.guards,
  19452. viewQueries: metadata.viewQueries,
  19453. entryComponents: metadata.entryComponents,
  19454. componentViewType: metadata.componentViewType,
  19455. rendererType: metadata.rendererType,
  19456. componentFactory: metadata.componentFactory,
  19457. template: templateMetadata
  19458. });
  19459. if (templateMetadata) {
  19460. this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
  19461. }
  19462. this._directiveCache.set(directiveType, normalizedDirMeta);
  19463. this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
  19464. return null;
  19465. };
  19466. if (metadata.isComponent) {
  19467. const template = metadata.template;
  19468. const templateMeta = this._directiveNormalizer.normalizeTemplate({
  19469. ngModuleType,
  19470. componentType: directiveType,
  19471. moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
  19472. encapsulation: template.encapsulation,
  19473. template: template.template,
  19474. templateUrl: template.templateUrl,
  19475. styles: template.styles,
  19476. styleUrls: template.styleUrls,
  19477. animations: template.animations,
  19478. interpolation: template.interpolation,
  19479. preserveWhitespaces: template.preserveWhitespaces
  19480. });
  19481. if (isPromise(templateMeta) && isSync) {
  19482. this._reportError(componentStillLoadingError(directiveType), directiveType);
  19483. return null;
  19484. }
  19485. return SyncAsync.then(templateMeta, createDirectiveMetadata);
  19486. }
  19487. else {
  19488. // directive
  19489. createDirectiveMetadata(null);
  19490. return null;
  19491. }
  19492. }
  19493. getNonNormalizedDirectiveMetadata(directiveType) {
  19494. directiveType = resolveForwardRef(directiveType);
  19495. if (!directiveType) {
  19496. return null;
  19497. }
  19498. let cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
  19499. if (cacheEntry) {
  19500. return cacheEntry;
  19501. }
  19502. const dirMeta = this._directiveResolver.resolve(directiveType, false);
  19503. if (!dirMeta) {
  19504. return null;
  19505. }
  19506. let nonNormalizedTemplateMetadata = undefined;
  19507. if (createComponent.isTypeOf(dirMeta)) {
  19508. // component
  19509. const compMeta = dirMeta;
  19510. assertArrayOfStrings('styles', compMeta.styles);
  19511. assertArrayOfStrings('styleUrls', compMeta.styleUrls);
  19512. assertInterpolationSymbols('interpolation', compMeta.interpolation);
  19513. const animations = compMeta.animations;
  19514. nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
  19515. encapsulation: noUndefined(compMeta.encapsulation),
  19516. template: noUndefined(compMeta.template),
  19517. templateUrl: noUndefined(compMeta.templateUrl),
  19518. htmlAst: null,
  19519. styles: compMeta.styles || [],
  19520. styleUrls: compMeta.styleUrls || [],
  19521. animations: animations || [],
  19522. interpolation: noUndefined(compMeta.interpolation),
  19523. isInline: !!compMeta.template,
  19524. externalStylesheets: [],
  19525. ngContentSelectors: [],
  19526. preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
  19527. });
  19528. }
  19529. let changeDetectionStrategy = null;
  19530. let viewProviders = [];
  19531. let entryComponentMetadata = [];
  19532. let selector = dirMeta.selector;
  19533. if (createComponent.isTypeOf(dirMeta)) {
  19534. // Component
  19535. const compMeta = dirMeta;
  19536. changeDetectionStrategy = compMeta.changeDetection;
  19537. if (compMeta.viewProviders) {
  19538. viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, `viewProviders for "${stringifyType(directiveType)}"`, [], directiveType);
  19539. }
  19540. if (compMeta.entryComponents) {
  19541. entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
  19542. .map((type) => this._getEntryComponentMetadata(type))
  19543. .concat(entryComponentMetadata);
  19544. }
  19545. if (!selector) {
  19546. selector = this._schemaRegistry.getDefaultComponentElementName();
  19547. }
  19548. }
  19549. else {
  19550. // Directive
  19551. if (!selector) {
  19552. this._reportError(syntaxError(`Directive ${stringifyType(directiveType)} has no selector, please add it!`), directiveType);
  19553. selector = 'error';
  19554. }
  19555. }
  19556. let providers = [];
  19557. if (dirMeta.providers != null) {
  19558. providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, `providers for "${stringifyType(directiveType)}"`, [], directiveType);
  19559. }
  19560. let queries = [];
  19561. let viewQueries = [];
  19562. if (dirMeta.queries != null) {
  19563. queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
  19564. viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
  19565. }
  19566. const metadata = CompileDirectiveMetadata.create({
  19567. isHost: false,
  19568. selector: selector,
  19569. exportAs: noUndefined(dirMeta.exportAs),
  19570. isComponent: !!nonNormalizedTemplateMetadata,
  19571. type: this._getTypeMetadata(directiveType),
  19572. template: nonNormalizedTemplateMetadata,
  19573. changeDetection: changeDetectionStrategy,
  19574. inputs: dirMeta.inputs || [],
  19575. outputs: dirMeta.outputs || [],
  19576. host: dirMeta.host || {},
  19577. providers: providers || [],
  19578. viewProviders: viewProviders || [],
  19579. queries: queries || [],
  19580. guards: dirMeta.guards || {},
  19581. viewQueries: viewQueries || [],
  19582. entryComponents: entryComponentMetadata,
  19583. componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
  19584. null,
  19585. rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
  19586. componentFactory: null
  19587. });
  19588. if (nonNormalizedTemplateMetadata) {
  19589. metadata.componentFactory =
  19590. this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
  19591. }
  19592. cacheEntry = { metadata, annotation: dirMeta };
  19593. this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
  19594. return cacheEntry;
  19595. }
  19596. /**
  19597. * Gets the metadata for the given directive.
  19598. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  19599. */
  19600. getDirectiveMetadata(directiveType) {
  19601. const dirMeta = this._directiveCache.get(directiveType);
  19602. if (!dirMeta) {
  19603. this._reportError(syntaxError(`Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive ${stringifyType(directiveType)}.`), directiveType);
  19604. }
  19605. return dirMeta;
  19606. }
  19607. getDirectiveSummary(dirType) {
  19608. const dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
  19609. if (!dirSummary) {
  19610. this._reportError(syntaxError(`Illegal state: Could not load the summary for directive ${stringifyType(dirType)}.`), dirType);
  19611. }
  19612. return dirSummary;
  19613. }
  19614. isDirective(type) {
  19615. return !!this._loadSummary(type, CompileSummaryKind.Directive) ||
  19616. this._directiveResolver.isDirective(type);
  19617. }
  19618. isPipe(type) {
  19619. return !!this._loadSummary(type, CompileSummaryKind.Pipe) ||
  19620. this._pipeResolver.isPipe(type);
  19621. }
  19622. isNgModule(type) {
  19623. return !!this._loadSummary(type, CompileSummaryKind.NgModule) ||
  19624. this._ngModuleResolver.isNgModule(type);
  19625. }
  19626. getNgModuleSummary(moduleType, alreadyCollecting = null) {
  19627. let moduleSummary = this._loadSummary(moduleType, CompileSummaryKind.NgModule);
  19628. if (!moduleSummary) {
  19629. const moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
  19630. moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
  19631. if (moduleSummary) {
  19632. this._summaryCache.set(moduleType, moduleSummary);
  19633. }
  19634. }
  19635. return moduleSummary;
  19636. }
  19637. /**
  19638. * Loads the declared directives and pipes of an NgModule.
  19639. */
  19640. loadNgModuleDirectiveAndPipeMetadata(moduleType, isSync, throwIfNotFound = true) {
  19641. const ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
  19642. const loading = [];
  19643. if (ngModule) {
  19644. ngModule.declaredDirectives.forEach((id) => {
  19645. const promise = this.loadDirectiveMetadata(moduleType, id.reference, isSync);
  19646. if (promise) {
  19647. loading.push(promise);
  19648. }
  19649. });
  19650. ngModule.declaredPipes.forEach((id) => this._loadPipeMetadata(id.reference));
  19651. }
  19652. return Promise.all(loading);
  19653. }
  19654. getShallowModuleMetadata(moduleType) {
  19655. let compileMeta = this._shallowModuleCache.get(moduleType);
  19656. if (compileMeta) {
  19657. return compileMeta;
  19658. }
  19659. const ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
  19660. compileMeta = {
  19661. type: this._getTypeMetadata(moduleType),
  19662. rawExports: ngModuleMeta.exports,
  19663. rawImports: ngModuleMeta.imports,
  19664. rawProviders: ngModuleMeta.providers,
  19665. };
  19666. this._shallowModuleCache.set(moduleType, compileMeta);
  19667. return compileMeta;
  19668. }
  19669. getNgModuleMetadata(moduleType, throwIfNotFound = true, alreadyCollecting = null) {
  19670. moduleType = resolveForwardRef(moduleType);
  19671. let compileMeta = this._ngModuleCache.get(moduleType);
  19672. if (compileMeta) {
  19673. return compileMeta;
  19674. }
  19675. const meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
  19676. if (!meta) {
  19677. return null;
  19678. }
  19679. const declaredDirectives = [];
  19680. const exportedNonModuleIdentifiers = [];
  19681. const declaredPipes = [];
  19682. const importedModules = [];
  19683. const exportedModules = [];
  19684. const providers = [];
  19685. const entryComponents = [];
  19686. const bootstrapComponents = [];
  19687. const schemas = [];
  19688. if (meta.imports) {
  19689. flattenAndDedupeArray(meta.imports).forEach((importedType) => {
  19690. let importedModuleType = undefined;
  19691. if (isValidType(importedType)) {
  19692. importedModuleType = importedType;
  19693. }
  19694. else if (importedType && importedType.ngModule) {
  19695. const moduleWithProviders = importedType;
  19696. importedModuleType = moduleWithProviders.ngModule;
  19697. if (moduleWithProviders.providers) {
  19698. providers.push(...this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, `provider for the NgModule '${stringifyType(importedModuleType)}'`, [], importedType));
  19699. }
  19700. }
  19701. if (importedModuleType) {
  19702. if (this._checkSelfImport(moduleType, importedModuleType))
  19703. return;
  19704. if (!alreadyCollecting)
  19705. alreadyCollecting = new Set();
  19706. if (alreadyCollecting.has(importedModuleType)) {
  19707. this._reportError(syntaxError(`${this._getTypeDescriptor(importedModuleType)} '${stringifyType(importedType)}' is imported recursively by the module '${stringifyType(moduleType)}'.`), moduleType);
  19708. return;
  19709. }
  19710. alreadyCollecting.add(importedModuleType);
  19711. const importedModuleSummary = this.getNgModuleSummary(importedModuleType, alreadyCollecting);
  19712. alreadyCollecting.delete(importedModuleType);
  19713. if (!importedModuleSummary) {
  19714. this._reportError(syntaxError(`Unexpected ${this._getTypeDescriptor(importedType)} '${stringifyType(importedType)}' imported by the module '${stringifyType(moduleType)}'. Please add a @NgModule annotation.`), moduleType);
  19715. return;
  19716. }
  19717. importedModules.push(importedModuleSummary);
  19718. }
  19719. else {
  19720. this._reportError(syntaxError(`Unexpected value '${stringifyType(importedType)}' imported by the module '${stringifyType(moduleType)}'`), moduleType);
  19721. return;
  19722. }
  19723. });
  19724. }
  19725. if (meta.exports) {
  19726. flattenAndDedupeArray(meta.exports).forEach((exportedType) => {
  19727. if (!isValidType(exportedType)) {
  19728. this._reportError(syntaxError(`Unexpected value '${stringifyType(exportedType)}' exported by the module '${stringifyType(moduleType)}'`), moduleType);
  19729. return;
  19730. }
  19731. if (!alreadyCollecting)
  19732. alreadyCollecting = new Set();
  19733. if (alreadyCollecting.has(exportedType)) {
  19734. this._reportError(syntaxError(`${this._getTypeDescriptor(exportedType)} '${stringify(exportedType)}' is exported recursively by the module '${stringifyType(moduleType)}'`), moduleType);
  19735. return;
  19736. }
  19737. alreadyCollecting.add(exportedType);
  19738. const exportedModuleSummary = this.getNgModuleSummary(exportedType, alreadyCollecting);
  19739. alreadyCollecting.delete(exportedType);
  19740. if (exportedModuleSummary) {
  19741. exportedModules.push(exportedModuleSummary);
  19742. }
  19743. else {
  19744. exportedNonModuleIdentifiers.push(this._getIdentifierMetadata(exportedType));
  19745. }
  19746. });
  19747. }
  19748. // Note: This will be modified later, so we rely on
  19749. // getting a new instance every time!
  19750. const transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
  19751. if (meta.declarations) {
  19752. flattenAndDedupeArray(meta.declarations).forEach((declaredType) => {
  19753. if (!isValidType(declaredType)) {
  19754. this._reportError(syntaxError(`Unexpected value '${stringifyType(declaredType)}' declared by the module '${stringifyType(moduleType)}'`), moduleType);
  19755. return;
  19756. }
  19757. const declaredIdentifier = this._getIdentifierMetadata(declaredType);
  19758. if (this.isDirective(declaredType)) {
  19759. transitiveModule.addDirective(declaredIdentifier);
  19760. declaredDirectives.push(declaredIdentifier);
  19761. this._addTypeToModule(declaredType, moduleType);
  19762. }
  19763. else if (this.isPipe(declaredType)) {
  19764. transitiveModule.addPipe(declaredIdentifier);
  19765. transitiveModule.pipes.push(declaredIdentifier);
  19766. declaredPipes.push(declaredIdentifier);
  19767. this._addTypeToModule(declaredType, moduleType);
  19768. }
  19769. else {
  19770. this._reportError(syntaxError(`Unexpected ${this._getTypeDescriptor(declaredType)} '${stringifyType(declaredType)}' declared by the module '${stringifyType(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`), moduleType);
  19771. return;
  19772. }
  19773. });
  19774. }
  19775. const exportedDirectives = [];
  19776. const exportedPipes = [];
  19777. exportedNonModuleIdentifiers.forEach((exportedId) => {
  19778. if (transitiveModule.directivesSet.has(exportedId.reference)) {
  19779. exportedDirectives.push(exportedId);
  19780. transitiveModule.addExportedDirective(exportedId);
  19781. }
  19782. else if (transitiveModule.pipesSet.has(exportedId.reference)) {
  19783. exportedPipes.push(exportedId);
  19784. transitiveModule.addExportedPipe(exportedId);
  19785. }
  19786. else {
  19787. this._reportError(syntaxError(`Can't export ${this._getTypeDescriptor(exportedId.reference)} ${stringifyType(exportedId.reference)} from ${stringifyType(moduleType)} as it was neither declared nor imported!`), moduleType);
  19788. return;
  19789. }
  19790. });
  19791. // The providers of the module have to go last
  19792. // so that they overwrite any other provider we already added.
  19793. if (meta.providers) {
  19794. providers.push(...this._getProvidersMetadata(meta.providers, entryComponents, `provider for the NgModule '${stringifyType(moduleType)}'`, [], moduleType));
  19795. }
  19796. if (meta.entryComponents) {
  19797. entryComponents.push(...flattenAndDedupeArray(meta.entryComponents)
  19798. .map(type => this._getEntryComponentMetadata(type)));
  19799. }
  19800. if (meta.bootstrap) {
  19801. flattenAndDedupeArray(meta.bootstrap).forEach(type => {
  19802. if (!isValidType(type)) {
  19803. this._reportError(syntaxError(`Unexpected value '${stringifyType(type)}' used in the bootstrap property of module '${stringifyType(moduleType)}'`), moduleType);
  19804. return;
  19805. }
  19806. bootstrapComponents.push(this._getIdentifierMetadata(type));
  19807. });
  19808. }
  19809. entryComponents.push(...bootstrapComponents.map(type => this._getEntryComponentMetadata(type.reference)));
  19810. if (meta.schemas) {
  19811. schemas.push(...flattenAndDedupeArray(meta.schemas));
  19812. }
  19813. compileMeta = new CompileNgModuleMetadata({
  19814. type: this._getTypeMetadata(moduleType),
  19815. providers,
  19816. entryComponents,
  19817. bootstrapComponents,
  19818. schemas,
  19819. declaredDirectives,
  19820. exportedDirectives,
  19821. declaredPipes,
  19822. exportedPipes,
  19823. importedModules,
  19824. exportedModules,
  19825. transitiveModule,
  19826. id: meta.id || null,
  19827. });
  19828. entryComponents.forEach((id) => transitiveModule.addEntryComponent(id));
  19829. providers.forEach((provider) => transitiveModule.addProvider(provider, compileMeta.type));
  19830. transitiveModule.addModule(compileMeta.type);
  19831. this._ngModuleCache.set(moduleType, compileMeta);
  19832. return compileMeta;
  19833. }
  19834. _checkSelfImport(moduleType, importedModuleType) {
  19835. if (moduleType === importedModuleType) {
  19836. this._reportError(syntaxError(`'${stringifyType(moduleType)}' module can't import itself`), moduleType);
  19837. return true;
  19838. }
  19839. return false;
  19840. }
  19841. _getTypeDescriptor(type) {
  19842. if (isValidType(type)) {
  19843. if (this.isDirective(type)) {
  19844. return 'directive';
  19845. }
  19846. if (this.isPipe(type)) {
  19847. return 'pipe';
  19848. }
  19849. if (this.isNgModule(type)) {
  19850. return 'module';
  19851. }
  19852. }
  19853. if (type.provide) {
  19854. return 'provider';
  19855. }
  19856. return 'value';
  19857. }
  19858. _addTypeToModule(type, moduleType) {
  19859. const oldModule = this._ngModuleOfTypes.get(type);
  19860. if (oldModule && oldModule !== moduleType) {
  19861. this._reportError(syntaxError(`Type ${stringifyType(type)} is part of the declarations of 2 modules: ${stringifyType(oldModule)} and ${stringifyType(moduleType)}! ` +
  19862. `Please consider moving ${stringifyType(type)} to a higher module that imports ${stringifyType(oldModule)} and ${stringifyType(moduleType)}. ` +
  19863. `You can also create a new NgModule that exports and includes ${stringifyType(type)} then import that NgModule in ${stringifyType(oldModule)} and ${stringifyType(moduleType)}.`), moduleType);
  19864. return;
  19865. }
  19866. this._ngModuleOfTypes.set(type, moduleType);
  19867. }
  19868. _getTransitiveNgModuleMetadata(importedModules, exportedModules) {
  19869. // collect `providers` / `entryComponents` from all imported and all exported modules
  19870. const result = new TransitiveCompileNgModuleMetadata();
  19871. const modulesByToken = new Map();
  19872. importedModules.concat(exportedModules).forEach((modSummary) => {
  19873. modSummary.modules.forEach((mod) => result.addModule(mod));
  19874. modSummary.entryComponents.forEach((comp) => result.addEntryComponent(comp));
  19875. const addedTokens = new Set();
  19876. modSummary.providers.forEach((entry) => {
  19877. const tokenRef = tokenReference(entry.provider.token);
  19878. let prevModules = modulesByToken.get(tokenRef);
  19879. if (!prevModules) {
  19880. prevModules = new Set();
  19881. modulesByToken.set(tokenRef, prevModules);
  19882. }
  19883. const moduleRef = entry.module.reference;
  19884. // Note: the providers of one module may still contain multiple providers
  19885. // per token (e.g. for multi providers), and we need to preserve these.
  19886. if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
  19887. prevModules.add(moduleRef);
  19888. addedTokens.add(tokenRef);
  19889. result.addProvider(entry.provider, entry.module);
  19890. }
  19891. });
  19892. });
  19893. exportedModules.forEach((modSummary) => {
  19894. modSummary.exportedDirectives.forEach((id) => result.addExportedDirective(id));
  19895. modSummary.exportedPipes.forEach((id) => result.addExportedPipe(id));
  19896. });
  19897. importedModules.forEach((modSummary) => {
  19898. modSummary.exportedDirectives.forEach((id) => result.addDirective(id));
  19899. modSummary.exportedPipes.forEach((id) => result.addPipe(id));
  19900. });
  19901. return result;
  19902. }
  19903. _getIdentifierMetadata(type) {
  19904. type = resolveForwardRef(type);
  19905. return { reference: type };
  19906. }
  19907. isInjectable(type) {
  19908. const annotations = this._reflector.tryAnnotations(type);
  19909. return annotations.some(ann => createInjectable.isTypeOf(ann));
  19910. }
  19911. getInjectableSummary(type) {
  19912. return {
  19913. summaryKind: CompileSummaryKind.Injectable,
  19914. type: this._getTypeMetadata(type, null, false)
  19915. };
  19916. }
  19917. getInjectableMetadata(type, dependencies = null, throwOnUnknownDeps = true) {
  19918. const typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
  19919. const typeMetadata = typeSummary ?
  19920. typeSummary.type :
  19921. this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
  19922. const annotations = this._reflector.annotations(type).filter(ann => createInjectable.isTypeOf(ann));
  19923. if (annotations.length === 0) {
  19924. return null;
  19925. }
  19926. const meta = annotations[annotations.length - 1];
  19927. return {
  19928. symbol: type,
  19929. type: typeMetadata,
  19930. providedIn: meta.providedIn,
  19931. useValue: meta.useValue,
  19932. useClass: meta.useClass,
  19933. useExisting: meta.useExisting,
  19934. useFactory: meta.useFactory,
  19935. deps: meta.deps,
  19936. };
  19937. }
  19938. _getTypeMetadata(type, dependencies = null, throwOnUnknownDeps = true) {
  19939. const identifier = this._getIdentifierMetadata(type);
  19940. return {
  19941. reference: identifier.reference,
  19942. diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
  19943. lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
  19944. };
  19945. }
  19946. _getFactoryMetadata(factory, dependencies = null) {
  19947. factory = resolveForwardRef(factory);
  19948. return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
  19949. }
  19950. /**
  19951. * Gets the metadata for the given pipe.
  19952. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  19953. */
  19954. getPipeMetadata(pipeType) {
  19955. const pipeMeta = this._pipeCache.get(pipeType);
  19956. if (!pipeMeta) {
  19957. this._reportError(syntaxError(`Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe ${stringifyType(pipeType)}.`), pipeType);
  19958. }
  19959. return pipeMeta || null;
  19960. }
  19961. getPipeSummary(pipeType) {
  19962. const pipeSummary = this._loadSummary(pipeType, CompileSummaryKind.Pipe);
  19963. if (!pipeSummary) {
  19964. this._reportError(syntaxError(`Illegal state: Could not load the summary for pipe ${stringifyType(pipeType)}.`), pipeType);
  19965. }
  19966. return pipeSummary;
  19967. }
  19968. getOrLoadPipeMetadata(pipeType) {
  19969. let pipeMeta = this._pipeCache.get(pipeType);
  19970. if (!pipeMeta) {
  19971. pipeMeta = this._loadPipeMetadata(pipeType);
  19972. }
  19973. return pipeMeta;
  19974. }
  19975. _loadPipeMetadata(pipeType) {
  19976. pipeType = resolveForwardRef(pipeType);
  19977. const pipeAnnotation = this._pipeResolver.resolve(pipeType);
  19978. const pipeMeta = new CompilePipeMetadata({
  19979. type: this._getTypeMetadata(pipeType),
  19980. name: pipeAnnotation.name,
  19981. pure: !!pipeAnnotation.pure
  19982. });
  19983. this._pipeCache.set(pipeType, pipeMeta);
  19984. this._summaryCache.set(pipeType, pipeMeta.toSummary());
  19985. return pipeMeta;
  19986. }
  19987. _getDependenciesMetadata(typeOrFunc, dependencies, throwOnUnknownDeps = true) {
  19988. let hasUnknownDeps = false;
  19989. const params = dependencies || this._reflector.parameters(typeOrFunc) || [];
  19990. const dependenciesMetadata = params.map((param) => {
  19991. let isAttribute = false;
  19992. let isHost = false;
  19993. let isSelf = false;
  19994. let isSkipSelf = false;
  19995. let isOptional = false;
  19996. let token = null;
  19997. if (Array.isArray(param)) {
  19998. param.forEach((paramEntry) => {
  19999. if (createHost.isTypeOf(paramEntry)) {
  20000. isHost = true;
  20001. }
  20002. else if (createSelf.isTypeOf(paramEntry)) {
  20003. isSelf = true;
  20004. }
  20005. else if (createSkipSelf.isTypeOf(paramEntry)) {
  20006. isSkipSelf = true;
  20007. }
  20008. else if (createOptional.isTypeOf(paramEntry)) {
  20009. isOptional = true;
  20010. }
  20011. else if (createAttribute.isTypeOf(paramEntry)) {
  20012. isAttribute = true;
  20013. token = paramEntry.attributeName;
  20014. }
  20015. else if (createInject.isTypeOf(paramEntry)) {
  20016. token = paramEntry.token;
  20017. }
  20018. else if (createInjectionToken.isTypeOf(paramEntry) ||
  20019. paramEntry instanceof StaticSymbol) {
  20020. token = paramEntry;
  20021. }
  20022. else if (isValidType(paramEntry) && token == null) {
  20023. token = paramEntry;
  20024. }
  20025. });
  20026. }
  20027. else {
  20028. token = param;
  20029. }
  20030. if (token == null) {
  20031. hasUnknownDeps = true;
  20032. return {};
  20033. }
  20034. return {
  20035. isAttribute,
  20036. isHost,
  20037. isSelf,
  20038. isSkipSelf,
  20039. isOptional,
  20040. token: this._getTokenMetadata(token)
  20041. };
  20042. });
  20043. if (hasUnknownDeps) {
  20044. const depsTokens = dependenciesMetadata.map((dep) => dep.token ? stringifyType(dep.token) : '?').join(', ');
  20045. const message = `Can't resolve all parameters for ${stringifyType(typeOrFunc)}: (${depsTokens}).`;
  20046. if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
  20047. this._reportError(syntaxError(message), typeOrFunc);
  20048. }
  20049. else {
  20050. this._console.warn(`Warning: ${message} This will become an error in Angular v6.x`);
  20051. }
  20052. }
  20053. return dependenciesMetadata;
  20054. }
  20055. _getTokenMetadata(token) {
  20056. token = resolveForwardRef(token);
  20057. let compileToken;
  20058. if (typeof token === 'string') {
  20059. compileToken = { value: token };
  20060. }
  20061. else {
  20062. compileToken = { identifier: { reference: token } };
  20063. }
  20064. return compileToken;
  20065. }
  20066. _getProvidersMetadata(providers, targetEntryComponents, debugInfo, compileProviders = [], type) {
  20067. providers.forEach((provider, providerIdx) => {
  20068. if (Array.isArray(provider)) {
  20069. this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
  20070. }
  20071. else {
  20072. provider = resolveForwardRef(provider);
  20073. let providerMeta = undefined;
  20074. if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
  20075. this._validateProvider(provider);
  20076. providerMeta = new ProviderMeta(provider.provide, provider);
  20077. }
  20078. else if (isValidType(provider)) {
  20079. providerMeta = new ProviderMeta(provider, { useClass: provider });
  20080. }
  20081. else if (provider === void 0) {
  20082. this._reportError(syntaxError(`Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files.`));
  20083. return;
  20084. }
  20085. else {
  20086. const providersInfo = providers.reduce((soFar, seenProvider, seenProviderIdx) => {
  20087. if (seenProviderIdx < providerIdx) {
  20088. soFar.push(`${stringifyType(seenProvider)}`);
  20089. }
  20090. else if (seenProviderIdx == providerIdx) {
  20091. soFar.push(`?${stringifyType(seenProvider)}?`);
  20092. }
  20093. else if (seenProviderIdx == providerIdx + 1) {
  20094. soFar.push('...');
  20095. }
  20096. return soFar;
  20097. }, [])
  20098. .join(', ');
  20099. this._reportError(syntaxError(`Invalid ${debugInfo ? debugInfo : 'provider'} - only instances of Provider and Type are allowed, got: [${providersInfo}]`), type);
  20100. return;
  20101. }
  20102. if (providerMeta.token ===
  20103. this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
  20104. targetEntryComponents.push(...this._getEntryComponentsFromProvider(providerMeta, type));
  20105. }
  20106. else {
  20107. compileProviders.push(this.getProviderMetadata(providerMeta));
  20108. }
  20109. }
  20110. });
  20111. return compileProviders;
  20112. }
  20113. _validateProvider(provider) {
  20114. if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
  20115. this._reportError(syntaxError(`Invalid provider for ${stringifyType(provider.provide)}. useClass cannot be ${provider.useClass}.
  20116. Usually it happens when:
  20117. 1. There's a circular dependency (might be caused by using index.ts (barrel) files).
  20118. 2. Class was used before it was declared. Use forwardRef in this case.`));
  20119. }
  20120. }
  20121. _getEntryComponentsFromProvider(provider, type) {
  20122. const components = [];
  20123. const collectedIdentifiers = [];
  20124. if (provider.useFactory || provider.useExisting || provider.useClass) {
  20125. this._reportError(syntaxError(`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!`), type);
  20126. return [];
  20127. }
  20128. if (!provider.multi) {
  20129. this._reportError(syntaxError(`The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!`), type);
  20130. return [];
  20131. }
  20132. extractIdentifiers(provider.useValue, collectedIdentifiers);
  20133. collectedIdentifiers.forEach((identifier) => {
  20134. const entry = this._getEntryComponentMetadata(identifier.reference, false);
  20135. if (entry) {
  20136. components.push(entry);
  20137. }
  20138. });
  20139. return components;
  20140. }
  20141. _getEntryComponentMetadata(dirType, throwIfNotFound = true) {
  20142. const dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
  20143. if (dirMeta && dirMeta.metadata.isComponent) {
  20144. return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
  20145. }
  20146. const dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
  20147. if (dirSummary && dirSummary.isComponent) {
  20148. return { componentType: dirType, componentFactory: dirSummary.componentFactory };
  20149. }
  20150. if (throwIfNotFound) {
  20151. throw syntaxError(`${dirType.name} cannot be used as an entry component.`);
  20152. }
  20153. return null;
  20154. }
  20155. _getInjectableTypeMetadata(type, dependencies = null) {
  20156. const typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
  20157. if (typeSummary) {
  20158. return typeSummary.type;
  20159. }
  20160. return this._getTypeMetadata(type, dependencies);
  20161. }
  20162. getProviderMetadata(provider) {
  20163. let compileDeps = undefined;
  20164. let compileTypeMetadata = null;
  20165. let compileFactoryMetadata = null;
  20166. let token = this._getTokenMetadata(provider.token);
  20167. if (provider.useClass) {
  20168. compileTypeMetadata =
  20169. this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
  20170. compileDeps = compileTypeMetadata.diDeps;
  20171. if (provider.token === provider.useClass) {
  20172. // use the compileTypeMetadata as it contains information about lifecycleHooks...
  20173. token = { identifier: compileTypeMetadata };
  20174. }
  20175. }
  20176. else if (provider.useFactory) {
  20177. compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
  20178. compileDeps = compileFactoryMetadata.diDeps;
  20179. }
  20180. return {
  20181. token: token,
  20182. useClass: compileTypeMetadata,
  20183. useValue: provider.useValue,
  20184. useFactory: compileFactoryMetadata,
  20185. useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
  20186. deps: compileDeps,
  20187. multi: provider.multi
  20188. };
  20189. }
  20190. _getQueriesMetadata(queries, isViewQuery, directiveType) {
  20191. const res = [];
  20192. Object.keys(queries).forEach((propertyName) => {
  20193. const query = queries[propertyName];
  20194. if (query.isViewQuery === isViewQuery) {
  20195. res.push(this._getQueryMetadata(query, propertyName, directiveType));
  20196. }
  20197. });
  20198. return res;
  20199. }
  20200. _queryVarBindings(selector) { return selector.split(/\s*,\s*/); }
  20201. _getQueryMetadata(q, propertyName, typeOrFunc) {
  20202. let selectors;
  20203. if (typeof q.selector === 'string') {
  20204. selectors =
  20205. this._queryVarBindings(q.selector).map(varName => this._getTokenMetadata(varName));
  20206. }
  20207. else {
  20208. if (!q.selector) {
  20209. this._reportError(syntaxError(`Can't construct a query for the property "${propertyName}" of "${stringifyType(typeOrFunc)}" since the query selector wasn't defined.`), typeOrFunc);
  20210. selectors = [];
  20211. }
  20212. else {
  20213. selectors = [this._getTokenMetadata(q.selector)];
  20214. }
  20215. }
  20216. return {
  20217. selectors,
  20218. first: q.first,
  20219. descendants: q.descendants, propertyName,
  20220. read: q.read ? this._getTokenMetadata(q.read) : null,
  20221. static: q.static
  20222. };
  20223. }
  20224. _reportError(error, type, otherType) {
  20225. if (this._errorCollector) {
  20226. this._errorCollector(error, type);
  20227. if (otherType) {
  20228. this._errorCollector(error, otherType);
  20229. }
  20230. }
  20231. else {
  20232. throw error;
  20233. }
  20234. }
  20235. }
  20236. function flattenArray(tree, out = []) {
  20237. if (tree) {
  20238. for (let i = 0; i < tree.length; i++) {
  20239. const item = resolveForwardRef(tree[i]);
  20240. if (Array.isArray(item)) {
  20241. flattenArray(item, out);
  20242. }
  20243. else {
  20244. out.push(item);
  20245. }
  20246. }
  20247. }
  20248. return out;
  20249. }
  20250. function dedupeArray(array) {
  20251. if (array) {
  20252. return Array.from(new Set(array));
  20253. }
  20254. return [];
  20255. }
  20256. function flattenAndDedupeArray(tree) {
  20257. return dedupeArray(flattenArray(tree));
  20258. }
  20259. function isValidType(value) {
  20260. return (value instanceof StaticSymbol) || (value instanceof Type);
  20261. }
  20262. function extractIdentifiers(value, targetIdentifiers) {
  20263. visitValue(value, new _CompileValueConverter(), targetIdentifiers);
  20264. }
  20265. class _CompileValueConverter extends ValueTransformer {
  20266. visitOther(value, targetIdentifiers) {
  20267. targetIdentifiers.push({ reference: value });
  20268. }
  20269. }
  20270. function stringifyType(type) {
  20271. if (type instanceof StaticSymbol) {
  20272. return `${type.name} in ${type.filePath}`;
  20273. }
  20274. else {
  20275. return stringify(type);
  20276. }
  20277. }
  20278. /**
  20279. * Indicates that a component is still being loaded in a synchronous compile.
  20280. */
  20281. function componentStillLoadingError(compType) {
  20282. const error = Error(`Can't compile synchronously as ${stringify(compType)} is still being loaded!`);
  20283. error[ERROR_COMPONENT_TYPE] = compType;
  20284. return error;
  20285. }
  20286. /**
  20287. * @license
  20288. * Copyright Google Inc. All Rights Reserved.
  20289. *
  20290. * Use of this source code is governed by an MIT-style license that can be
  20291. * found in the LICENSE file at https://angular.io/license
  20292. */
  20293. function providerDef(ctx, providerAst) {
  20294. let flags = 0 /* None */;
  20295. if (!providerAst.eager) {
  20296. flags |= 4096 /* LazyProvider */;
  20297. }
  20298. if (providerAst.providerType === ProviderAstType.PrivateService) {
  20299. flags |= 8192 /* PrivateProvider */;
  20300. }
  20301. if (providerAst.isModule) {
  20302. flags |= 1073741824 /* TypeModuleProvider */;
  20303. }
  20304. providerAst.lifecycleHooks.forEach((lifecycleHook) => {
  20305. // for regular providers, we only support ngOnDestroy
  20306. if (lifecycleHook === LifecycleHooks.OnDestroy ||
  20307. providerAst.providerType === ProviderAstType.Directive ||
  20308. providerAst.providerType === ProviderAstType.Component) {
  20309. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  20310. }
  20311. });
  20312. const { providerExpr, flags: providerFlags, depsExpr } = providerAst.multiProvider ?
  20313. multiProviderDef(ctx, flags, providerAst.providers) :
  20314. singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]);
  20315. return {
  20316. providerExpr,
  20317. flags: providerFlags, depsExpr,
  20318. tokenExpr: tokenExpr(ctx, providerAst.token),
  20319. };
  20320. }
  20321. function multiProviderDef(ctx, flags, providers) {
  20322. const allDepDefs = [];
  20323. const allParams = [];
  20324. const exprs = providers.map((provider, providerIndex) => {
  20325. let expr;
  20326. if (provider.useClass) {
  20327. const depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
  20328. expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
  20329. }
  20330. else if (provider.useFactory) {
  20331. const depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
  20332. expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
  20333. }
  20334. else if (provider.useExisting) {
  20335. const depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
  20336. expr = depExprs[0];
  20337. }
  20338. else {
  20339. expr = convertValueToOutputAst(ctx, provider.useValue);
  20340. }
  20341. return expr;
  20342. });
  20343. const providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
  20344. return {
  20345. providerExpr,
  20346. flags: flags | 1024 /* TypeFactoryProvider */,
  20347. depsExpr: literalArr(allDepDefs)
  20348. };
  20349. function convertDeps(providerIndex, deps) {
  20350. return deps.map((dep, depIndex) => {
  20351. const paramName = `p${providerIndex}_${depIndex}`;
  20352. allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
  20353. allDepDefs.push(depDef(ctx, dep));
  20354. return variable(paramName);
  20355. });
  20356. }
  20357. }
  20358. function singleProviderDef(ctx, flags, providerType, providerMeta) {
  20359. let providerExpr;
  20360. let deps;
  20361. if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {
  20362. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  20363. flags |= 16384 /* TypeDirective */;
  20364. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  20365. }
  20366. else {
  20367. if (providerMeta.useClass) {
  20368. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  20369. flags |= 512 /* TypeClassProvider */;
  20370. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  20371. }
  20372. else if (providerMeta.useFactory) {
  20373. providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
  20374. flags |= 1024 /* TypeFactoryProvider */;
  20375. deps = providerMeta.deps || providerMeta.useFactory.diDeps;
  20376. }
  20377. else if (providerMeta.useExisting) {
  20378. providerExpr = NULL_EXPR;
  20379. flags |= 2048 /* TypeUseExistingProvider */;
  20380. deps = [{ token: providerMeta.useExisting }];
  20381. }
  20382. else {
  20383. providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
  20384. flags |= 256 /* TypeValueProvider */;
  20385. deps = [];
  20386. }
  20387. }
  20388. const depsExpr = literalArr(deps.map(dep => depDef(ctx, dep)));
  20389. return { providerExpr, flags, depsExpr };
  20390. }
  20391. function tokenExpr(ctx, tokenMeta) {
  20392. return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
  20393. literal(tokenMeta.value);
  20394. }
  20395. function depDef(ctx, dep) {
  20396. // Note: the following fields have already been normalized out by provider_analyzer:
  20397. // - isAttribute, isHost
  20398. const expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
  20399. let flags = 0 /* None */;
  20400. if (dep.isSkipSelf) {
  20401. flags |= 1 /* SkipSelf */;
  20402. }
  20403. if (dep.isOptional) {
  20404. flags |= 2 /* Optional */;
  20405. }
  20406. if (dep.isSelf) {
  20407. flags |= 4 /* Self */;
  20408. }
  20409. if (dep.isValue) {
  20410. flags |= 8 /* Value */;
  20411. }
  20412. return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
  20413. }
  20414. function lifecycleHookToNodeFlag(lifecycleHook) {
  20415. let nodeFlag = 0 /* None */;
  20416. switch (lifecycleHook) {
  20417. case LifecycleHooks.AfterContentChecked:
  20418. nodeFlag = 2097152 /* AfterContentChecked */;
  20419. break;
  20420. case LifecycleHooks.AfterContentInit:
  20421. nodeFlag = 1048576 /* AfterContentInit */;
  20422. break;
  20423. case LifecycleHooks.AfterViewChecked:
  20424. nodeFlag = 8388608 /* AfterViewChecked */;
  20425. break;
  20426. case LifecycleHooks.AfterViewInit:
  20427. nodeFlag = 4194304 /* AfterViewInit */;
  20428. break;
  20429. case LifecycleHooks.DoCheck:
  20430. nodeFlag = 262144 /* DoCheck */;
  20431. break;
  20432. case LifecycleHooks.OnChanges:
  20433. nodeFlag = 524288 /* OnChanges */;
  20434. break;
  20435. case LifecycleHooks.OnDestroy:
  20436. nodeFlag = 131072 /* OnDestroy */;
  20437. break;
  20438. case LifecycleHooks.OnInit:
  20439. nodeFlag = 65536 /* OnInit */;
  20440. break;
  20441. }
  20442. return nodeFlag;
  20443. }
  20444. function componentFactoryResolverProviderDef(reflector, ctx, flags, entryComponents) {
  20445. const entryComponentFactories = entryComponents.map((entryComponent) => ctx.importExpr(entryComponent.componentFactory));
  20446. const token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
  20447. const classMeta = {
  20448. diDeps: [
  20449. { isValue: true, value: literalArr(entryComponentFactories) },
  20450. { token: token, isSkipSelf: true, isOptional: true },
  20451. { token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef) },
  20452. ],
  20453. lifecycleHooks: [],
  20454. reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
  20455. };
  20456. const { providerExpr, flags: providerFlags, depsExpr } = singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {
  20457. token,
  20458. multi: false,
  20459. useClass: classMeta,
  20460. });
  20461. return { providerExpr, flags: providerFlags, depsExpr, tokenExpr: tokenExpr(ctx, token) };
  20462. }
  20463. /**
  20464. * @license
  20465. * Copyright Google Inc. All Rights Reserved.
  20466. *
  20467. * Use of this source code is governed by an MIT-style license that can be
  20468. * found in the LICENSE file at https://angular.io/license
  20469. */
  20470. class NgModuleCompileResult {
  20471. constructor(ngModuleFactoryVar) {
  20472. this.ngModuleFactoryVar = ngModuleFactoryVar;
  20473. }
  20474. }
  20475. const LOG_VAR = variable('_l');
  20476. class NgModuleCompiler {
  20477. constructor(reflector) {
  20478. this.reflector = reflector;
  20479. }
  20480. compile(ctx, ngModuleMeta, extraProviders) {
  20481. const sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
  20482. const entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
  20483. const bootstrapComponents = ngModuleMeta.bootstrapComponents;
  20484. const providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
  20485. const providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
  20486. .concat(providerParser.parse().map((provider) => providerDef(ctx, provider)))
  20487. .map(({ providerExpr, depsExpr, flags, tokenExpr }) => {
  20488. return importExpr(Identifiers.moduleProviderDef).callFn([
  20489. literal(flags), tokenExpr, providerExpr, depsExpr
  20490. ]);
  20491. });
  20492. const ngModuleDef = importExpr(Identifiers.moduleDef).callFn([literalArr(providerDefs)]);
  20493. const ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
  20494. const ngModuleFactoryVar = `${identifierName(ngModuleMeta.type)}NgFactory`;
  20495. this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers.createModuleFactory).callFn([
  20496. ctx.importExpr(ngModuleMeta.type.reference),
  20497. literalArr(bootstrapComponents.map(id => ctx.importExpr(id.reference))),
  20498. ngModuleDefFactory
  20499. ]));
  20500. if (ngModuleMeta.id) {
  20501. const id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
  20502. ctx.importExpr(ngModuleMeta.id);
  20503. const registerFactoryStmt = importExpr(Identifiers.RegisterModuleFactoryFn)
  20504. .callFn([id, variable(ngModuleFactoryVar)])
  20505. .toStmt();
  20506. ctx.statements.push(registerFactoryStmt);
  20507. }
  20508. return new NgModuleCompileResult(ngModuleFactoryVar);
  20509. }
  20510. createStub(ctx, ngModuleReference) {
  20511. this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
  20512. }
  20513. _createNgModuleFactory(ctx, reference, value) {
  20514. const ngModuleFactoryVar = `${identifierName({ reference: reference })}NgFactory`;
  20515. const ngModuleFactoryStmt = variable(ngModuleFactoryVar)
  20516. .set(value)
  20517. .toDeclStmt(importType(Identifiers.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]);
  20518. ctx.statements.push(ngModuleFactoryStmt);
  20519. }
  20520. }
  20521. /**
  20522. * @license
  20523. * Copyright Google Inc. All Rights Reserved.
  20524. *
  20525. * Use of this source code is governed by an MIT-style license that can be
  20526. * found in the LICENSE file at https://angular.io/license
  20527. */
  20528. /**
  20529. * Resolves types to {@link NgModule}.
  20530. */
  20531. class NgModuleResolver {
  20532. constructor(_reflector) {
  20533. this._reflector = _reflector;
  20534. }
  20535. isNgModule(type) { return this._reflector.annotations(type).some(createNgModule.isTypeOf); }
  20536. resolve(type, throwIfNotFound = true) {
  20537. const ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
  20538. if (ngModuleMeta) {
  20539. return ngModuleMeta;
  20540. }
  20541. else {
  20542. if (throwIfNotFound) {
  20543. throw new Error(`No NgModule metadata found for '${stringify(type)}'.`);
  20544. }
  20545. return null;
  20546. }
  20547. }
  20548. }
  20549. /**
  20550. * @license
  20551. * Copyright Google Inc. All Rights Reserved.
  20552. *
  20553. * Use of this source code is governed by an MIT-style license that can be
  20554. * found in the LICENSE file at https://angular.io/license
  20555. */
  20556. function debugOutputAstAsTypeScript(ast) {
  20557. const converter = new _TsEmitterVisitor();
  20558. const ctx = EmitterVisitorContext.createRoot();
  20559. const asts = Array.isArray(ast) ? ast : [ast];
  20560. asts.forEach((ast) => {
  20561. if (ast instanceof Statement) {
  20562. ast.visitStatement(converter, ctx);
  20563. }
  20564. else if (ast instanceof Expression) {
  20565. ast.visitExpression(converter, ctx);
  20566. }
  20567. else if (ast instanceof Type$1) {
  20568. ast.visitType(converter, ctx);
  20569. }
  20570. else {
  20571. throw new Error(`Don't know how to print debug info for ${ast}`);
  20572. }
  20573. });
  20574. return ctx.toSource();
  20575. }
  20576. class TypeScriptEmitter {
  20577. emitStatementsAndContext(genFilePath, stmts, preamble = '', emitSourceMaps = true, referenceFilter, importFilter) {
  20578. const converter = new _TsEmitterVisitor(referenceFilter, importFilter);
  20579. const ctx = EmitterVisitorContext.createRoot();
  20580. converter.visitAllStatements(stmts, ctx);
  20581. const preambleLines = preamble ? preamble.split('\n') : [];
  20582. converter.reexports.forEach((reexports, exportedModuleName) => {
  20583. const reexportsCode = reexports.map(reexport => `${reexport.name} as ${reexport.as}`).join(',');
  20584. preambleLines.push(`export {${reexportsCode}} from '${exportedModuleName}';`);
  20585. });
  20586. converter.importsWithPrefixes.forEach((prefix, importedModuleName) => {
  20587. // Note: can't write the real word for import as it screws up system.js auto detection...
  20588. preambleLines.push(`imp` +
  20589. `ort * as ${prefix} from '${importedModuleName}';`);
  20590. });
  20591. const sm = emitSourceMaps ?
  20592. ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
  20593. '';
  20594. const lines = [...preambleLines, ctx.toSource(), sm];
  20595. if (sm) {
  20596. // always add a newline at the end, as some tools have bugs without it.
  20597. lines.push('');
  20598. }
  20599. ctx.setPreambleLineCount(preambleLines.length);
  20600. return { sourceText: lines.join('\n'), context: ctx };
  20601. }
  20602. emitStatements(genFilePath, stmts, preamble = '') {
  20603. return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
  20604. }
  20605. }
  20606. class _TsEmitterVisitor extends AbstractEmitterVisitor {
  20607. constructor(referenceFilter, importFilter) {
  20608. super(false);
  20609. this.referenceFilter = referenceFilter;
  20610. this.importFilter = importFilter;
  20611. this.typeExpression = 0;
  20612. this.importsWithPrefixes = new Map();
  20613. this.reexports = new Map();
  20614. }
  20615. visitType(t, ctx, defaultType = 'any') {
  20616. if (t) {
  20617. this.typeExpression++;
  20618. t.visitType(this, ctx);
  20619. this.typeExpression--;
  20620. }
  20621. else {
  20622. ctx.print(null, defaultType);
  20623. }
  20624. }
  20625. visitLiteralExpr(ast, ctx) {
  20626. const value = ast.value;
  20627. if (value == null && ast.type != INFERRED_TYPE) {
  20628. ctx.print(ast, `(${value} as any)`);
  20629. return null;
  20630. }
  20631. return super.visitLiteralExpr(ast, ctx);
  20632. }
  20633. // Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
  20634. // In SNC mode, [] have the type never[], so we cast here to any[].
  20635. // TODO: narrow the cast to a more explicit type, or use a pattern that does not
  20636. // start with [].concat. see https://github.com/angular/angular/pull/11846
  20637. visitLiteralArrayExpr(ast, ctx) {
  20638. if (ast.entries.length === 0) {
  20639. ctx.print(ast, '(');
  20640. }
  20641. const result = super.visitLiteralArrayExpr(ast, ctx);
  20642. if (ast.entries.length === 0) {
  20643. ctx.print(ast, ' as any[])');
  20644. }
  20645. return result;
  20646. }
  20647. visitExternalExpr(ast, ctx) {
  20648. this._visitIdentifier(ast.value, ast.typeParams, ctx);
  20649. return null;
  20650. }
  20651. visitAssertNotNullExpr(ast, ctx) {
  20652. const result = super.visitAssertNotNullExpr(ast, ctx);
  20653. ctx.print(ast, '!');
  20654. return result;
  20655. }
  20656. visitDeclareVarStmt(stmt, ctx) {
  20657. if (stmt.hasModifier(StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
  20658. !stmt.type) {
  20659. // check for a reexport
  20660. const { name, moduleName } = stmt.value.value;
  20661. if (moduleName) {
  20662. let reexports = this.reexports.get(moduleName);
  20663. if (!reexports) {
  20664. reexports = [];
  20665. this.reexports.set(moduleName, reexports);
  20666. }
  20667. reexports.push({ name: name, as: stmt.name });
  20668. return null;
  20669. }
  20670. }
  20671. if (stmt.hasModifier(StmtModifier.Exported)) {
  20672. ctx.print(stmt, `export `);
  20673. }
  20674. if (stmt.hasModifier(StmtModifier.Final)) {
  20675. ctx.print(stmt, `const`);
  20676. }
  20677. else {
  20678. ctx.print(stmt, `var`);
  20679. }
  20680. ctx.print(stmt, ` ${stmt.name}`);
  20681. this._printColonType(stmt.type, ctx);
  20682. if (stmt.value) {
  20683. ctx.print(stmt, ` = `);
  20684. stmt.value.visitExpression(this, ctx);
  20685. }
  20686. ctx.println(stmt, `;`);
  20687. return null;
  20688. }
  20689. visitWrappedNodeExpr(ast, ctx) {
  20690. throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
  20691. }
  20692. visitCastExpr(ast, ctx) {
  20693. ctx.print(ast, `(<`);
  20694. ast.type.visitType(this, ctx);
  20695. ctx.print(ast, `>`);
  20696. ast.value.visitExpression(this, ctx);
  20697. ctx.print(ast, `)`);
  20698. return null;
  20699. }
  20700. visitInstantiateExpr(ast, ctx) {
  20701. ctx.print(ast, `new `);
  20702. this.typeExpression++;
  20703. ast.classExpr.visitExpression(this, ctx);
  20704. this.typeExpression--;
  20705. ctx.print(ast, `(`);
  20706. this.visitAllExpressions(ast.args, ctx, ',');
  20707. ctx.print(ast, `)`);
  20708. return null;
  20709. }
  20710. visitDeclareClassStmt(stmt, ctx) {
  20711. ctx.pushClass(stmt);
  20712. if (stmt.hasModifier(StmtModifier.Exported)) {
  20713. ctx.print(stmt, `export `);
  20714. }
  20715. ctx.print(stmt, `class ${stmt.name}`);
  20716. if (stmt.parent != null) {
  20717. ctx.print(stmt, ` extends `);
  20718. this.typeExpression++;
  20719. stmt.parent.visitExpression(this, ctx);
  20720. this.typeExpression--;
  20721. }
  20722. ctx.println(stmt, ` {`);
  20723. ctx.incIndent();
  20724. stmt.fields.forEach((field) => this._visitClassField(field, ctx));
  20725. if (stmt.constructorMethod != null) {
  20726. this._visitClassConstructor(stmt, ctx);
  20727. }
  20728. stmt.getters.forEach((getter) => this._visitClassGetter(getter, ctx));
  20729. stmt.methods.forEach((method) => this._visitClassMethod(method, ctx));
  20730. ctx.decIndent();
  20731. ctx.println(stmt, `}`);
  20732. ctx.popClass();
  20733. return null;
  20734. }
  20735. _visitClassField(field, ctx) {
  20736. if (field.hasModifier(StmtModifier.Private)) {
  20737. // comment out as a workaround for #10967
  20738. ctx.print(null, `/*private*/ `);
  20739. }
  20740. if (field.hasModifier(StmtModifier.Static)) {
  20741. ctx.print(null, 'static ');
  20742. }
  20743. ctx.print(null, field.name);
  20744. this._printColonType(field.type, ctx);
  20745. if (field.initializer) {
  20746. ctx.print(null, ' = ');
  20747. field.initializer.visitExpression(this, ctx);
  20748. }
  20749. ctx.println(null, `;`);
  20750. }
  20751. _visitClassGetter(getter, ctx) {
  20752. if (getter.hasModifier(StmtModifier.Private)) {
  20753. ctx.print(null, `private `);
  20754. }
  20755. ctx.print(null, `get ${getter.name}()`);
  20756. this._printColonType(getter.type, ctx);
  20757. ctx.println(null, ` {`);
  20758. ctx.incIndent();
  20759. this.visitAllStatements(getter.body, ctx);
  20760. ctx.decIndent();
  20761. ctx.println(null, `}`);
  20762. }
  20763. _visitClassConstructor(stmt, ctx) {
  20764. ctx.print(stmt, `constructor(`);
  20765. this._visitParams(stmt.constructorMethod.params, ctx);
  20766. ctx.println(stmt, `) {`);
  20767. ctx.incIndent();
  20768. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  20769. ctx.decIndent();
  20770. ctx.println(stmt, `}`);
  20771. }
  20772. _visitClassMethod(method, ctx) {
  20773. if (method.hasModifier(StmtModifier.Private)) {
  20774. ctx.print(null, `private `);
  20775. }
  20776. ctx.print(null, `${method.name}(`);
  20777. this._visitParams(method.params, ctx);
  20778. ctx.print(null, `)`);
  20779. this._printColonType(method.type, ctx, 'void');
  20780. ctx.println(null, ` {`);
  20781. ctx.incIndent();
  20782. this.visitAllStatements(method.body, ctx);
  20783. ctx.decIndent();
  20784. ctx.println(null, `}`);
  20785. }
  20786. visitFunctionExpr(ast, ctx) {
  20787. if (ast.name) {
  20788. ctx.print(ast, 'function ');
  20789. ctx.print(ast, ast.name);
  20790. }
  20791. ctx.print(ast, `(`);
  20792. this._visitParams(ast.params, ctx);
  20793. ctx.print(ast, `)`);
  20794. this._printColonType(ast.type, ctx, 'void');
  20795. if (!ast.name) {
  20796. ctx.print(ast, ` => `);
  20797. }
  20798. ctx.println(ast, '{');
  20799. ctx.incIndent();
  20800. this.visitAllStatements(ast.statements, ctx);
  20801. ctx.decIndent();
  20802. ctx.print(ast, `}`);
  20803. return null;
  20804. }
  20805. visitDeclareFunctionStmt(stmt, ctx) {
  20806. if (stmt.hasModifier(StmtModifier.Exported)) {
  20807. ctx.print(stmt, `export `);
  20808. }
  20809. ctx.print(stmt, `function ${stmt.name}(`);
  20810. this._visitParams(stmt.params, ctx);
  20811. ctx.print(stmt, `)`);
  20812. this._printColonType(stmt.type, ctx, 'void');
  20813. ctx.println(stmt, ` {`);
  20814. ctx.incIndent();
  20815. this.visitAllStatements(stmt.statements, ctx);
  20816. ctx.decIndent();
  20817. ctx.println(stmt, `}`);
  20818. return null;
  20819. }
  20820. visitTryCatchStmt(stmt, ctx) {
  20821. ctx.println(stmt, `try {`);
  20822. ctx.incIndent();
  20823. this.visitAllStatements(stmt.bodyStmts, ctx);
  20824. ctx.decIndent();
  20825. ctx.println(stmt, `} catch (${CATCH_ERROR_VAR$1.name}) {`);
  20826. ctx.incIndent();
  20827. const catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
  20828. StmtModifier.Final
  20829. ])].concat(stmt.catchStmts);
  20830. this.visitAllStatements(catchStmts, ctx);
  20831. ctx.decIndent();
  20832. ctx.println(stmt, `}`);
  20833. return null;
  20834. }
  20835. visitBuiltinType(type, ctx) {
  20836. let typeStr;
  20837. switch (type.name) {
  20838. case BuiltinTypeName.Bool:
  20839. typeStr = 'boolean';
  20840. break;
  20841. case BuiltinTypeName.Dynamic:
  20842. typeStr = 'any';
  20843. break;
  20844. case BuiltinTypeName.Function:
  20845. typeStr = 'Function';
  20846. break;
  20847. case BuiltinTypeName.Number:
  20848. typeStr = 'number';
  20849. break;
  20850. case BuiltinTypeName.Int:
  20851. typeStr = 'number';
  20852. break;
  20853. case BuiltinTypeName.String:
  20854. typeStr = 'string';
  20855. break;
  20856. case BuiltinTypeName.None:
  20857. typeStr = 'never';
  20858. break;
  20859. default:
  20860. throw new Error(`Unsupported builtin type ${type.name}`);
  20861. }
  20862. ctx.print(null, typeStr);
  20863. return null;
  20864. }
  20865. visitExpressionType(ast, ctx) {
  20866. ast.value.visitExpression(this, ctx);
  20867. if (ast.typeParams !== null) {
  20868. ctx.print(null, '<');
  20869. this.visitAllObjects(type => this.visitType(type, ctx), ast.typeParams, ctx, ',');
  20870. ctx.print(null, '>');
  20871. }
  20872. return null;
  20873. }
  20874. visitArrayType(type, ctx) {
  20875. this.visitType(type.of, ctx);
  20876. ctx.print(null, `[]`);
  20877. return null;
  20878. }
  20879. visitMapType(type, ctx) {
  20880. ctx.print(null, `{[key: string]:`);
  20881. this.visitType(type.valueType, ctx);
  20882. ctx.print(null, `}`);
  20883. return null;
  20884. }
  20885. getBuiltinMethodName(method) {
  20886. let name;
  20887. switch (method) {
  20888. case BuiltinMethod.ConcatArray:
  20889. name = 'concat';
  20890. break;
  20891. case BuiltinMethod.SubscribeObservable:
  20892. name = 'subscribe';
  20893. break;
  20894. case BuiltinMethod.Bind:
  20895. name = 'bind';
  20896. break;
  20897. default:
  20898. throw new Error(`Unknown builtin method: ${method}`);
  20899. }
  20900. return name;
  20901. }
  20902. _visitParams(params, ctx) {
  20903. this.visitAllObjects(param => {
  20904. ctx.print(null, param.name);
  20905. this._printColonType(param.type, ctx);
  20906. }, params, ctx, ',');
  20907. }
  20908. _visitIdentifier(value, typeParams, ctx) {
  20909. const { name, moduleName } = value;
  20910. if (this.referenceFilter && this.referenceFilter(value)) {
  20911. ctx.print(null, '(null as any)');
  20912. return;
  20913. }
  20914. if (moduleName && (!this.importFilter || !this.importFilter(value))) {
  20915. let prefix = this.importsWithPrefixes.get(moduleName);
  20916. if (prefix == null) {
  20917. prefix = `i${this.importsWithPrefixes.size}`;
  20918. this.importsWithPrefixes.set(moduleName, prefix);
  20919. }
  20920. ctx.print(null, `${prefix}.`);
  20921. }
  20922. ctx.print(null, name);
  20923. if (this.typeExpression > 0) {
  20924. // If we are in a type expression that refers to a generic type then supply
  20925. // the required type parameters. If there were not enough type parameters
  20926. // supplied, supply any as the type. Outside a type expression the reference
  20927. // should not supply type parameters and be treated as a simple value reference
  20928. // to the constructor function itself.
  20929. const suppliedParameters = typeParams || [];
  20930. if (suppliedParameters.length > 0) {
  20931. ctx.print(null, `<`);
  20932. this.visitAllObjects(type => type.visitType(this, ctx), typeParams, ctx, ',');
  20933. ctx.print(null, `>`);
  20934. }
  20935. }
  20936. }
  20937. _printColonType(type, ctx, defaultType) {
  20938. if (type !== INFERRED_TYPE) {
  20939. ctx.print(null, ':');
  20940. this.visitType(type, ctx, defaultType);
  20941. }
  20942. }
  20943. }
  20944. /**
  20945. * @license
  20946. * Copyright Google Inc. All Rights Reserved.
  20947. *
  20948. * Use of this source code is governed by an MIT-style license that can be
  20949. * found in the LICENSE file at https://angular.io/license
  20950. */
  20951. /**
  20952. * Resolve a `Type` for {@link Pipe}.
  20953. *
  20954. * This interface can be overridden by the application developer to create custom behavior.
  20955. *
  20956. * See {@link Compiler}
  20957. */
  20958. class PipeResolver {
  20959. constructor(_reflector) {
  20960. this._reflector = _reflector;
  20961. }
  20962. isPipe(type) {
  20963. const typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  20964. return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
  20965. }
  20966. /**
  20967. * Return {@link Pipe} for a given `Type`.
  20968. */
  20969. resolve(type, throwIfNotFound = true) {
  20970. const metas = this._reflector.annotations(resolveForwardRef(type));
  20971. if (metas) {
  20972. const annotation = findLast(metas, createPipe.isTypeOf);
  20973. if (annotation) {
  20974. return annotation;
  20975. }
  20976. }
  20977. if (throwIfNotFound) {
  20978. throw new Error(`No Pipe decorator found on ${stringify(type)}`);
  20979. }
  20980. return null;
  20981. }
  20982. }
  20983. /**
  20984. * @license
  20985. * Copyright Google Inc. All Rights Reserved.
  20986. *
  20987. * Use of this source code is governed by an MIT-style license that can be
  20988. * found in the LICENSE file at https://angular.io/license
  20989. */
  20990. /**
  20991. * Generates code that is used to type check templates.
  20992. */
  20993. class TypeCheckCompiler {
  20994. constructor(options, reflector) {
  20995. this.options = options;
  20996. this.reflector = reflector;
  20997. }
  20998. /**
  20999. * Important notes:
  21000. * - This must not produce new `import` statements, but only refer to types outside
  21001. * of the file via the variables provided via externalReferenceVars.
  21002. * This allows Typescript to reuse the old program's structure as no imports have changed.
  21003. * - This must not produce any exports, as this would pollute the .d.ts file
  21004. * and also violate the point above.
  21005. */
  21006. compileComponent(componentId, component, template, usedPipes, externalReferenceVars, ctx) {
  21007. const pipes = new Map();
  21008. usedPipes.forEach(p => pipes.set(p.name, p.type.reference));
  21009. let embeddedViewCount = 0;
  21010. const viewBuilderFactory = (parent, guards) => {
  21011. const embeddedViewIndex = embeddedViewCount++;
  21012. return new ViewBuilder(this.options, this.reflector, externalReferenceVars, parent, component.type.reference, component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
  21013. };
  21014. const visitor = viewBuilderFactory(null, []);
  21015. visitor.visitAll([], template);
  21016. return visitor.build(componentId);
  21017. }
  21018. }
  21019. const DYNAMIC_VAR_NAME = '_any';
  21020. class TypeCheckLocalResolver {
  21021. notifyImplicitReceiverUse() { }
  21022. getLocal(name) {
  21023. if (name === EventHandlerVars.event.name) {
  21024. // References to the event should not be type-checked.
  21025. // TODO(chuckj): determine a better type for the event.
  21026. return variable(DYNAMIC_VAR_NAME);
  21027. }
  21028. return null;
  21029. }
  21030. }
  21031. const defaultResolver = new TypeCheckLocalResolver();
  21032. class ViewBuilder {
  21033. constructor(options, reflector, externalReferenceVars, parent, component, isHostComponent, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory) {
  21034. this.options = options;
  21035. this.reflector = reflector;
  21036. this.externalReferenceVars = externalReferenceVars;
  21037. this.parent = parent;
  21038. this.component = component;
  21039. this.isHostComponent = isHostComponent;
  21040. this.embeddedViewIndex = embeddedViewIndex;
  21041. this.pipes = pipes;
  21042. this.guards = guards;
  21043. this.ctx = ctx;
  21044. this.viewBuilderFactory = viewBuilderFactory;
  21045. this.refOutputVars = new Map();
  21046. this.variables = [];
  21047. this.children = [];
  21048. this.updates = [];
  21049. this.actions = [];
  21050. }
  21051. getOutputVar(type) {
  21052. let varName;
  21053. if (type === this.component && this.isHostComponent) {
  21054. varName = DYNAMIC_VAR_NAME;
  21055. }
  21056. else if (type instanceof StaticSymbol) {
  21057. varName = this.externalReferenceVars.get(type);
  21058. }
  21059. else {
  21060. varName = DYNAMIC_VAR_NAME;
  21061. }
  21062. if (!varName) {
  21063. throw new Error(`Illegal State: referring to a type without a variable ${JSON.stringify(type)}`);
  21064. }
  21065. return varName;
  21066. }
  21067. getTypeGuardExpressions(ast) {
  21068. const result = [...this.guards];
  21069. for (let directive of ast.directives) {
  21070. for (let input of directive.inputs) {
  21071. const guard = directive.directive.guards[input.directiveName];
  21072. if (guard) {
  21073. const useIf = guard === 'UseIf';
  21074. result.push({
  21075. guard,
  21076. useIf,
  21077. expression: { context: this.component, value: input.value }
  21078. });
  21079. }
  21080. }
  21081. }
  21082. return result;
  21083. }
  21084. visitAll(variables, astNodes) {
  21085. this.variables = variables;
  21086. templateVisitAll(this, astNodes);
  21087. }
  21088. build(componentId, targetStatements = []) {
  21089. this.children.forEach((child) => child.build(componentId, targetStatements));
  21090. let viewStmts = [variable(DYNAMIC_VAR_NAME).set(NULL_EXPR).toDeclStmt(DYNAMIC_TYPE)];
  21091. let bindingCount = 0;
  21092. this.updates.forEach((expression) => {
  21093. const { sourceSpan, context, value } = this.preprocessUpdateExpression(expression);
  21094. const bindingId = `${bindingCount++}`;
  21095. const nameResolver = context === this.component ? this : defaultResolver;
  21096. const { stmts, currValExpr } = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.General);
  21097. stmts.push(new ExpressionStatement(currValExpr));
  21098. viewStmts.push(...stmts.map((stmt) => applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
  21099. });
  21100. this.actions.forEach(({ sourceSpan, context, value }) => {
  21101. const bindingId = `${bindingCount++}`;
  21102. const nameResolver = context === this.component ? this : defaultResolver;
  21103. const { stmts } = convertActionBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId);
  21104. viewStmts.push(...stmts.map((stmt) => applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
  21105. });
  21106. if (this.guards.length) {
  21107. let guardExpression = undefined;
  21108. for (const guard of this.guards) {
  21109. const { context, value } = this.preprocessUpdateExpression(guard.expression);
  21110. const bindingId = `${bindingCount++}`;
  21111. const nameResolver = context === this.component ? this : defaultResolver;
  21112. // We only support support simple expressions and ignore others as they
  21113. // are unlikely to affect type narrowing.
  21114. const { stmts, currValExpr } = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.TrySimple);
  21115. if (stmts.length == 0) {
  21116. const guardClause = guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
  21117. guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
  21118. }
  21119. }
  21120. if (guardExpression) {
  21121. viewStmts = [new IfStmt(guardExpression, viewStmts)];
  21122. }
  21123. }
  21124. const viewName = `_View_${componentId}_${this.embeddedViewIndex}`;
  21125. const viewFactory = new DeclareFunctionStmt(viewName, [], viewStmts);
  21126. targetStatements.push(viewFactory);
  21127. return targetStatements;
  21128. }
  21129. visitBoundText(ast, context) {
  21130. const astWithSource = ast.value;
  21131. const inter = astWithSource.ast;
  21132. inter.expressions.forEach((expr) => this.updates.push({ context: this.component, value: expr, sourceSpan: ast.sourceSpan }));
  21133. }
  21134. visitEmbeddedTemplate(ast, context) {
  21135. this.visitElementOrTemplate(ast);
  21136. // Note: The old view compiler used to use an `any` type
  21137. // for the context in any embedded view.
  21138. // We keep this behaivor behind a flag for now.
  21139. if (this.options.fullTemplateTypeCheck) {
  21140. // Find any applicable type guards. For example, NgIf has a type guard on ngIf
  21141. // (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
  21142. // stamped out if ngIf is truthy so any bindings in the template can assume that,
  21143. // if a nullable type is used for ngIf, that expression is not null or undefined.
  21144. const guards = this.getTypeGuardExpressions(ast);
  21145. const childVisitor = this.viewBuilderFactory(this, guards);
  21146. this.children.push(childVisitor);
  21147. childVisitor.visitAll(ast.variables, ast.children);
  21148. }
  21149. }
  21150. visitElement(ast, context) {
  21151. this.visitElementOrTemplate(ast);
  21152. ast.inputs.forEach((inputAst) => {
  21153. this.updates.push({ context: this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan });
  21154. });
  21155. templateVisitAll(this, ast.children);
  21156. }
  21157. visitElementOrTemplate(ast) {
  21158. ast.directives.forEach((dirAst) => { this.visitDirective(dirAst); });
  21159. ast.references.forEach((ref) => {
  21160. let outputVarType = null;
  21161. // Note: The old view compiler used to use an `any` type
  21162. // for directives exposed via `exportAs`.
  21163. // We keep this behaivor behind a flag for now.
  21164. if (ref.value && ref.value.identifier && this.options.fullTemplateTypeCheck) {
  21165. outputVarType = ref.value.identifier.reference;
  21166. }
  21167. else {
  21168. outputVarType = BuiltinTypeName.Dynamic;
  21169. }
  21170. this.refOutputVars.set(ref.name, outputVarType);
  21171. });
  21172. ast.outputs.forEach((outputAst) => {
  21173. this.actions.push({ context: this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan });
  21174. });
  21175. }
  21176. visitDirective(dirAst) {
  21177. const dirType = dirAst.directive.type.reference;
  21178. dirAst.inputs.forEach((input) => this.updates.push({ context: this.component, value: input.value, sourceSpan: input.sourceSpan }));
  21179. // Note: The old view compiler used to use an `any` type
  21180. // for expressions in host properties / events.
  21181. // We keep this behaivor behind a flag for now.
  21182. if (this.options.fullTemplateTypeCheck) {
  21183. dirAst.hostProperties.forEach((inputAst) => this.updates.push({ context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan }));
  21184. dirAst.hostEvents.forEach((hostEventAst) => this.actions.push({
  21185. context: dirType,
  21186. value: hostEventAst.handler,
  21187. sourceSpan: hostEventAst.sourceSpan
  21188. }));
  21189. }
  21190. }
  21191. notifyImplicitReceiverUse() { }
  21192. getLocal(name) {
  21193. if (name == EventHandlerVars.event.name) {
  21194. return variable(this.getOutputVar(BuiltinTypeName.Dynamic));
  21195. }
  21196. for (let currBuilder = this; currBuilder; currBuilder = currBuilder.parent) {
  21197. let outputVarType;
  21198. // check references
  21199. outputVarType = currBuilder.refOutputVars.get(name);
  21200. if (outputVarType == null) {
  21201. // check variables
  21202. const varAst = currBuilder.variables.find((varAst) => varAst.name === name);
  21203. if (varAst) {
  21204. outputVarType = BuiltinTypeName.Dynamic;
  21205. }
  21206. }
  21207. if (outputVarType != null) {
  21208. return variable(this.getOutputVar(outputVarType));
  21209. }
  21210. }
  21211. return null;
  21212. }
  21213. pipeOutputVar(name) {
  21214. const pipe = this.pipes.get(name);
  21215. if (!pipe) {
  21216. throw new Error(`Illegal State: Could not find pipe ${name} in template of ${this.component}`);
  21217. }
  21218. return this.getOutputVar(pipe);
  21219. }
  21220. preprocessUpdateExpression(expression) {
  21221. return {
  21222. sourceSpan: expression.sourceSpan,
  21223. context: expression.context,
  21224. value: convertPropertyBindingBuiltins({
  21225. createLiteralArrayConverter: (argCount) => (args) => {
  21226. const arr = literalArr(args);
  21227. // Note: The old view compiler used to use an `any` type
  21228. // for arrays.
  21229. return this.options.fullTemplateTypeCheck ? arr : arr.cast(DYNAMIC_TYPE);
  21230. },
  21231. createLiteralMapConverter: (keys) => (values) => {
  21232. const entries = keys.map((k, i) => ({
  21233. key: k.key,
  21234. value: values[i],
  21235. quoted: k.quoted,
  21236. }));
  21237. const map = literalMap(entries);
  21238. // Note: The old view compiler used to use an `any` type
  21239. // for maps.
  21240. return this.options.fullTemplateTypeCheck ? map : map.cast(DYNAMIC_TYPE);
  21241. },
  21242. createPipeConverter: (name, argCount) => (args) => {
  21243. // Note: The old view compiler used to use an `any` type
  21244. // for pipes.
  21245. const pipeExpr = this.options.fullTemplateTypeCheck ?
  21246. variable(this.pipeOutputVar(name)) :
  21247. variable(this.getOutputVar(BuiltinTypeName.Dynamic));
  21248. return pipeExpr.callMethod('transform', args);
  21249. },
  21250. }, expression.value)
  21251. };
  21252. }
  21253. visitNgContent(ast, context) { }
  21254. visitText(ast, context) { }
  21255. visitDirectiveProperty(ast, context) { }
  21256. visitReference(ast, context) { }
  21257. visitVariable(ast, context) { }
  21258. visitEvent(ast, context) { }
  21259. visitElementProperty(ast, context) { }
  21260. visitAttr(ast, context) { }
  21261. }
  21262. /**
  21263. * @license
  21264. * Copyright Google Inc. All Rights Reserved.
  21265. *
  21266. * Use of this source code is governed by an MIT-style license that can be
  21267. * found in the LICENSE file at https://angular.io/license
  21268. */
  21269. const CLASS_ATTR$1 = 'class';
  21270. const STYLE_ATTR = 'style';
  21271. const IMPLICIT_TEMPLATE_VAR = '\$implicit';
  21272. class ViewCompileResult {
  21273. constructor(viewClassVar, rendererTypeVar) {
  21274. this.viewClassVar = viewClassVar;
  21275. this.rendererTypeVar = rendererTypeVar;
  21276. }
  21277. }
  21278. class ViewCompiler {
  21279. constructor(_reflector) {
  21280. this._reflector = _reflector;
  21281. }
  21282. compileComponent(outputCtx, component, template, styles, usedPipes) {
  21283. let embeddedViewCount = 0;
  21284. const staticQueryIds = findStaticQueryIds(template);
  21285. let renderComponentVarName = undefined;
  21286. if (!component.isHost) {
  21287. const template = component.template;
  21288. const customRenderData = [];
  21289. if (template.animations && template.animations.length) {
  21290. customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(outputCtx, template.animations), true));
  21291. }
  21292. const renderComponentVar = variable(rendererTypeName(component.type.reference));
  21293. renderComponentVarName = renderComponentVar.name;
  21294. outputCtx.statements.push(renderComponentVar
  21295. .set(importExpr(Identifiers.createRendererType2).callFn([new LiteralMapExpr([
  21296. new LiteralMapEntry('encapsulation', literal(template.encapsulation), false),
  21297. new LiteralMapEntry('styles', styles, false),
  21298. new LiteralMapEntry('data', new LiteralMapExpr(customRenderData), false)
  21299. ])]))
  21300. .toDeclStmt(importType(Identifiers.RendererType2), [StmtModifier.Final, StmtModifier.Exported]));
  21301. }
  21302. const viewBuilderFactory = (parent) => {
  21303. const embeddedViewIndex = embeddedViewCount++;
  21304. return new ViewBuilder$1(this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory);
  21305. };
  21306. const visitor = viewBuilderFactory(null);
  21307. visitor.visitAll([], template);
  21308. outputCtx.statements.push(...visitor.build());
  21309. return new ViewCompileResult(visitor.viewName, renderComponentVarName);
  21310. }
  21311. }
  21312. const LOG_VAR$1 = variable('_l');
  21313. const VIEW_VAR = variable('_v');
  21314. const CHECK_VAR = variable('_ck');
  21315. const COMP_VAR = variable('_co');
  21316. const EVENT_NAME_VAR = variable('en');
  21317. const ALLOW_DEFAULT_VAR = variable(`ad`);
  21318. class ViewBuilder$1 {
  21319. constructor(reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory) {
  21320. this.reflector = reflector;
  21321. this.outputCtx = outputCtx;
  21322. this.parent = parent;
  21323. this.component = component;
  21324. this.embeddedViewIndex = embeddedViewIndex;
  21325. this.usedPipes = usedPipes;
  21326. this.staticQueryIds = staticQueryIds;
  21327. this.viewBuilderFactory = viewBuilderFactory;
  21328. this.nodes = [];
  21329. this.purePipeNodeIndices = Object.create(null);
  21330. // Need Object.create so that we don't have builtin values...
  21331. this.refNodeIndices = Object.create(null);
  21332. this.variables = [];
  21333. this.children = [];
  21334. // TODO(tbosch): The old view compiler used to use an `any` type
  21335. // for the context in any embedded view. We keep this behaivor for now
  21336. // to be able to introduce the new view compiler without too many errors.
  21337. this.compType = this.embeddedViewIndex > 0 ?
  21338. DYNAMIC_TYPE :
  21339. expressionType(outputCtx.importExpr(this.component.type.reference));
  21340. this.viewName = viewClassName(this.component.type.reference, this.embeddedViewIndex);
  21341. }
  21342. visitAll(variables, astNodes) {
  21343. this.variables = variables;
  21344. // create the pipes for the pure pipes immediately, so that we know their indices.
  21345. if (!this.parent) {
  21346. this.usedPipes.forEach((pipe) => {
  21347. if (pipe.pure) {
  21348. this.purePipeNodeIndices[pipe.name] = this._createPipe(null, pipe);
  21349. }
  21350. });
  21351. }
  21352. if (!this.parent) {
  21353. const queryIds = staticViewQueryIds(this.staticQueryIds);
  21354. this.component.viewQueries.forEach((query, queryIndex) => {
  21355. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  21356. const queryId = queryIndex + 1;
  21357. const bindingType = query.first ? 0 /* First */ : 1 /* All */;
  21358. const flags = 134217728 /* TypeViewQuery */ | calcStaticDynamicQueryFlags(queryIds, queryId, query);
  21359. this.nodes.push(() => ({
  21360. sourceSpan: null,
  21361. nodeFlags: flags,
  21362. nodeDef: importExpr(Identifiers.queryDef).callFn([
  21363. literal(flags), literal(queryId),
  21364. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  21365. ])
  21366. }));
  21367. });
  21368. }
  21369. templateVisitAll(this, astNodes);
  21370. if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
  21371. // if the view is an embedded view, then we need to add an additional root node in some cases
  21372. this.nodes.push(() => ({
  21373. sourceSpan: null,
  21374. nodeFlags: 1 /* TypeElement */,
  21375. nodeDef: importExpr(Identifiers.anchorDef).callFn([
  21376. literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
  21377. ])
  21378. }));
  21379. }
  21380. }
  21381. build(targetStatements = []) {
  21382. this.children.forEach((child) => child.build(targetStatements));
  21383. const { updateRendererStmts, updateDirectivesStmts, nodeDefExprs } = this._createNodeExpressions();
  21384. const updateRendererFn = this._createUpdateFn(updateRendererStmts);
  21385. const updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
  21386. let viewFlags = 0 /* None */;
  21387. if (!this.parent && this.component.changeDetection === ChangeDetectionStrategy.OnPush) {
  21388. viewFlags |= 2 /* OnPush */;
  21389. }
  21390. const viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(LOG_VAR$1.name)], [new ReturnStatement(importExpr(Identifiers.viewDef).callFn([
  21391. literal(viewFlags),
  21392. literalArr(nodeDefExprs),
  21393. updateDirectivesFn,
  21394. updateRendererFn,
  21395. ]))], importType(Identifiers.ViewDefinition), this.embeddedViewIndex === 0 ? [StmtModifier.Exported] : []);
  21396. targetStatements.push(viewFactory);
  21397. return targetStatements;
  21398. }
  21399. _createUpdateFn(updateStmts) {
  21400. let updateFn;
  21401. if (updateStmts.length > 0) {
  21402. const preStmts = [];
  21403. if (!this.component.isHost && findReadVarNames(updateStmts).has(COMP_VAR.name)) {
  21404. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  21405. }
  21406. updateFn = fn([
  21407. new FnParam(CHECK_VAR.name, INFERRED_TYPE),
  21408. new FnParam(VIEW_VAR.name, INFERRED_TYPE)
  21409. ], [...preStmts, ...updateStmts], INFERRED_TYPE);
  21410. }
  21411. else {
  21412. updateFn = NULL_EXPR;
  21413. }
  21414. return updateFn;
  21415. }
  21416. visitNgContent(ast, context) {
  21417. // ngContentDef(ngContentIndex: number, index: number): NodeDef;
  21418. this.nodes.push(() => ({
  21419. sourceSpan: ast.sourceSpan,
  21420. nodeFlags: 8 /* TypeNgContent */,
  21421. nodeDef: importExpr(Identifiers.ngContentDef).callFn([
  21422. literal(ast.ngContentIndex), literal(ast.index)
  21423. ])
  21424. }));
  21425. }
  21426. visitText(ast, context) {
  21427. // Static text nodes have no check function
  21428. const checkIndex = -1;
  21429. this.nodes.push(() => ({
  21430. sourceSpan: ast.sourceSpan,
  21431. nodeFlags: 2 /* TypeText */,
  21432. nodeDef: importExpr(Identifiers.textDef).callFn([
  21433. literal(checkIndex),
  21434. literal(ast.ngContentIndex),
  21435. literalArr([literal(ast.value)]),
  21436. ])
  21437. }));
  21438. }
  21439. visitBoundText(ast, context) {
  21440. const nodeIndex = this.nodes.length;
  21441. // reserve the space in the nodeDefs array
  21442. this.nodes.push(null);
  21443. const astWithSource = ast.value;
  21444. const inter = astWithSource.ast;
  21445. const updateRendererExpressions = inter.expressions.map((expr, bindingIndex) => this._preprocessUpdateExpression({ nodeIndex, bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }));
  21446. // Check index is the same as the node index during compilation
  21447. // They might only differ at runtime
  21448. const checkIndex = nodeIndex;
  21449. this.nodes[nodeIndex] = () => ({
  21450. sourceSpan: ast.sourceSpan,
  21451. nodeFlags: 2 /* TypeText */,
  21452. nodeDef: importExpr(Identifiers.textDef).callFn([
  21453. literal(checkIndex),
  21454. literal(ast.ngContentIndex),
  21455. literalArr(inter.strings.map(s => literal(s))),
  21456. ]),
  21457. updateRenderer: updateRendererExpressions
  21458. });
  21459. }
  21460. visitEmbeddedTemplate(ast, context) {
  21461. const nodeIndex = this.nodes.length;
  21462. // reserve the space in the nodeDefs array
  21463. this.nodes.push(null);
  21464. const { flags, queryMatchesExpr, hostEvents } = this._visitElementOrTemplate(nodeIndex, ast);
  21465. const childVisitor = this.viewBuilderFactory(this);
  21466. this.children.push(childVisitor);
  21467. childVisitor.visitAll(ast.variables, ast.children);
  21468. const childCount = this.nodes.length - nodeIndex - 1;
  21469. // anchorDef(
  21470. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
  21471. // childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
  21472. // ViewDefinitionFactory): NodeDef;
  21473. this.nodes[nodeIndex] = () => ({
  21474. sourceSpan: ast.sourceSpan,
  21475. nodeFlags: 1 /* TypeElement */ | flags,
  21476. nodeDef: importExpr(Identifiers.anchorDef).callFn([
  21477. literal(flags),
  21478. queryMatchesExpr,
  21479. literal(ast.ngContentIndex),
  21480. literal(childCount),
  21481. this._createElementHandleEventFn(nodeIndex, hostEvents),
  21482. variable(childVisitor.viewName),
  21483. ])
  21484. });
  21485. }
  21486. visitElement(ast, context) {
  21487. const nodeIndex = this.nodes.length;
  21488. // reserve the space in the nodeDefs array so we can add children
  21489. this.nodes.push(null);
  21490. // Using a null element name creates an anchor.
  21491. const elName = isNgContainer(ast.name) ? null : ast.name;
  21492. const { flags, usedEvents, queryMatchesExpr, hostBindings: dirHostBindings, hostEvents } = this._visitElementOrTemplate(nodeIndex, ast);
  21493. let inputDefs = [];
  21494. let updateRendererExpressions = [];
  21495. let outputDefs = [];
  21496. if (elName) {
  21497. const hostBindings = ast.inputs
  21498. .map((inputAst) => ({
  21499. context: COMP_VAR,
  21500. inputAst,
  21501. dirAst: null,
  21502. }))
  21503. .concat(dirHostBindings);
  21504. if (hostBindings.length) {
  21505. updateRendererExpressions =
  21506. hostBindings.map((hostBinding, bindingIndex) => this._preprocessUpdateExpression({
  21507. context: hostBinding.context,
  21508. nodeIndex,
  21509. bindingIndex,
  21510. sourceSpan: hostBinding.inputAst.sourceSpan,
  21511. value: hostBinding.inputAst.value
  21512. }));
  21513. inputDefs = hostBindings.map(hostBinding => elementBindingDef(hostBinding.inputAst, hostBinding.dirAst));
  21514. }
  21515. outputDefs = usedEvents.map(([target, eventName]) => literalArr([literal(target), literal(eventName)]));
  21516. }
  21517. templateVisitAll(this, ast.children);
  21518. const childCount = this.nodes.length - nodeIndex - 1;
  21519. const compAst = ast.directives.find(dirAst => dirAst.directive.isComponent);
  21520. let compRendererType = NULL_EXPR;
  21521. let compView = NULL_EXPR;
  21522. if (compAst) {
  21523. compView = this.outputCtx.importExpr(compAst.directive.componentViewType);
  21524. compRendererType = this.outputCtx.importExpr(compAst.directive.rendererType);
  21525. }
  21526. // Check index is the same as the node index during compilation
  21527. // They might only differ at runtime
  21528. const checkIndex = nodeIndex;
  21529. this.nodes[nodeIndex] = () => ({
  21530. sourceSpan: ast.sourceSpan,
  21531. nodeFlags: 1 /* TypeElement */ | flags,
  21532. nodeDef: importExpr(Identifiers.elementDef).callFn([
  21533. literal(checkIndex),
  21534. literal(flags),
  21535. queryMatchesExpr,
  21536. literal(ast.ngContentIndex),
  21537. literal(childCount),
  21538. literal(elName),
  21539. elName ? fixedAttrsDef(ast) : NULL_EXPR,
  21540. inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
  21541. outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
  21542. this._createElementHandleEventFn(nodeIndex, hostEvents),
  21543. compView,
  21544. compRendererType,
  21545. ]),
  21546. updateRenderer: updateRendererExpressions
  21547. });
  21548. }
  21549. _visitElementOrTemplate(nodeIndex, ast) {
  21550. let flags = 0 /* None */;
  21551. if (ast.hasViewContainer) {
  21552. flags |= 16777216 /* EmbeddedViews */;
  21553. }
  21554. const usedEvents = new Map();
  21555. ast.outputs.forEach((event) => {
  21556. const { name, target } = elementEventNameAndTarget(event, null);
  21557. usedEvents.set(elementEventFullName(target, name), [target, name]);
  21558. });
  21559. ast.directives.forEach((dirAst) => {
  21560. dirAst.hostEvents.forEach((event) => {
  21561. const { name, target } = elementEventNameAndTarget(event, dirAst);
  21562. usedEvents.set(elementEventFullName(target, name), [target, name]);
  21563. });
  21564. });
  21565. const hostBindings = [];
  21566. const hostEvents = [];
  21567. this._visitComponentFactoryResolverProvider(ast.directives);
  21568. ast.providers.forEach((providerAst, providerIndex) => {
  21569. let dirAst = undefined;
  21570. let dirIndex = undefined;
  21571. ast.directives.forEach((localDirAst, i) => {
  21572. if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
  21573. dirAst = localDirAst;
  21574. dirIndex = i;
  21575. }
  21576. });
  21577. if (dirAst) {
  21578. const { hostBindings: dirHostBindings, hostEvents: dirHostEvents } = this._visitDirective(providerAst, dirAst, dirIndex, nodeIndex, ast.references, ast.queryMatches, usedEvents, this.staticQueryIds.get(ast));
  21579. hostBindings.push(...dirHostBindings);
  21580. hostEvents.push(...dirHostEvents);
  21581. }
  21582. else {
  21583. this._visitProvider(providerAst, ast.queryMatches);
  21584. }
  21585. });
  21586. let queryMatchExprs = [];
  21587. ast.queryMatches.forEach((match) => {
  21588. let valueType = undefined;
  21589. if (tokenReference(match.value) ===
  21590. this.reflector.resolveExternalReference(Identifiers.ElementRef)) {
  21591. valueType = 0 /* ElementRef */;
  21592. }
  21593. else if (tokenReference(match.value) ===
  21594. this.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  21595. valueType = 3 /* ViewContainerRef */;
  21596. }
  21597. else if (tokenReference(match.value) ===
  21598. this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  21599. valueType = 2 /* TemplateRef */;
  21600. }
  21601. if (valueType != null) {
  21602. queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
  21603. }
  21604. });
  21605. ast.references.forEach((ref) => {
  21606. let valueType = undefined;
  21607. if (!ref.value) {
  21608. valueType = 1 /* RenderElement */;
  21609. }
  21610. else if (tokenReference(ref.value) ===
  21611. this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  21612. valueType = 2 /* TemplateRef */;
  21613. }
  21614. if (valueType != null) {
  21615. this.refNodeIndices[ref.name] = nodeIndex;
  21616. queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
  21617. }
  21618. });
  21619. ast.outputs.forEach((outputAst) => {
  21620. hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: null });
  21621. });
  21622. return {
  21623. flags,
  21624. usedEvents: Array.from(usedEvents.values()),
  21625. queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  21626. hostBindings,
  21627. hostEvents: hostEvents
  21628. };
  21629. }
  21630. _visitDirective(providerAst, dirAst, directiveIndex, elementNodeIndex, refs, queryMatches, usedEvents, queryIds) {
  21631. const nodeIndex = this.nodes.length;
  21632. // reserve the space in the nodeDefs array so we can add children
  21633. this.nodes.push(null);
  21634. dirAst.directive.queries.forEach((query, queryIndex) => {
  21635. const queryId = dirAst.contentQueryStartId + queryIndex;
  21636. const flags = 67108864 /* TypeContentQuery */ | calcStaticDynamicQueryFlags(queryIds, queryId, query);
  21637. const bindingType = query.first ? 0 /* First */ : 1 /* All */;
  21638. this.nodes.push(() => ({
  21639. sourceSpan: dirAst.sourceSpan,
  21640. nodeFlags: flags,
  21641. nodeDef: importExpr(Identifiers.queryDef).callFn([
  21642. literal(flags), literal(queryId),
  21643. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  21644. ]),
  21645. }));
  21646. });
  21647. // Note: the operation below might also create new nodeDefs,
  21648. // but we don't want them to be a child of a directive,
  21649. // as they might be a provider/pipe on their own.
  21650. // I.e. we only allow queries as children of directives nodes.
  21651. const childCount = this.nodes.length - nodeIndex - 1;
  21652. let { flags, queryMatchExprs, providerExpr, depsExpr } = this._visitProviderOrDirective(providerAst, queryMatches);
  21653. refs.forEach((ref) => {
  21654. if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
  21655. this.refNodeIndices[ref.name] = nodeIndex;
  21656. queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
  21657. }
  21658. });
  21659. if (dirAst.directive.isComponent) {
  21660. flags |= 32768 /* Component */;
  21661. }
  21662. const inputDefs = dirAst.inputs.map((inputAst, inputIndex) => {
  21663. const mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
  21664. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  21665. return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
  21666. });
  21667. const outputDefs = [];
  21668. const dirMeta = dirAst.directive;
  21669. Object.keys(dirMeta.outputs).forEach((propName) => {
  21670. const eventName = dirMeta.outputs[propName];
  21671. if (usedEvents.has(eventName)) {
  21672. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  21673. outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
  21674. }
  21675. });
  21676. let updateDirectiveExpressions = [];
  21677. if (dirAst.inputs.length || (flags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0) {
  21678. updateDirectiveExpressions =
  21679. dirAst.inputs.map((input, bindingIndex) => this._preprocessUpdateExpression({
  21680. nodeIndex,
  21681. bindingIndex,
  21682. sourceSpan: input.sourceSpan,
  21683. context: COMP_VAR,
  21684. value: input.value
  21685. }));
  21686. }
  21687. const dirContextExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  21688. const hostBindings = dirAst.hostProperties.map((inputAst) => ({
  21689. context: dirContextExpr,
  21690. dirAst,
  21691. inputAst,
  21692. }));
  21693. const hostEvents = dirAst.hostEvents.map((hostEventAst) => ({
  21694. context: dirContextExpr,
  21695. eventAst: hostEventAst, dirAst,
  21696. }));
  21697. // Check index is the same as the node index during compilation
  21698. // They might only differ at runtime
  21699. const checkIndex = nodeIndex;
  21700. this.nodes[nodeIndex] = () => ({
  21701. sourceSpan: dirAst.sourceSpan,
  21702. nodeFlags: 16384 /* TypeDirective */ | flags,
  21703. nodeDef: importExpr(Identifiers.directiveDef).callFn([
  21704. literal(checkIndex),
  21705. literal(flags),
  21706. queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  21707. literal(childCount),
  21708. providerExpr,
  21709. depsExpr,
  21710. inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
  21711. outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR,
  21712. ]),
  21713. updateDirectives: updateDirectiveExpressions,
  21714. directive: dirAst.directive.type,
  21715. });
  21716. return { hostBindings, hostEvents };
  21717. }
  21718. _visitProvider(providerAst, queryMatches) {
  21719. this._addProviderNode(this._visitProviderOrDirective(providerAst, queryMatches));
  21720. }
  21721. _visitComponentFactoryResolverProvider(directives) {
  21722. const componentDirMeta = directives.find(dirAst => dirAst.directive.isComponent);
  21723. if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
  21724. const { providerExpr, depsExpr, flags, tokenExpr } = componentFactoryResolverProviderDef(this.reflector, this.outputCtx, 8192 /* PrivateProvider */, componentDirMeta.directive.entryComponents);
  21725. this._addProviderNode({
  21726. providerExpr,
  21727. depsExpr,
  21728. flags,
  21729. tokenExpr,
  21730. queryMatchExprs: [],
  21731. sourceSpan: componentDirMeta.sourceSpan
  21732. });
  21733. }
  21734. }
  21735. _addProviderNode(data) {
  21736. const nodeIndex = this.nodes.length;
  21737. // providerDef(
  21738. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
  21739. // value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
  21740. this.nodes.push(() => ({
  21741. sourceSpan: data.sourceSpan,
  21742. nodeFlags: data.flags,
  21743. nodeDef: importExpr(Identifiers.providerDef).callFn([
  21744. literal(data.flags),
  21745. data.queryMatchExprs.length ? literalArr(data.queryMatchExprs) : NULL_EXPR,
  21746. data.tokenExpr, data.providerExpr, data.depsExpr
  21747. ])
  21748. }));
  21749. }
  21750. _visitProviderOrDirective(providerAst, queryMatches) {
  21751. let flags = 0 /* None */;
  21752. let queryMatchExprs = [];
  21753. queryMatches.forEach((match) => {
  21754. if (tokenReference(match.value) === tokenReference(providerAst.token)) {
  21755. queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
  21756. }
  21757. });
  21758. const { providerExpr, depsExpr, flags: providerFlags, tokenExpr } = providerDef(this.outputCtx, providerAst);
  21759. return {
  21760. flags: flags | providerFlags,
  21761. queryMatchExprs,
  21762. providerExpr,
  21763. depsExpr,
  21764. tokenExpr,
  21765. sourceSpan: providerAst.sourceSpan
  21766. };
  21767. }
  21768. getLocal(name) {
  21769. if (name == EventHandlerVars.event.name) {
  21770. return EventHandlerVars.event;
  21771. }
  21772. let currViewExpr = VIEW_VAR;
  21773. for (let currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
  21774. currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
  21775. // check references
  21776. const refNodeIndex = currBuilder.refNodeIndices[name];
  21777. if (refNodeIndex != null) {
  21778. return importExpr(Identifiers.nodeValue).callFn([currViewExpr, literal(refNodeIndex)]);
  21779. }
  21780. // check variables
  21781. const varAst = currBuilder.variables.find((varAst) => varAst.name === name);
  21782. if (varAst) {
  21783. const varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
  21784. return currViewExpr.prop('context').prop(varValue);
  21785. }
  21786. }
  21787. return null;
  21788. }
  21789. notifyImplicitReceiverUse() {
  21790. // Not needed in View Engine as View Engine walks through the generated
  21791. // expressions to figure out if the implicit receiver is used and needs
  21792. // to be generated as part of the pre-update statements.
  21793. }
  21794. _createLiteralArrayConverter(sourceSpan, argCount) {
  21795. if (argCount === 0) {
  21796. const valueExpr = importExpr(Identifiers.EMPTY_ARRAY);
  21797. return () => valueExpr;
  21798. }
  21799. const checkIndex = this.nodes.length;
  21800. this.nodes.push(() => ({
  21801. sourceSpan,
  21802. nodeFlags: 32 /* TypePureArray */,
  21803. nodeDef: importExpr(Identifiers.pureArrayDef).callFn([
  21804. literal(checkIndex),
  21805. literal(argCount),
  21806. ])
  21807. }));
  21808. return (args) => callCheckStmt(checkIndex, args);
  21809. }
  21810. _createLiteralMapConverter(sourceSpan, keys) {
  21811. if (keys.length === 0) {
  21812. const valueExpr = importExpr(Identifiers.EMPTY_MAP);
  21813. return () => valueExpr;
  21814. }
  21815. const map = literalMap(keys.map((e, i) => (Object.assign({}, e, { value: literal(i) }))));
  21816. const checkIndex = this.nodes.length;
  21817. this.nodes.push(() => ({
  21818. sourceSpan,
  21819. nodeFlags: 64 /* TypePureObject */,
  21820. nodeDef: importExpr(Identifiers.pureObjectDef).callFn([
  21821. literal(checkIndex),
  21822. map,
  21823. ])
  21824. }));
  21825. return (args) => callCheckStmt(checkIndex, args);
  21826. }
  21827. _createPipeConverter(expression, name, argCount) {
  21828. const pipe = this.usedPipes.find((pipeSummary) => pipeSummary.name === name);
  21829. if (pipe.pure) {
  21830. const checkIndex = this.nodes.length;
  21831. this.nodes.push(() => ({
  21832. sourceSpan: expression.sourceSpan,
  21833. nodeFlags: 128 /* TypePurePipe */,
  21834. nodeDef: importExpr(Identifiers.purePipeDef).callFn([
  21835. literal(checkIndex),
  21836. literal(argCount),
  21837. ])
  21838. }));
  21839. // find underlying pipe in the component view
  21840. let compViewExpr = VIEW_VAR;
  21841. let compBuilder = this;
  21842. while (compBuilder.parent) {
  21843. compBuilder = compBuilder.parent;
  21844. compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
  21845. }
  21846. const pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
  21847. const pipeValueExpr = importExpr(Identifiers.nodeValue).callFn([compViewExpr, literal(pipeNodeIndex)]);
  21848. return (args) => callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(checkIndex, [pipeValueExpr].concat(args)));
  21849. }
  21850. else {
  21851. const nodeIndex = this._createPipe(expression.sourceSpan, pipe);
  21852. const nodeValueExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  21853. return (args) => callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr.callMethod('transform', args));
  21854. }
  21855. }
  21856. _createPipe(sourceSpan, pipe) {
  21857. const nodeIndex = this.nodes.length;
  21858. let flags = 0 /* None */;
  21859. pipe.type.lifecycleHooks.forEach((lifecycleHook) => {
  21860. // for pipes, we only support ngOnDestroy
  21861. if (lifecycleHook === LifecycleHooks.OnDestroy) {
  21862. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  21863. }
  21864. });
  21865. const depExprs = pipe.type.diDeps.map((diDep) => depDef(this.outputCtx, diDep));
  21866. // function pipeDef(
  21867. // flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
  21868. this.nodes.push(() => ({
  21869. sourceSpan,
  21870. nodeFlags: 16 /* TypePipe */,
  21871. nodeDef: importExpr(Identifiers.pipeDef).callFn([
  21872. literal(flags), this.outputCtx.importExpr(pipe.type.reference), literalArr(depExprs)
  21873. ])
  21874. }));
  21875. return nodeIndex;
  21876. }
  21877. /**
  21878. * For the AST in `UpdateExpression.value`:
  21879. * - create nodes for pipes, literal arrays and, literal maps,
  21880. * - update the AST to replace pipes, literal arrays and, literal maps with calls to check fn.
  21881. *
  21882. * WARNING: This might create new nodeDefs (for pipes and literal arrays and literal maps)!
  21883. */
  21884. _preprocessUpdateExpression(expression) {
  21885. return {
  21886. nodeIndex: expression.nodeIndex,
  21887. bindingIndex: expression.bindingIndex,
  21888. sourceSpan: expression.sourceSpan,
  21889. context: expression.context,
  21890. value: convertPropertyBindingBuiltins({
  21891. createLiteralArrayConverter: (argCount) => this._createLiteralArrayConverter(expression.sourceSpan, argCount),
  21892. createLiteralMapConverter: (keys) => this._createLiteralMapConverter(expression.sourceSpan, keys),
  21893. createPipeConverter: (name, argCount) => this._createPipeConverter(expression, name, argCount)
  21894. }, expression.value)
  21895. };
  21896. }
  21897. _createNodeExpressions() {
  21898. const self = this;
  21899. let updateBindingCount = 0;
  21900. const updateRendererStmts = [];
  21901. const updateDirectivesStmts = [];
  21902. const nodeDefExprs = this.nodes.map((factory, nodeIndex) => {
  21903. const { nodeDef, nodeFlags, updateDirectives, updateRenderer, sourceSpan } = factory();
  21904. if (updateRenderer) {
  21905. updateRendererStmts.push(...createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false));
  21906. }
  21907. if (updateDirectives) {
  21908. updateDirectivesStmts.push(...createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0));
  21909. }
  21910. // We use a comma expression to call the log function before
  21911. // the nodeDef function, but still use the result of the nodeDef function
  21912. // as the value.
  21913. // Note: We only add the logger to elements / text nodes,
  21914. // so we don't generate too much code.
  21915. const logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
  21916. new CommaExpr([LOG_VAR$1.callFn([]).callFn([]), nodeDef]) :
  21917. nodeDef;
  21918. return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
  21919. });
  21920. return { updateRendererStmts, updateDirectivesStmts, nodeDefExprs };
  21921. function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
  21922. const updateStmts = [];
  21923. const exprs = expressions.map(({ sourceSpan, context, value }) => {
  21924. const bindingId = `${updateBindingCount++}`;
  21925. const nameResolver = context === COMP_VAR ? self : null;
  21926. const { stmts, currValExpr } = convertPropertyBinding(nameResolver, context, value, bindingId, BindingForm.General);
  21927. updateStmts.push(...stmts.map((stmt) => applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
  21928. return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
  21929. });
  21930. if (expressions.length || allowEmptyExprs) {
  21931. updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
  21932. }
  21933. return updateStmts;
  21934. }
  21935. }
  21936. _createElementHandleEventFn(nodeIndex, handlers) {
  21937. const handleEventStmts = [];
  21938. let handleEventBindingCount = 0;
  21939. handlers.forEach(({ context, eventAst, dirAst }) => {
  21940. const bindingId = `${handleEventBindingCount++}`;
  21941. const nameResolver = context === COMP_VAR ? this : null;
  21942. const { stmts, allowDefault } = convertActionBinding(nameResolver, context, eventAst.handler, bindingId);
  21943. const trueStmts = stmts;
  21944. if (allowDefault) {
  21945. trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
  21946. }
  21947. const { target: eventTarget, name: eventName } = elementEventNameAndTarget(eventAst, dirAst);
  21948. const fullEventName = elementEventFullName(eventTarget, eventName);
  21949. handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
  21950. });
  21951. let handleEventFn;
  21952. if (handleEventStmts.length > 0) {
  21953. const preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
  21954. if (!this.component.isHost && findReadVarNames(handleEventStmts).has(COMP_VAR.name)) {
  21955. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  21956. }
  21957. handleEventFn = fn([
  21958. new FnParam(VIEW_VAR.name, INFERRED_TYPE),
  21959. new FnParam(EVENT_NAME_VAR.name, INFERRED_TYPE),
  21960. new FnParam(EventHandlerVars.event.name, INFERRED_TYPE)
  21961. ], [...preStmts, ...handleEventStmts, new ReturnStatement(ALLOW_DEFAULT_VAR)], INFERRED_TYPE);
  21962. }
  21963. else {
  21964. handleEventFn = NULL_EXPR;
  21965. }
  21966. return handleEventFn;
  21967. }
  21968. visitDirective(ast, context) { }
  21969. visitDirectiveProperty(ast, context) { }
  21970. visitReference(ast, context) { }
  21971. visitVariable(ast, context) { }
  21972. visitEvent(ast, context) { }
  21973. visitElementProperty(ast, context) { }
  21974. visitAttr(ast, context) { }
  21975. }
  21976. function needsAdditionalRootNode(astNodes) {
  21977. const lastAstNode = astNodes[astNodes.length - 1];
  21978. if (lastAstNode instanceof EmbeddedTemplateAst) {
  21979. return lastAstNode.hasViewContainer;
  21980. }
  21981. if (lastAstNode instanceof ElementAst) {
  21982. if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
  21983. return needsAdditionalRootNode(lastAstNode.children);
  21984. }
  21985. return lastAstNode.hasViewContainer;
  21986. }
  21987. return lastAstNode instanceof NgContentAst;
  21988. }
  21989. function elementBindingDef(inputAst, dirAst) {
  21990. const inputType = inputAst.type;
  21991. switch (inputType) {
  21992. case 1 /* Attribute */:
  21993. return literalArr([
  21994. literal(1 /* TypeElementAttribute */), literal(inputAst.name),
  21995. literal(inputAst.securityContext)
  21996. ]);
  21997. case 0 /* Property */:
  21998. return literalArr([
  21999. literal(8 /* TypeProperty */), literal(inputAst.name),
  22000. literal(inputAst.securityContext)
  22001. ]);
  22002. case 4 /* Animation */:
  22003. const bindingType = 8 /* TypeProperty */ |
  22004. (dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
  22005. 16 /* SyntheticProperty */);
  22006. return literalArr([
  22007. literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
  22008. ]);
  22009. case 2 /* Class */:
  22010. return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
  22011. case 3 /* Style */:
  22012. return literalArr([
  22013. literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
  22014. ]);
  22015. default:
  22016. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  22017. // However Closure Compiler does not understand that and reports an error in typed mode.
  22018. // The `throw new Error` below works around the problem, and the unexpected: never variable
  22019. // makes sure tsc still checks this code is unreachable.
  22020. const unexpected = inputType;
  22021. throw new Error(`unexpected ${unexpected}`);
  22022. }
  22023. }
  22024. function fixedAttrsDef(elementAst) {
  22025. const mapResult = Object.create(null);
  22026. elementAst.attrs.forEach(attrAst => { mapResult[attrAst.name] = attrAst.value; });
  22027. elementAst.directives.forEach(dirAst => {
  22028. Object.keys(dirAst.directive.hostAttributes).forEach(name => {
  22029. const value = dirAst.directive.hostAttributes[name];
  22030. const prevValue = mapResult[name];
  22031. mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
  22032. });
  22033. });
  22034. // Note: We need to sort to get a defined output order
  22035. // for tests and for caching generated artifacts...
  22036. return literalArr(Object.keys(mapResult).sort().map((attrName) => literalArr([literal(attrName), literal(mapResult[attrName])])));
  22037. }
  22038. function mergeAttributeValue(attrName, attrValue1, attrValue2) {
  22039. if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
  22040. return `${attrValue1} ${attrValue2}`;
  22041. }
  22042. else {
  22043. return attrValue2;
  22044. }
  22045. }
  22046. function callCheckStmt(nodeIndex, exprs) {
  22047. if (exprs.length > 10) {
  22048. return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
  22049. }
  22050. else {
  22051. return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */), ...exprs]);
  22052. }
  22053. }
  22054. function callUnwrapValue(nodeIndex, bindingIdx, expr) {
  22055. return importExpr(Identifiers.unwrapValue).callFn([
  22056. VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
  22057. ]);
  22058. }
  22059. function findStaticQueryIds(nodes, result = new Map()) {
  22060. nodes.forEach((node) => {
  22061. const staticQueryIds = new Set();
  22062. const dynamicQueryIds = new Set();
  22063. let queryMatches = undefined;
  22064. if (node instanceof ElementAst) {
  22065. findStaticQueryIds(node.children, result);
  22066. node.children.forEach((child) => {
  22067. const childData = result.get(child);
  22068. childData.staticQueryIds.forEach(queryId => staticQueryIds.add(queryId));
  22069. childData.dynamicQueryIds.forEach(queryId => dynamicQueryIds.add(queryId));
  22070. });
  22071. queryMatches = node.queryMatches;
  22072. }
  22073. else if (node instanceof EmbeddedTemplateAst) {
  22074. findStaticQueryIds(node.children, result);
  22075. node.children.forEach((child) => {
  22076. const childData = result.get(child);
  22077. childData.staticQueryIds.forEach(queryId => dynamicQueryIds.add(queryId));
  22078. childData.dynamicQueryIds.forEach(queryId => dynamicQueryIds.add(queryId));
  22079. });
  22080. queryMatches = node.queryMatches;
  22081. }
  22082. if (queryMatches) {
  22083. queryMatches.forEach((match) => staticQueryIds.add(match.queryId));
  22084. }
  22085. dynamicQueryIds.forEach(queryId => staticQueryIds.delete(queryId));
  22086. result.set(node, { staticQueryIds, dynamicQueryIds });
  22087. });
  22088. return result;
  22089. }
  22090. function staticViewQueryIds(nodeStaticQueryIds) {
  22091. const staticQueryIds = new Set();
  22092. const dynamicQueryIds = new Set();
  22093. Array.from(nodeStaticQueryIds.values()).forEach((entry) => {
  22094. entry.staticQueryIds.forEach(queryId => staticQueryIds.add(queryId));
  22095. entry.dynamicQueryIds.forEach(queryId => dynamicQueryIds.add(queryId));
  22096. });
  22097. dynamicQueryIds.forEach(queryId => staticQueryIds.delete(queryId));
  22098. return { staticQueryIds, dynamicQueryIds };
  22099. }
  22100. function elementEventNameAndTarget(eventAst, dirAst) {
  22101. if (eventAst.isAnimation) {
  22102. return {
  22103. name: `@${eventAst.name}.${eventAst.phase}`,
  22104. target: dirAst && dirAst.directive.isComponent ? 'component' : null
  22105. };
  22106. }
  22107. else {
  22108. return eventAst;
  22109. }
  22110. }
  22111. function calcStaticDynamicQueryFlags(queryIds, queryId, query) {
  22112. let flags = 0 /* None */;
  22113. // Note: We only make queries static that query for a single item.
  22114. // This is because of backwards compatibility with the old view compiler...
  22115. if (query.first && shouldResolveAsStaticQuery(queryIds, queryId, query)) {
  22116. flags |= 268435456 /* StaticQuery */;
  22117. }
  22118. else {
  22119. flags |= 536870912 /* DynamicQuery */;
  22120. }
  22121. return flags;
  22122. }
  22123. function shouldResolveAsStaticQuery(queryIds, queryId, query) {
  22124. // If query.static has been set by the user, use that value to determine whether
  22125. // the query is static. If none has been set, sort the query into static/dynamic
  22126. // based on query results (i.e. dynamic if CD needs to run to get all results).
  22127. return query.static ||
  22128. query.static == null &&
  22129. (queryIds.staticQueryIds.has(queryId) || !queryIds.dynamicQueryIds.has(queryId));
  22130. }
  22131. function elementEventFullName(target, name) {
  22132. return target ? `${target}:${name}` : name;
  22133. }
  22134. /**
  22135. * @license
  22136. * Copyright Google Inc. All Rights Reserved.
  22137. *
  22138. * Use of this source code is governed by an MIT-style license that can be
  22139. * found in the LICENSE file at https://angular.io/license
  22140. */
  22141. /**
  22142. * A container for message extracted from the templates.
  22143. */
  22144. class MessageBundle {
  22145. constructor(_htmlParser, _implicitTags, _implicitAttrs, _locale = null) {
  22146. this._htmlParser = _htmlParser;
  22147. this._implicitTags = _implicitTags;
  22148. this._implicitAttrs = _implicitAttrs;
  22149. this._locale = _locale;
  22150. this._messages = [];
  22151. }
  22152. updateFromTemplate(html, url, interpolationConfig) {
  22153. const htmlParserResult = this._htmlParser.parse(html, url, { tokenizeExpansionForms: true, interpolationConfig });
  22154. if (htmlParserResult.errors.length) {
  22155. return htmlParserResult.errors;
  22156. }
  22157. const i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
  22158. if (i18nParserResult.errors.length) {
  22159. return i18nParserResult.errors;
  22160. }
  22161. this._messages.push(...i18nParserResult.messages);
  22162. return [];
  22163. }
  22164. // Return the message in the internal format
  22165. // The public (serialized) format might be different, see the `write` method.
  22166. getMessages() { return this._messages; }
  22167. write(serializer, filterSources) {
  22168. const messages = {};
  22169. const mapperVisitor = new MapPlaceholderNames();
  22170. // Deduplicate messages based on their ID
  22171. this._messages.forEach(message => {
  22172. const id = serializer.digest(message);
  22173. if (!messages.hasOwnProperty(id)) {
  22174. messages[id] = message;
  22175. }
  22176. else {
  22177. messages[id].sources.push(...message.sources);
  22178. }
  22179. });
  22180. // Transform placeholder names using the serializer mapping
  22181. const msgList = Object.keys(messages).map(id => {
  22182. const mapper = serializer.createNameMapper(messages[id]);
  22183. const src = messages[id];
  22184. const nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
  22185. let transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
  22186. transformedMessage.sources = src.sources;
  22187. if (filterSources) {
  22188. transformedMessage.sources.forEach((source) => source.filePath = filterSources(source.filePath));
  22189. }
  22190. return transformedMessage;
  22191. });
  22192. return serializer.write(msgList, this._locale);
  22193. }
  22194. }
  22195. // Transform an i18n AST by renaming the placeholder nodes with the given mapper
  22196. class MapPlaceholderNames extends CloneVisitor {
  22197. convert(nodes, mapper) {
  22198. return mapper ? nodes.map(n => n.visit(this, mapper)) : nodes;
  22199. }
  22200. visitTagPlaceholder(ph, mapper) {
  22201. const startName = mapper.toPublicName(ph.startName);
  22202. const closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
  22203. const children = ph.children.map(n => n.visit(this, mapper));
  22204. return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan);
  22205. }
  22206. visitPlaceholder(ph, mapper) {
  22207. return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  22208. }
  22209. visitIcuPlaceholder(ph, mapper) {
  22210. return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  22211. }
  22212. }
  22213. /**
  22214. * @license
  22215. * Copyright Google Inc. All Rights Reserved.
  22216. *
  22217. * Use of this source code is governed by an MIT-style license that can be
  22218. * found in the LICENSE file at https://angular.io/license
  22219. */
  22220. class GeneratedFile {
  22221. constructor(srcFileUrl, genFileUrl, sourceOrStmts) {
  22222. this.srcFileUrl = srcFileUrl;
  22223. this.genFileUrl = genFileUrl;
  22224. if (typeof sourceOrStmts === 'string') {
  22225. this.source = sourceOrStmts;
  22226. this.stmts = null;
  22227. }
  22228. else {
  22229. this.source = null;
  22230. this.stmts = sourceOrStmts;
  22231. }
  22232. }
  22233. isEquivalent(other) {
  22234. if (this.genFileUrl !== other.genFileUrl) {
  22235. return false;
  22236. }
  22237. if (this.source) {
  22238. return this.source === other.source;
  22239. }
  22240. if (other.stmts == null) {
  22241. return false;
  22242. }
  22243. // Note: the constructor guarantees that if this.source is not filled,
  22244. // then this.stmts is.
  22245. return areAllEquivalent(this.stmts, other.stmts);
  22246. }
  22247. }
  22248. function toTypeScript(file, preamble = '') {
  22249. if (!file.stmts) {
  22250. throw new Error(`Illegal state: No stmts present on GeneratedFile ${file.genFileUrl}`);
  22251. }
  22252. return new TypeScriptEmitter().emitStatements(file.genFileUrl, file.stmts, preamble);
  22253. }
  22254. /**
  22255. * @license
  22256. * Copyright Google Inc. All Rights Reserved.
  22257. *
  22258. * Use of this source code is governed by an MIT-style license that can be
  22259. * found in the LICENSE file at https://angular.io/license
  22260. */
  22261. function listLazyRoutes(moduleMeta, reflector) {
  22262. const allLazyRoutes = [];
  22263. for (const { provider, module } of moduleMeta.transitiveModule.providers) {
  22264. if (tokenReference(provider.token) === reflector.ROUTES) {
  22265. const loadChildren = _collectLoadChildren(provider.useValue);
  22266. for (const route of loadChildren) {
  22267. allLazyRoutes.push(parseLazyRoute(route, reflector, module.reference));
  22268. }
  22269. }
  22270. }
  22271. return allLazyRoutes;
  22272. }
  22273. function _collectLoadChildren(routes, target = []) {
  22274. if (typeof routes === 'string') {
  22275. target.push(routes);
  22276. }
  22277. else if (Array.isArray(routes)) {
  22278. for (const route of routes) {
  22279. _collectLoadChildren(route, target);
  22280. }
  22281. }
  22282. else if (routes.loadChildren) {
  22283. _collectLoadChildren(routes.loadChildren, target);
  22284. }
  22285. else if (routes.children) {
  22286. _collectLoadChildren(routes.children, target);
  22287. }
  22288. return target;
  22289. }
  22290. function parseLazyRoute(route, reflector, module) {
  22291. const [routePath, routeName] = route.split('#');
  22292. const referencedModule = reflector.resolveExternalReference({
  22293. moduleName: routePath,
  22294. name: routeName,
  22295. }, module ? module.filePath : undefined);
  22296. return { route: route, module: module || referencedModule, referencedModule };
  22297. }
  22298. /**
  22299. * @license
  22300. * Copyright Google Inc. All Rights Reserved.
  22301. *
  22302. * Use of this source code is governed by an MIT-style license that can be
  22303. * found in the LICENSE file at https://angular.io/license
  22304. */
  22305. const TS = /^(?!.*\.d\.ts$).*\.ts$/;
  22306. class ResolvedStaticSymbol {
  22307. constructor(symbol, metadata) {
  22308. this.symbol = symbol;
  22309. this.metadata = metadata;
  22310. }
  22311. }
  22312. const SUPPORTED_SCHEMA_VERSION = 4;
  22313. /**
  22314. * This class is responsible for loading metadata per symbol,
  22315. * and normalizing references between symbols.
  22316. *
  22317. * Internally, it only uses symbols without members,
  22318. * and deduces the values for symbols with members based
  22319. * on these symbols.
  22320. */
  22321. class StaticSymbolResolver {
  22322. constructor(host, staticSymbolCache, summaryResolver, errorRecorder) {
  22323. this.host = host;
  22324. this.staticSymbolCache = staticSymbolCache;
  22325. this.summaryResolver = summaryResolver;
  22326. this.errorRecorder = errorRecorder;
  22327. this.metadataCache = new Map();
  22328. // Note: this will only contain StaticSymbols without members!
  22329. this.resolvedSymbols = new Map();
  22330. this.resolvedFilePaths = new Set();
  22331. // Note: this will only contain StaticSymbols without members!
  22332. this.importAs = new Map();
  22333. this.symbolResourcePaths = new Map();
  22334. this.symbolFromFile = new Map();
  22335. this.knownFileNameToModuleNames = new Map();
  22336. }
  22337. resolveSymbol(staticSymbol) {
  22338. if (staticSymbol.members.length > 0) {
  22339. return this._resolveSymbolMembers(staticSymbol);
  22340. }
  22341. // Note: always ask for a summary first,
  22342. // as we might have read shallow metadata via a .d.ts file
  22343. // for the symbol.
  22344. const resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
  22345. if (resultFromSummary) {
  22346. return resultFromSummary;
  22347. }
  22348. const resultFromCache = this.resolvedSymbols.get(staticSymbol);
  22349. if (resultFromCache) {
  22350. return resultFromCache;
  22351. }
  22352. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  22353. // have summaries, only .d.ts files. So we always need to check both, the summary
  22354. // and metadata.
  22355. this._createSymbolsOf(staticSymbol.filePath);
  22356. return this.resolvedSymbols.get(staticSymbol);
  22357. }
  22358. /**
  22359. * getImportAs produces a symbol that can be used to import the given symbol.
  22360. * The import might be different than the symbol if the symbol is exported from
  22361. * a library with a summary; in which case we want to import the symbol from the
  22362. * ngfactory re-export instead of directly to avoid introducing a direct dependency
  22363. * on an otherwise indirect dependency.
  22364. *
  22365. * @param staticSymbol the symbol for which to generate a import symbol
  22366. */
  22367. getImportAs(staticSymbol, useSummaries = true) {
  22368. if (staticSymbol.members.length) {
  22369. const baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
  22370. const baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  22371. return baseImportAs ?
  22372. this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
  22373. null;
  22374. }
  22375. const summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
  22376. if (summarizedFileName !== staticSymbol.filePath) {
  22377. const summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
  22378. const baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
  22379. const baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  22380. return baseImportAs ?
  22381. this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
  22382. null;
  22383. }
  22384. let result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
  22385. if (!result) {
  22386. result = this.importAs.get(staticSymbol);
  22387. }
  22388. return result;
  22389. }
  22390. /**
  22391. * getResourcePath produces the path to the original location of the symbol and should
  22392. * be used to determine the relative location of resource references recorded in
  22393. * symbol metadata.
  22394. */
  22395. getResourcePath(staticSymbol) {
  22396. return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
  22397. }
  22398. /**
  22399. * getTypeArity returns the number of generic type parameters the given symbol
  22400. * has. If the symbol is not a type the result is null.
  22401. */
  22402. getTypeArity(staticSymbol) {
  22403. // If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
  22404. // cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
  22405. // All references to generated classes must include the correct arity whenever
  22406. // generating code.
  22407. if (isGeneratedFile(staticSymbol.filePath)) {
  22408. return null;
  22409. }
  22410. let resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
  22411. while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
  22412. resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
  22413. }
  22414. return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
  22415. }
  22416. getKnownModuleName(filePath) {
  22417. return this.knownFileNameToModuleNames.get(filePath) || null;
  22418. }
  22419. recordImportAs(sourceSymbol, targetSymbol) {
  22420. sourceSymbol.assertNoMembers();
  22421. targetSymbol.assertNoMembers();
  22422. this.importAs.set(sourceSymbol, targetSymbol);
  22423. }
  22424. recordModuleNameForFileName(fileName, moduleName) {
  22425. this.knownFileNameToModuleNames.set(fileName, moduleName);
  22426. }
  22427. /**
  22428. * Invalidate all information derived from the given file.
  22429. *
  22430. * @param fileName the file to invalidate
  22431. */
  22432. invalidateFile(fileName) {
  22433. this.metadataCache.delete(fileName);
  22434. this.resolvedFilePaths.delete(fileName);
  22435. const symbols = this.symbolFromFile.get(fileName);
  22436. if (symbols) {
  22437. this.symbolFromFile.delete(fileName);
  22438. for (const symbol of symbols) {
  22439. this.resolvedSymbols.delete(symbol);
  22440. this.importAs.delete(symbol);
  22441. this.symbolResourcePaths.delete(symbol);
  22442. }
  22443. }
  22444. }
  22445. /** @internal */
  22446. ignoreErrorsFor(cb) {
  22447. const recorder = this.errorRecorder;
  22448. this.errorRecorder = () => { };
  22449. try {
  22450. return cb();
  22451. }
  22452. finally {
  22453. this.errorRecorder = recorder;
  22454. }
  22455. }
  22456. _resolveSymbolMembers(staticSymbol) {
  22457. const members = staticSymbol.members;
  22458. const baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
  22459. if (!baseResolvedSymbol) {
  22460. return null;
  22461. }
  22462. let baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
  22463. if (baseMetadata instanceof StaticSymbol) {
  22464. return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
  22465. }
  22466. else if (baseMetadata && baseMetadata.__symbolic === 'class') {
  22467. if (baseMetadata.statics && members.length === 1) {
  22468. return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
  22469. }
  22470. }
  22471. else {
  22472. let value = baseMetadata;
  22473. for (let i = 0; i < members.length && value; i++) {
  22474. value = value[members[i]];
  22475. }
  22476. return new ResolvedStaticSymbol(staticSymbol, value);
  22477. }
  22478. return null;
  22479. }
  22480. _resolveSymbolFromSummary(staticSymbol) {
  22481. const summary = this.summaryResolver.resolveSummary(staticSymbol);
  22482. return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
  22483. }
  22484. /**
  22485. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  22486. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  22487. *
  22488. * @param declarationFile the absolute path of the file where the symbol is declared
  22489. * @param name the name of the type.
  22490. * @param members a symbol for a static member of the named type
  22491. */
  22492. getStaticSymbol(declarationFile, name, members) {
  22493. return this.staticSymbolCache.get(declarationFile, name, members);
  22494. }
  22495. /**
  22496. * hasDecorators checks a file's metadata for the presence of decorators without evaluating the
  22497. * metadata.
  22498. *
  22499. * @param filePath the absolute path to examine for decorators.
  22500. * @returns true if any class in the file has a decorator.
  22501. */
  22502. hasDecorators(filePath) {
  22503. const metadata = this.getModuleMetadata(filePath);
  22504. if (metadata['metadata']) {
  22505. return Object.keys(metadata['metadata']).some((metadataKey) => {
  22506. const entry = metadata['metadata'][metadataKey];
  22507. return entry && entry.__symbolic === 'class' && entry.decorators;
  22508. });
  22509. }
  22510. return false;
  22511. }
  22512. getSymbolsOf(filePath) {
  22513. const summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
  22514. if (summarySymbols) {
  22515. return summarySymbols;
  22516. }
  22517. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  22518. // have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
  22519. this._createSymbolsOf(filePath);
  22520. const metadataSymbols = [];
  22521. this.resolvedSymbols.forEach((resolvedSymbol) => {
  22522. if (resolvedSymbol.symbol.filePath === filePath) {
  22523. metadataSymbols.push(resolvedSymbol.symbol);
  22524. }
  22525. });
  22526. return metadataSymbols;
  22527. }
  22528. _createSymbolsOf(filePath) {
  22529. if (this.resolvedFilePaths.has(filePath)) {
  22530. return;
  22531. }
  22532. this.resolvedFilePaths.add(filePath);
  22533. const resolvedSymbols = [];
  22534. const metadata = this.getModuleMetadata(filePath);
  22535. if (metadata['importAs']) {
  22536. // Index bundle indices should use the importAs module name defined
  22537. // in the bundle.
  22538. this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
  22539. }
  22540. // handle the symbols in one of the re-export location
  22541. if (metadata['exports']) {
  22542. for (const moduleExport of metadata['exports']) {
  22543. // handle the symbols in the list of explicitly re-exported symbols.
  22544. if (moduleExport.export) {
  22545. moduleExport.export.forEach((exportSymbol) => {
  22546. let symbolName;
  22547. if (typeof exportSymbol === 'string') {
  22548. symbolName = exportSymbol;
  22549. }
  22550. else {
  22551. symbolName = exportSymbol.as;
  22552. }
  22553. symbolName = unescapeIdentifier(symbolName);
  22554. let symName = symbolName;
  22555. if (typeof exportSymbol !== 'string') {
  22556. symName = unescapeIdentifier(exportSymbol.name);
  22557. }
  22558. const resolvedModule = this.resolveModule(moduleExport.from, filePath);
  22559. if (resolvedModule) {
  22560. const targetSymbol = this.getStaticSymbol(resolvedModule, symName);
  22561. const sourceSymbol = this.getStaticSymbol(filePath, symbolName);
  22562. resolvedSymbols.push(this.createExport(sourceSymbol, targetSymbol));
  22563. }
  22564. });
  22565. }
  22566. else {
  22567. // handle the symbols via export * directives.
  22568. const resolvedModule = this.resolveModule(moduleExport.from, filePath);
  22569. if (resolvedModule) {
  22570. const nestedExports = this.getSymbolsOf(resolvedModule);
  22571. nestedExports.forEach((targetSymbol) => {
  22572. const sourceSymbol = this.getStaticSymbol(filePath, targetSymbol.name);
  22573. resolvedSymbols.push(this.createExport(sourceSymbol, targetSymbol));
  22574. });
  22575. }
  22576. }
  22577. }
  22578. }
  22579. // handle the actual metadata. Has to be after the exports
  22580. // as there might be collisions in the names, and we want the symbols
  22581. // of the current module to win ofter reexports.
  22582. if (metadata['metadata']) {
  22583. // handle direct declarations of the symbol
  22584. const topLevelSymbolNames = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
  22585. const origins = metadata['origins'] || {};
  22586. Object.keys(metadata['metadata']).forEach((metadataKey) => {
  22587. const symbolMeta = metadata['metadata'][metadataKey];
  22588. const name = unescapeIdentifier(metadataKey);
  22589. const symbol = this.getStaticSymbol(filePath, name);
  22590. const origin = origins.hasOwnProperty(metadataKey) && origins[metadataKey];
  22591. if (origin) {
  22592. // If the symbol is from a bundled index, use the declaration location of the
  22593. // symbol so relative references (such as './my.html') will be calculated
  22594. // correctly.
  22595. const originFilePath = this.resolveModule(origin, filePath);
  22596. if (!originFilePath) {
  22597. this.reportError(new Error(`Couldn't resolve original symbol for ${origin} from ${this.host.getOutputName(filePath)}`));
  22598. }
  22599. else {
  22600. this.symbolResourcePaths.set(symbol, originFilePath);
  22601. }
  22602. }
  22603. resolvedSymbols.push(this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames, symbolMeta));
  22604. });
  22605. }
  22606. resolvedSymbols.forEach((resolvedSymbol) => this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol));
  22607. this.symbolFromFile.set(filePath, resolvedSymbols.map(resolvedSymbol => resolvedSymbol.symbol));
  22608. }
  22609. createResolvedSymbol(sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
  22610. // For classes that don't have Angular summaries / metadata,
  22611. // we only keep their arity, but nothing else
  22612. // (e.g. their constructor parameters).
  22613. // We do this to prevent introducing deep imports
  22614. // as we didn't generate .ngfactory.ts files with proper reexports.
  22615. const isTsFile = TS.test(sourceSymbol.filePath);
  22616. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
  22617. metadata['__symbolic'] === 'class') {
  22618. const transformedMeta = { __symbolic: 'class', arity: metadata.arity };
  22619. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
  22620. }
  22621. let _originalFileMemo;
  22622. const getOriginalName = () => {
  22623. if (!_originalFileMemo) {
  22624. // Guess what the original file name is from the reference. If it has a `.d.ts` extension
  22625. // replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
  22626. // .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
  22627. // location as it is not important to finding the file.
  22628. _originalFileMemo =
  22629. this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
  22630. .replace(/^.*node_modules[/\\]/, ''));
  22631. }
  22632. return _originalFileMemo;
  22633. };
  22634. const self = this;
  22635. class ReferenceTransformer extends ValueTransformer {
  22636. visitStringMap(map, functionParams) {
  22637. const symbolic = map['__symbolic'];
  22638. if (symbolic === 'function') {
  22639. const oldLen = functionParams.length;
  22640. functionParams.push(...(map['parameters'] || []));
  22641. const result = super.visitStringMap(map, functionParams);
  22642. functionParams.length = oldLen;
  22643. return result;
  22644. }
  22645. else if (symbolic === 'reference') {
  22646. const module = map['module'];
  22647. const name = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
  22648. if (!name) {
  22649. return null;
  22650. }
  22651. let filePath;
  22652. if (module) {
  22653. filePath = self.resolveModule(module, sourceSymbol.filePath);
  22654. if (!filePath) {
  22655. return {
  22656. __symbolic: 'error',
  22657. message: `Could not resolve ${module} relative to ${self.host.getMetadataFor(sourceSymbol.filePath)}.`,
  22658. line: map['line'],
  22659. character: map['character'],
  22660. fileName: getOriginalName()
  22661. };
  22662. }
  22663. return {
  22664. __symbolic: 'resolved',
  22665. symbol: self.getStaticSymbol(filePath, name),
  22666. line: map['line'],
  22667. character: map['character'],
  22668. fileName: getOriginalName()
  22669. };
  22670. }
  22671. else if (functionParams.indexOf(name) >= 0) {
  22672. // reference to a function parameter
  22673. return { __symbolic: 'reference', name: name };
  22674. }
  22675. else {
  22676. if (topLevelSymbolNames.has(name)) {
  22677. return self.getStaticSymbol(topLevelPath, name);
  22678. }
  22679. }
  22680. }
  22681. else if (symbolic === 'error') {
  22682. return Object.assign({}, map, { fileName: getOriginalName() });
  22683. }
  22684. else {
  22685. return super.visitStringMap(map, functionParams);
  22686. }
  22687. }
  22688. }
  22689. const transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
  22690. let unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
  22691. if (unwrappedTransformedMeta instanceof StaticSymbol) {
  22692. return this.createExport(sourceSymbol, unwrappedTransformedMeta);
  22693. }
  22694. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
  22695. }
  22696. createExport(sourceSymbol, targetSymbol) {
  22697. sourceSymbol.assertNoMembers();
  22698. targetSymbol.assertNoMembers();
  22699. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
  22700. this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
  22701. // This case is for an ng library importing symbols from a plain ts library
  22702. // transitively.
  22703. // Note: We rely on the fact that we discover symbols in the direction
  22704. // from source files to library files
  22705. this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
  22706. }
  22707. return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
  22708. }
  22709. reportError(error, context, path) {
  22710. if (this.errorRecorder) {
  22711. this.errorRecorder(error, (context && context.filePath) || path);
  22712. }
  22713. else {
  22714. throw error;
  22715. }
  22716. }
  22717. /**
  22718. * @param module an absolute path to a module file.
  22719. */
  22720. getModuleMetadata(module) {
  22721. let moduleMetadata = this.metadataCache.get(module);
  22722. if (!moduleMetadata) {
  22723. const moduleMetadatas = this.host.getMetadataFor(module);
  22724. if (moduleMetadatas) {
  22725. let maxVersion = -1;
  22726. moduleMetadatas.forEach((md) => {
  22727. if (md && md['version'] > maxVersion) {
  22728. maxVersion = md['version'];
  22729. moduleMetadata = md;
  22730. }
  22731. });
  22732. }
  22733. if (!moduleMetadata) {
  22734. moduleMetadata =
  22735. { __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
  22736. }
  22737. if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
  22738. const errorMessage = moduleMetadata['version'] == 2 ?
  22739. `Unsupported metadata version ${moduleMetadata['version']} for module ${module}. This module should be compiled with a newer version of ngc` :
  22740. `Metadata version mismatch for module ${this.host.getOutputName(module)}, found version ${moduleMetadata['version']}, expected ${SUPPORTED_SCHEMA_VERSION}`;
  22741. this.reportError(new Error(errorMessage));
  22742. }
  22743. this.metadataCache.set(module, moduleMetadata);
  22744. }
  22745. return moduleMetadata;
  22746. }
  22747. getSymbolByModule(module, symbolName, containingFile) {
  22748. const filePath = this.resolveModule(module, containingFile);
  22749. if (!filePath) {
  22750. this.reportError(new Error(`Could not resolve module ${module}${containingFile ? ' relative to ' +
  22751. this.host.getOutputName(containingFile) : ''}`));
  22752. return this.getStaticSymbol(`ERROR:${module}`, symbolName);
  22753. }
  22754. return this.getStaticSymbol(filePath, symbolName);
  22755. }
  22756. resolveModule(module, containingFile) {
  22757. try {
  22758. return this.host.moduleNameToFileName(module, containingFile);
  22759. }
  22760. catch (e) {
  22761. console.error(`Could not resolve module '${module}' relative to file ${containingFile}`);
  22762. this.reportError(e, undefined, containingFile);
  22763. }
  22764. return null;
  22765. }
  22766. }
  22767. // Remove extra underscore from escaped identifier.
  22768. // See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
  22769. function unescapeIdentifier(identifier) {
  22770. return identifier.startsWith('___') ? identifier.substr(1) : identifier;
  22771. }
  22772. function unwrapResolvedMetadata(metadata) {
  22773. if (metadata && metadata.__symbolic === 'resolved') {
  22774. return metadata.symbol;
  22775. }
  22776. return metadata;
  22777. }
  22778. /**
  22779. * @license
  22780. * Copyright Google Inc. All Rights Reserved.
  22781. *
  22782. * Use of this source code is governed by an MIT-style license that can be
  22783. * found in the LICENSE file at https://angular.io/license
  22784. */
  22785. function serializeSummaries(srcFileName, forJitCtx, summaryResolver, symbolResolver, symbols, types, createExternalSymbolReexports = false) {
  22786. const toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);
  22787. // for symbols, we use everything except for the class metadata itself
  22788. // (we keep the statics though), as the class metadata is contained in the
  22789. // CompileTypeSummary.
  22790. symbols.forEach((resolvedSymbol) => toJsonSerializer.addSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }));
  22791. // Add type summaries.
  22792. types.forEach(({ summary, metadata }) => {
  22793. toJsonSerializer.addSummary({ symbol: summary.type.reference, metadata: undefined, type: summary });
  22794. });
  22795. const { json, exportAs } = toJsonSerializer.serialize(createExternalSymbolReexports);
  22796. if (forJitCtx) {
  22797. const forJitSerializer = new ForJitSerializer(forJitCtx, symbolResolver, summaryResolver);
  22798. types.forEach(({ summary, metadata }) => { forJitSerializer.addSourceType(summary, metadata); });
  22799. toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach((summary) => {
  22800. if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
  22801. forJitSerializer.addLibType(summary.type);
  22802. }
  22803. });
  22804. forJitSerializer.serialize(exportAs);
  22805. }
  22806. return { json, exportAs };
  22807. }
  22808. function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
  22809. const deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
  22810. return deserializer.deserialize(libraryFileName, json);
  22811. }
  22812. function createForJitStub(outputCtx, reference) {
  22813. return createSummaryForJitFunction(outputCtx, reference, NULL_EXPR);
  22814. }
  22815. function createSummaryForJitFunction(outputCtx, reference, value) {
  22816. const fnName = summaryForJitName(reference.name);
  22817. outputCtx.statements.push(fn([], [new ReturnStatement(value)], new ArrayType(DYNAMIC_TYPE)).toDeclStmt(fnName, [
  22818. StmtModifier.Final, StmtModifier.Exported
  22819. ]));
  22820. }
  22821. class ToJsonSerializer extends ValueTransformer {
  22822. constructor(symbolResolver, summaryResolver, srcFileName) {
  22823. super();
  22824. this.symbolResolver = symbolResolver;
  22825. this.summaryResolver = summaryResolver;
  22826. this.srcFileName = srcFileName;
  22827. // Note: This only contains symbols without members.
  22828. this.symbols = [];
  22829. this.indexBySymbol = new Map();
  22830. this.reexportedBy = new Map();
  22831. // This now contains a `__symbol: number` in the place of
  22832. // StaticSymbols, but otherwise has the same shape as the original objects.
  22833. this.processedSummaryBySymbol = new Map();
  22834. this.processedSummaries = [];
  22835. this.unprocessedSymbolSummariesBySymbol = new Map();
  22836. this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
  22837. }
  22838. addSummary(summary) {
  22839. let unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
  22840. let processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
  22841. if (!unprocessedSummary) {
  22842. unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
  22843. this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
  22844. processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
  22845. this.processedSummaries.push(processedSummary);
  22846. this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
  22847. }
  22848. if (!unprocessedSummary.metadata && summary.metadata) {
  22849. let metadata = summary.metadata || {};
  22850. if (metadata.__symbolic === 'class') {
  22851. // For classes, we keep everything except their class decorators.
  22852. // We need to keep e.g. the ctor args, method names, method decorators
  22853. // so that the class can be extended in another compilation unit.
  22854. // We don't keep the class decorators as
  22855. // 1) they refer to data
  22856. // that should not cause a rebuild of downstream compilation units
  22857. // (e.g. inline templates of @Component, or @NgModule.declarations)
  22858. // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
  22859. const clone = {};
  22860. Object.keys(metadata).forEach((propName) => {
  22861. if (propName !== 'decorators') {
  22862. clone[propName] = metadata[propName];
  22863. }
  22864. });
  22865. metadata = clone;
  22866. }
  22867. else if (isCall(metadata)) {
  22868. if (!isFunctionCall(metadata) && !isMethodCallOnVariable(metadata)) {
  22869. // Don't store complex calls as we won't be able to simplify them anyways later on.
  22870. metadata = {
  22871. __symbolic: 'error',
  22872. message: 'Complex function calls are not supported.',
  22873. };
  22874. }
  22875. }
  22876. // Note: We need to keep storing ctor calls for e.g.
  22877. // `export const x = new InjectionToken(...)`
  22878. unprocessedSummary.metadata = metadata;
  22879. processedSummary.metadata = this.processValue(metadata, 1 /* ResolveValue */);
  22880. if (metadata instanceof StaticSymbol &&
  22881. this.summaryResolver.isLibraryFile(metadata.filePath)) {
  22882. const declarationSymbol = this.symbols[this.indexBySymbol.get(metadata)];
  22883. if (!isLoweredSymbol(declarationSymbol.name)) {
  22884. // Note: symbols that were introduced during codegen in the user file can have a reexport
  22885. // if a user used `export *`. However, we can't rely on this as tsickle will change
  22886. // `export *` into named exports, using only the information from the typechecker.
  22887. // As we introduce the new symbols after typecheck, Tsickle does not know about them,
  22888. // and omits them when expanding `export *`.
  22889. // So we have to keep reexporting these symbols manually via .ngfactory files.
  22890. this.reexportedBy.set(declarationSymbol, summary.symbol);
  22891. }
  22892. }
  22893. }
  22894. if (!unprocessedSummary.type && summary.type) {
  22895. unprocessedSummary.type = summary.type;
  22896. // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
  22897. // as the type summaries already contain the transitive data that they require
  22898. // (in a minimal way).
  22899. processedSummary.type = this.processValue(summary.type, 0 /* None */);
  22900. // except for reexported directives / pipes, so we need to store
  22901. // their summaries explicitly.
  22902. if (summary.type.summaryKind === CompileSummaryKind.NgModule) {
  22903. const ngModuleSummary = summary.type;
  22904. ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach((id) => {
  22905. const symbol = id.reference;
  22906. if (this.summaryResolver.isLibraryFile(symbol.filePath) &&
  22907. !this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
  22908. const summary = this.summaryResolver.resolveSummary(symbol);
  22909. if (summary) {
  22910. this.addSummary(summary);
  22911. }
  22912. }
  22913. });
  22914. }
  22915. }
  22916. }
  22917. /**
  22918. * @param createExternalSymbolReexports Whether external static symbols should be re-exported.
  22919. * This can be enabled if external symbols should be re-exported by the current module in
  22920. * order to avoid dynamically generated module dependencies which can break strict dependency
  22921. * enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
  22922. */
  22923. serialize(createExternalSymbolReexports) {
  22924. const exportAs = [];
  22925. const json = JSON.stringify({
  22926. moduleName: this.moduleName,
  22927. summaries: this.processedSummaries,
  22928. symbols: this.symbols.map((symbol, index) => {
  22929. symbol.assertNoMembers();
  22930. let importAs = undefined;
  22931. if (this.summaryResolver.isLibraryFile(symbol.filePath)) {
  22932. const reexportSymbol = this.reexportedBy.get(symbol);
  22933. if (reexportSymbol) {
  22934. // In case the given external static symbol is already manually exported by the
  22935. // user, we just proxy the external static symbol reference to the manual export.
  22936. // This ensures that the AOT compiler imports the external symbol through the
  22937. // user export and does not introduce another dependency which is not needed.
  22938. importAs = this.indexBySymbol.get(reexportSymbol);
  22939. }
  22940. else if (createExternalSymbolReexports) {
  22941. // In this case, the given external static symbol is *not* manually exported by
  22942. // the user, and we manually create a re-export in the factory file so that we
  22943. // don't introduce another module dependency. This is useful when running within
  22944. // Bazel so that the AOT compiler does not introduce any module dependencies
  22945. // which can break the strict dependency enforcement. (e.g. as in Google3)
  22946. // Read more about this here: https://github.com/angular/angular/issues/25644
  22947. const summary = this.unprocessedSymbolSummariesBySymbol.get(symbol);
  22948. if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
  22949. importAs = `${symbol.name}_${index}`;
  22950. exportAs.push({ symbol, exportAs: importAs });
  22951. }
  22952. }
  22953. }
  22954. return {
  22955. __symbol: index,
  22956. name: symbol.name,
  22957. filePath: this.summaryResolver.toSummaryFileName(symbol.filePath, this.srcFileName),
  22958. importAs: importAs
  22959. };
  22960. })
  22961. });
  22962. return { json, exportAs };
  22963. }
  22964. processValue(value, flags) {
  22965. return visitValue(value, this, flags);
  22966. }
  22967. visitOther(value, context) {
  22968. if (value instanceof StaticSymbol) {
  22969. let baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
  22970. const index = this.visitStaticSymbol(baseSymbol, context);
  22971. return { __symbol: index, members: value.members };
  22972. }
  22973. }
  22974. /**
  22975. * Strip line and character numbers from ngsummaries.
  22976. * Emitting them causes white spaces changes to retrigger upstream
  22977. * recompilations in bazel.
  22978. * TODO: find out a way to have line and character numbers in errors without
  22979. * excessive recompilation in bazel.
  22980. */
  22981. visitStringMap(map, context) {
  22982. if (map['__symbolic'] === 'resolved') {
  22983. return visitValue(map['symbol'], this, context);
  22984. }
  22985. if (map['__symbolic'] === 'error') {
  22986. delete map['line'];
  22987. delete map['character'];
  22988. }
  22989. return super.visitStringMap(map, context);
  22990. }
  22991. /**
  22992. * Returns null if the options.resolveValue is true, and the summary for the symbol
  22993. * resolved to a type or could not be resolved.
  22994. */
  22995. visitStaticSymbol(baseSymbol, flags) {
  22996. let index = this.indexBySymbol.get(baseSymbol);
  22997. let summary = null;
  22998. if (flags & 1 /* ResolveValue */ &&
  22999. this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
  23000. if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
  23001. // the summary for this symbol was already added
  23002. // -> nothing to do.
  23003. return index;
  23004. }
  23005. summary = this.loadSummary(baseSymbol);
  23006. if (summary && summary.metadata instanceof StaticSymbol) {
  23007. // The summary is a reexport
  23008. index = this.visitStaticSymbol(summary.metadata, flags);
  23009. // reset the summary as it is just a reexport, so we don't want to store it.
  23010. summary = null;
  23011. }
  23012. }
  23013. else if (index != null) {
  23014. // Note: == on purpose to compare with undefined!
  23015. // No summary and the symbol is already added -> nothing to do.
  23016. return index;
  23017. }
  23018. // Note: == on purpose to compare with undefined!
  23019. if (index == null) {
  23020. index = this.symbols.length;
  23021. this.symbols.push(baseSymbol);
  23022. }
  23023. this.indexBySymbol.set(baseSymbol, index);
  23024. if (summary) {
  23025. this.addSummary(summary);
  23026. }
  23027. return index;
  23028. }
  23029. loadSummary(symbol) {
  23030. let summary = this.summaryResolver.resolveSummary(symbol);
  23031. if (!summary) {
  23032. // some symbols might originate from a plain typescript library
  23033. // that just exported .d.ts and .metadata.json files, i.e. where no summary
  23034. // files were created.
  23035. const resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  23036. if (resolvedSymbol) {
  23037. summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
  23038. }
  23039. }
  23040. return summary;
  23041. }
  23042. }
  23043. class ForJitSerializer {
  23044. constructor(outputCtx, symbolResolver, summaryResolver) {
  23045. this.outputCtx = outputCtx;
  23046. this.symbolResolver = symbolResolver;
  23047. this.summaryResolver = summaryResolver;
  23048. this.data = [];
  23049. }
  23050. addSourceType(summary, metadata) {
  23051. this.data.push({ summary, metadata, isLibrary: false });
  23052. }
  23053. addLibType(summary) {
  23054. this.data.push({ summary, metadata: null, isLibrary: true });
  23055. }
  23056. serialize(exportAsArr) {
  23057. const exportAsBySymbol = new Map();
  23058. for (const { symbol, exportAs } of exportAsArr) {
  23059. exportAsBySymbol.set(symbol, exportAs);
  23060. }
  23061. const ngModuleSymbols = new Set();
  23062. for (const { summary, metadata, isLibrary } of this.data) {
  23063. if (summary.summaryKind === CompileSummaryKind.NgModule) {
  23064. // collect the symbols that refer to NgModule classes.
  23065. // Note: we can't just rely on `summary.type.summaryKind` to determine this as
  23066. // we don't add the summaries of all referenced symbols when we serialize type summaries.
  23067. // See serializeSummaries for details.
  23068. ngModuleSymbols.add(summary.type.reference);
  23069. const modSummary = summary;
  23070. for (const mod of modSummary.modules) {
  23071. ngModuleSymbols.add(mod.reference);
  23072. }
  23073. }
  23074. if (!isLibrary) {
  23075. const fnName = summaryForJitName(summary.type.reference.name);
  23076. createSummaryForJitFunction(this.outputCtx, summary.type.reference, this.serializeSummaryWithDeps(summary, metadata));
  23077. }
  23078. }
  23079. ngModuleSymbols.forEach((ngModuleSymbol) => {
  23080. if (this.summaryResolver.isLibraryFile(ngModuleSymbol.filePath)) {
  23081. let exportAs = exportAsBySymbol.get(ngModuleSymbol) || ngModuleSymbol.name;
  23082. const jitExportAsName = summaryForJitName(exportAs);
  23083. this.outputCtx.statements.push(variable(jitExportAsName)
  23084. .set(this.serializeSummaryRef(ngModuleSymbol))
  23085. .toDeclStmt(null, [StmtModifier.Exported]));
  23086. }
  23087. });
  23088. }
  23089. serializeSummaryWithDeps(summary, metadata) {
  23090. const expressions = [this.serializeSummary(summary)];
  23091. let providers = [];
  23092. if (metadata instanceof CompileNgModuleMetadata) {
  23093. expressions.push(...
  23094. // For directives / pipes, we only add the declared ones,
  23095. // and rely on transitively importing NgModules to get the transitive
  23096. // summaries.
  23097. metadata.declaredDirectives.concat(metadata.declaredPipes)
  23098. .map(type => type.reference)
  23099. // For modules,
  23100. // we also add the summaries for modules
  23101. // from libraries.
  23102. // This is ok as we produce reexports for all transitive modules.
  23103. .concat(metadata.transitiveModule.modules.map(type => type.reference)
  23104. .filter(ref => ref !== metadata.type.reference))
  23105. .map((ref) => this.serializeSummaryRef(ref)));
  23106. // Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
  23107. // and we already have transitive modules.
  23108. providers = metadata.providers;
  23109. }
  23110. else if (summary.summaryKind === CompileSummaryKind.Directive) {
  23111. const dirSummary = summary;
  23112. providers = dirSummary.providers.concat(dirSummary.viewProviders);
  23113. }
  23114. // Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
  23115. // declaredDirectives / declaredPipes), as we allow
  23116. // providers without ctor arguments to skip the `@Injectable` decorator,
  23117. // i.e. we didn't generate .ngsummary.ts files for these.
  23118. expressions.push(...providers.filter(provider => !!provider.useClass).map(provider => this.serializeSummary({
  23119. summaryKind: CompileSummaryKind.Injectable, type: provider.useClass
  23120. })));
  23121. return literalArr(expressions);
  23122. }
  23123. serializeSummaryRef(typeSymbol) {
  23124. const jitImportedSymbol = this.symbolResolver.getStaticSymbol(summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
  23125. return this.outputCtx.importExpr(jitImportedSymbol);
  23126. }
  23127. serializeSummary(data) {
  23128. const outputCtx = this.outputCtx;
  23129. class Transformer {
  23130. visitArray(arr, context) {
  23131. return literalArr(arr.map(entry => visitValue(entry, this, context)));
  23132. }
  23133. visitStringMap(map, context) {
  23134. return new LiteralMapExpr(Object.keys(map).map((key) => new LiteralMapEntry(key, visitValue(map[key], this, context), false)));
  23135. }
  23136. visitPrimitive(value, context) { return literal(value); }
  23137. visitOther(value, context) {
  23138. if (value instanceof StaticSymbol) {
  23139. return outputCtx.importExpr(value);
  23140. }
  23141. else {
  23142. throw new Error(`Illegal State: Encountered value ${value}`);
  23143. }
  23144. }
  23145. }
  23146. return visitValue(data, new Transformer(), null);
  23147. }
  23148. }
  23149. class FromJsonDeserializer extends ValueTransformer {
  23150. constructor(symbolCache, summaryResolver) {
  23151. super();
  23152. this.symbolCache = symbolCache;
  23153. this.summaryResolver = summaryResolver;
  23154. }
  23155. deserialize(libraryFileName, json) {
  23156. const data = JSON.parse(json);
  23157. const allImportAs = [];
  23158. this.symbols = data.symbols.map((serializedSymbol) => this.symbolCache.get(this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name));
  23159. data.symbols.forEach((serializedSymbol, index) => {
  23160. const symbol = this.symbols[index];
  23161. const importAs = serializedSymbol.importAs;
  23162. if (typeof importAs === 'number') {
  23163. allImportAs.push({ symbol, importAs: this.symbols[importAs] });
  23164. }
  23165. else if (typeof importAs === 'string') {
  23166. allImportAs.push({ symbol, importAs: this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
  23167. }
  23168. });
  23169. const summaries = visitValue(data.summaries, this, null);
  23170. return { moduleName: data.moduleName, summaries, importAs: allImportAs };
  23171. }
  23172. visitStringMap(map, context) {
  23173. if ('__symbol' in map) {
  23174. const baseSymbol = this.symbols[map['__symbol']];
  23175. const members = map['members'];
  23176. return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
  23177. baseSymbol;
  23178. }
  23179. else {
  23180. return super.visitStringMap(map, context);
  23181. }
  23182. }
  23183. }
  23184. function isCall(metadata) {
  23185. return metadata && metadata.__symbolic === 'call';
  23186. }
  23187. function isFunctionCall(metadata) {
  23188. return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
  23189. }
  23190. function isMethodCallOnVariable(metadata) {
  23191. return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
  23192. unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
  23193. }
  23194. /**
  23195. * @license
  23196. * Copyright Google Inc. All Rights Reserved.
  23197. *
  23198. * Use of this source code is governed by an MIT-style license that can be
  23199. * found in the LICENSE file at https://angular.io/license
  23200. */
  23201. class AotCompiler {
  23202. constructor(_config, _options, _host, reflector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _typeCheckCompiler, _ngModuleCompiler, _injectableCompiler, _outputEmitter, _summaryResolver, _symbolResolver) {
  23203. this._config = _config;
  23204. this._options = _options;
  23205. this._host = _host;
  23206. this.reflector = reflector;
  23207. this._metadataResolver = _metadataResolver;
  23208. this._templateParser = _templateParser;
  23209. this._styleCompiler = _styleCompiler;
  23210. this._viewCompiler = _viewCompiler;
  23211. this._typeCheckCompiler = _typeCheckCompiler;
  23212. this._ngModuleCompiler = _ngModuleCompiler;
  23213. this._injectableCompiler = _injectableCompiler;
  23214. this._outputEmitter = _outputEmitter;
  23215. this._summaryResolver = _summaryResolver;
  23216. this._symbolResolver = _symbolResolver;
  23217. this._templateAstCache = new Map();
  23218. this._analyzedFiles = new Map();
  23219. this._analyzedFilesForInjectables = new Map();
  23220. }
  23221. clearCache() { this._metadataResolver.clearCache(); }
  23222. analyzeModulesSync(rootFiles) {
  23223. const analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  23224. analyzeResult.ngModules.forEach(ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true));
  23225. return analyzeResult;
  23226. }
  23227. analyzeModulesAsync(rootFiles) {
  23228. const analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  23229. return Promise
  23230. .all(analyzeResult.ngModules.map(ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false)))
  23231. .then(() => analyzeResult);
  23232. }
  23233. _analyzeFile(fileName) {
  23234. let analyzedFile = this._analyzedFiles.get(fileName);
  23235. if (!analyzedFile) {
  23236. analyzedFile =
  23237. analyzeFile(this._host, this._symbolResolver, this._metadataResolver, fileName);
  23238. this._analyzedFiles.set(fileName, analyzedFile);
  23239. }
  23240. return analyzedFile;
  23241. }
  23242. _analyzeFileForInjectables(fileName) {
  23243. let analyzedFile = this._analyzedFilesForInjectables.get(fileName);
  23244. if (!analyzedFile) {
  23245. analyzedFile = analyzeFileForInjectables(this._host, this._symbolResolver, this._metadataResolver, fileName);
  23246. this._analyzedFilesForInjectables.set(fileName, analyzedFile);
  23247. }
  23248. return analyzedFile;
  23249. }
  23250. findGeneratedFileNames(fileName) {
  23251. const genFileNames = [];
  23252. const file = this._analyzeFile(fileName);
  23253. // Make sure we create a .ngfactory if we have a injectable/directive/pipe/NgModule
  23254. // or a reference to a non source file.
  23255. // Note: This is overestimating the required .ngfactory files as the real calculation is harder.
  23256. // Only do this for StubEmitFlags.Basic, as adding a type check block
  23257. // does not change this file (as we generate type check blocks based on NgModules).
  23258. if (this._options.allowEmptyCodegenFiles || file.directives.length || file.pipes.length ||
  23259. file.injectables.length || file.ngModules.length || file.exportsNonSourceFiles) {
  23260. genFileNames.push(ngfactoryFilePath(file.fileName, true));
  23261. if (this._options.enableSummariesForJit) {
  23262. genFileNames.push(summaryForJitFileName(file.fileName, true));
  23263. }
  23264. }
  23265. const fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(file.fileName, true)[1]);
  23266. file.directives.forEach((dirSymbol) => {
  23267. const compMeta = this._metadataResolver.getNonNormalizedDirectiveMetadata(dirSymbol).metadata;
  23268. if (!compMeta.isComponent) {
  23269. return;
  23270. }
  23271. // Note: compMeta is a component and therefore template is non null.
  23272. compMeta.template.styleUrls.forEach((styleUrl) => {
  23273. const normalizedUrl = this._host.resourceNameToFileName(styleUrl, file.fileName);
  23274. if (!normalizedUrl) {
  23275. throw syntaxError(`Couldn't resolve resource ${styleUrl} relative to ${file.fileName}`);
  23276. }
  23277. const needsShim = (compMeta.template.encapsulation ||
  23278. this._config.defaultEncapsulation) === ViewEncapsulation.Emulated;
  23279. genFileNames.push(_stylesModuleUrl(normalizedUrl, needsShim, fileSuffix));
  23280. if (this._options.allowEmptyCodegenFiles) {
  23281. genFileNames.push(_stylesModuleUrl(normalizedUrl, !needsShim, fileSuffix));
  23282. }
  23283. });
  23284. });
  23285. return genFileNames;
  23286. }
  23287. emitBasicStub(genFileName, originalFileName) {
  23288. const outputCtx = this._createOutputContext(genFileName);
  23289. if (genFileName.endsWith('.ngfactory.ts')) {
  23290. if (!originalFileName) {
  23291. throw new Error(`Assertion error: require the original file for .ngfactory.ts stubs. File: ${genFileName}`);
  23292. }
  23293. const originalFile = this._analyzeFile(originalFileName);
  23294. this._createNgFactoryStub(outputCtx, originalFile, 1 /* Basic */);
  23295. }
  23296. else if (genFileName.endsWith('.ngsummary.ts')) {
  23297. if (this._options.enableSummariesForJit) {
  23298. if (!originalFileName) {
  23299. throw new Error(`Assertion error: require the original file for .ngsummary.ts stubs. File: ${genFileName}`);
  23300. }
  23301. const originalFile = this._analyzeFile(originalFileName);
  23302. _createEmptyStub(outputCtx);
  23303. originalFile.ngModules.forEach(ngModule => {
  23304. // create exports that user code can reference
  23305. createForJitStub(outputCtx, ngModule.type.reference);
  23306. });
  23307. }
  23308. }
  23309. else if (genFileName.endsWith('.ngstyle.ts')) {
  23310. _createEmptyStub(outputCtx);
  23311. }
  23312. // Note: for the stubs, we don't need a property srcFileUrl,
  23313. // as later on in emitAllImpls we will create the proper GeneratedFiles with the
  23314. // correct srcFileUrl.
  23315. // This is good as e.g. for .ngstyle.ts files we can't derive
  23316. // the url of components based on the genFileUrl.
  23317. return this._codegenSourceModule('unknown', outputCtx);
  23318. }
  23319. emitTypeCheckStub(genFileName, originalFileName) {
  23320. const originalFile = this._analyzeFile(originalFileName);
  23321. const outputCtx = this._createOutputContext(genFileName);
  23322. if (genFileName.endsWith('.ngfactory.ts')) {
  23323. this._createNgFactoryStub(outputCtx, originalFile, 2 /* TypeCheck */);
  23324. }
  23325. return outputCtx.statements.length > 0 ?
  23326. this._codegenSourceModule(originalFile.fileName, outputCtx) :
  23327. null;
  23328. }
  23329. loadFilesAsync(fileNames, tsFiles) {
  23330. const files = fileNames.map(fileName => this._analyzeFile(fileName));
  23331. const loadingPromises = [];
  23332. files.forEach(file => file.ngModules.forEach(ngModule => loadingPromises.push(this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false))));
  23333. const analyzedInjectables = tsFiles.map(tsFile => this._analyzeFileForInjectables(tsFile));
  23334. return Promise.all(loadingPromises).then(_ => ({
  23335. analyzedModules: mergeAndValidateNgFiles(files),
  23336. analyzedInjectables: analyzedInjectables,
  23337. }));
  23338. }
  23339. loadFilesSync(fileNames, tsFiles) {
  23340. const files = fileNames.map(fileName => this._analyzeFile(fileName));
  23341. files.forEach(file => file.ngModules.forEach(ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true)));
  23342. const analyzedInjectables = tsFiles.map(tsFile => this._analyzeFileForInjectables(tsFile));
  23343. return {
  23344. analyzedModules: mergeAndValidateNgFiles(files),
  23345. analyzedInjectables: analyzedInjectables,
  23346. };
  23347. }
  23348. _createNgFactoryStub(outputCtx, file, emitFlags) {
  23349. let componentId = 0;
  23350. file.ngModules.forEach((ngModuleMeta, ngModuleIndex) => {
  23351. // Note: the code below needs to executed for StubEmitFlags.Basic and StubEmitFlags.TypeCheck,
  23352. // so we don't change the .ngfactory file too much when adding the type-check block.
  23353. // create exports that user code can reference
  23354. this._ngModuleCompiler.createStub(outputCtx, ngModuleMeta.type.reference);
  23355. // add references to the symbols from the metadata.
  23356. // These can be used by the type check block for components,
  23357. // and they also cause TypeScript to include these files into the program too,
  23358. // which will make them part of the analyzedFiles.
  23359. const externalReferences = [
  23360. // Add references that are available from all the modules and imports.
  23361. ...ngModuleMeta.transitiveModule.directives.map(d => d.reference),
  23362. ...ngModuleMeta.transitiveModule.pipes.map(d => d.reference),
  23363. ...ngModuleMeta.importedModules.map(m => m.type.reference),
  23364. ...ngModuleMeta.exportedModules.map(m => m.type.reference),
  23365. // Add references that might be inserted by the template compiler.
  23366. ...this._externalIdentifierReferences([Identifiers.TemplateRef, Identifiers.ElementRef]),
  23367. ];
  23368. const externalReferenceVars = new Map();
  23369. externalReferences.forEach((ref, typeIndex) => {
  23370. externalReferenceVars.set(ref, `_decl${ngModuleIndex}_${typeIndex}`);
  23371. });
  23372. externalReferenceVars.forEach((varName, reference) => {
  23373. outputCtx.statements.push(variable(varName)
  23374. .set(NULL_EXPR.cast(DYNAMIC_TYPE))
  23375. .toDeclStmt(expressionType(outputCtx.importExpr(reference, /* typeParams */ null, /* useSummaries */ false))));
  23376. });
  23377. if (emitFlags & 2 /* TypeCheck */) {
  23378. // add the type-check block for all components of the NgModule
  23379. ngModuleMeta.declaredDirectives.forEach((dirId) => {
  23380. const compMeta = this._metadataResolver.getDirectiveMetadata(dirId.reference);
  23381. if (!compMeta.isComponent) {
  23382. return;
  23383. }
  23384. componentId++;
  23385. this._createTypeCheckBlock(outputCtx, `${compMeta.type.reference.name}_Host_${componentId}`, ngModuleMeta, this._metadataResolver.getHostComponentMetadata(compMeta), [compMeta.type], externalReferenceVars);
  23386. this._createTypeCheckBlock(outputCtx, `${compMeta.type.reference.name}_${componentId}`, ngModuleMeta, compMeta, ngModuleMeta.transitiveModule.directives, externalReferenceVars);
  23387. });
  23388. }
  23389. });
  23390. if (outputCtx.statements.length === 0) {
  23391. _createEmptyStub(outputCtx);
  23392. }
  23393. }
  23394. _externalIdentifierReferences(references) {
  23395. const result = [];
  23396. for (let reference of references) {
  23397. const token = createTokenForExternalReference(this.reflector, reference);
  23398. if (token.identifier) {
  23399. result.push(token.identifier.reference);
  23400. }
  23401. }
  23402. return result;
  23403. }
  23404. _createTypeCheckBlock(ctx, componentId, moduleMeta, compMeta, directives, externalReferenceVars) {
  23405. const { template: parsedTemplate, pipes: usedPipes } = this._parseTemplate(compMeta, moduleMeta, directives);
  23406. ctx.statements.push(...this._typeCheckCompiler.compileComponent(componentId, compMeta, parsedTemplate, usedPipes, externalReferenceVars, ctx));
  23407. }
  23408. emitMessageBundle(analyzeResult, locale) {
  23409. const errors = [];
  23410. const htmlParser = new HtmlParser();
  23411. // TODO(vicb): implicit tags & attributes
  23412. const messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  23413. analyzeResult.files.forEach(file => {
  23414. const compMetas = [];
  23415. file.directives.forEach(directiveType => {
  23416. const dirMeta = this._metadataResolver.getDirectiveMetadata(directiveType);
  23417. if (dirMeta && dirMeta.isComponent) {
  23418. compMetas.push(dirMeta);
  23419. }
  23420. });
  23421. compMetas.forEach(compMeta => {
  23422. const html = compMeta.template.template;
  23423. // Template URL points to either an HTML or TS file depending on whether
  23424. // the file is used with `templateUrl:` or `template:`, respectively.
  23425. const templateUrl = compMeta.template.templateUrl;
  23426. const interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  23427. errors.push(...messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig));
  23428. });
  23429. });
  23430. if (errors.length) {
  23431. throw new Error(errors.map(e => e.toString()).join('\n'));
  23432. }
  23433. return messageBundle;
  23434. }
  23435. emitAllPartialModules({ ngModuleByPipeOrDirective, files }, r3Files) {
  23436. const contextMap = new Map();
  23437. const getContext = (fileName) => {
  23438. if (!contextMap.has(fileName)) {
  23439. contextMap.set(fileName, this._createOutputContext(fileName));
  23440. }
  23441. return contextMap.get(fileName);
  23442. };
  23443. files.forEach(file => this._compilePartialModule(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables, getContext(file.fileName)));
  23444. r3Files.forEach(file => this._compileShallowModules(file.fileName, file.shallowModules, getContext(file.fileName)));
  23445. return Array.from(contextMap.values())
  23446. .map(context => ({
  23447. fileName: context.genFilePath,
  23448. statements: [...context.constantPool.statements, ...context.statements],
  23449. }));
  23450. }
  23451. _compileShallowModules(fileName, shallowModules, context) {
  23452. shallowModules.forEach(module => compileNgModuleFromRender2(context, module, this._injectableCompiler));
  23453. }
  23454. _compilePartialModule(fileName, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables, context) {
  23455. const errors = [];
  23456. const schemaRegistry = new DomElementSchemaRegistry();
  23457. const hostBindingParser = new BindingParser(this._templateParser.expressionParser, DEFAULT_INTERPOLATION_CONFIG, schemaRegistry, [], errors);
  23458. // Process all components and directives
  23459. directives.forEach(directiveType => {
  23460. const directiveMetadata = this._metadataResolver.getDirectiveMetadata(directiveType);
  23461. if (directiveMetadata.isComponent) {
  23462. const module = ngModuleByPipeOrDirective.get(directiveType);
  23463. module ||
  23464. error(`Cannot determine the module for component '${identifierName(directiveMetadata.type)}'`);
  23465. let htmlAst = directiveMetadata.template.htmlAst;
  23466. const preserveWhitespaces = directiveMetadata.template.preserveWhitespaces;
  23467. if (!preserveWhitespaces) {
  23468. htmlAst = removeWhitespaces(htmlAst);
  23469. }
  23470. const render3Ast = htmlAstToRender3Ast(htmlAst.rootNodes, hostBindingParser);
  23471. // Map of StaticType by directive selectors
  23472. const directiveTypeBySel = new Map();
  23473. const directives = module.transitiveModule.directives.map(dir => this._metadataResolver.getDirectiveSummary(dir.reference));
  23474. directives.forEach(directive => {
  23475. if (directive.selector) {
  23476. directiveTypeBySel.set(directive.selector, directive.type.reference);
  23477. }
  23478. });
  23479. // Map of StaticType by pipe names
  23480. const pipeTypeByName = new Map();
  23481. const pipes = module.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
  23482. pipes.forEach(pipe => { pipeTypeByName.set(pipe.name, pipe.type.reference); });
  23483. compileComponentFromRender2(context, directiveMetadata, render3Ast, this.reflector, hostBindingParser, directiveTypeBySel, pipeTypeByName);
  23484. }
  23485. else {
  23486. compileDirectiveFromRender2(context, directiveMetadata, this.reflector, hostBindingParser);
  23487. }
  23488. });
  23489. pipes.forEach(pipeType => {
  23490. const pipeMetadata = this._metadataResolver.getPipeMetadata(pipeType);
  23491. if (pipeMetadata) {
  23492. compilePipeFromRender2(context, pipeMetadata, this.reflector);
  23493. }
  23494. });
  23495. injectables.forEach(injectable => this._injectableCompiler.compile(injectable, context));
  23496. }
  23497. emitAllPartialModules2(files) {
  23498. // Using reduce like this is a select many pattern (where map is a select pattern)
  23499. return files.reduce((r, file) => {
  23500. r.push(...this._emitPartialModule2(file.fileName, file.injectables));
  23501. return r;
  23502. }, []);
  23503. }
  23504. _emitPartialModule2(fileName, injectables) {
  23505. const context = this._createOutputContext(fileName);
  23506. injectables.forEach(injectable => this._injectableCompiler.compile(injectable, context));
  23507. if (context.statements && context.statements.length > 0) {
  23508. return [{ fileName, statements: [...context.constantPool.statements, ...context.statements] }];
  23509. }
  23510. return [];
  23511. }
  23512. emitAllImpls(analyzeResult) {
  23513. const { ngModuleByPipeOrDirective, files } = analyzeResult;
  23514. const sourceModules = files.map(file => this._compileImplFile(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables));
  23515. return flatten(sourceModules);
  23516. }
  23517. _compileImplFile(srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
  23518. const fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
  23519. const generatedFiles = [];
  23520. const outputCtx = this._createOutputContext(ngfactoryFilePath(srcFileUrl, true));
  23521. generatedFiles.push(...this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, outputCtx));
  23522. // compile all ng modules
  23523. ngModules.forEach((ngModuleMeta) => this._compileModule(outputCtx, ngModuleMeta));
  23524. // compile components
  23525. directives.forEach((dirType) => {
  23526. const compMeta = this._metadataResolver.getDirectiveMetadata(dirType);
  23527. if (!compMeta.isComponent) {
  23528. return;
  23529. }
  23530. const ngModule = ngModuleByPipeOrDirective.get(dirType);
  23531. if (!ngModule) {
  23532. throw new Error(`Internal Error: cannot determine the module for component ${identifierName(compMeta.type)}!`);
  23533. }
  23534. // compile styles
  23535. const componentStylesheet = this._styleCompiler.compileComponent(outputCtx, compMeta);
  23536. // Note: compMeta is a component and therefore template is non null.
  23537. compMeta.template.externalStylesheets.forEach((stylesheetMeta) => {
  23538. // Note: fill non shim and shim style files as they might
  23539. // be shared by component with and without ViewEncapsulation.
  23540. const shim = this._styleCompiler.needsStyleShim(compMeta);
  23541. generatedFiles.push(this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, shim, fileSuffix));
  23542. if (this._options.allowEmptyCodegenFiles) {
  23543. generatedFiles.push(this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, !shim, fileSuffix));
  23544. }
  23545. });
  23546. // compile components
  23547. const compViewVars = this._compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives, componentStylesheet, fileSuffix);
  23548. this._compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
  23549. });
  23550. if (outputCtx.statements.length > 0 || this._options.allowEmptyCodegenFiles) {
  23551. const srcModule = this._codegenSourceModule(srcFileUrl, outputCtx);
  23552. generatedFiles.unshift(srcModule);
  23553. }
  23554. return generatedFiles;
  23555. }
  23556. _createSummary(srcFileName, directives, pipes, ngModules, injectables, ngFactoryCtx) {
  23557. const symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
  23558. .map(symbol => this._symbolResolver.resolveSymbol(symbol));
  23559. const typeData = [
  23560. ...ngModules.map(meta => ({
  23561. summary: this._metadataResolver.getNgModuleSummary(meta.type.reference),
  23562. metadata: this._metadataResolver.getNgModuleMetadata(meta.type.reference)
  23563. })),
  23564. ...directives.map(ref => ({
  23565. summary: this._metadataResolver.getDirectiveSummary(ref),
  23566. metadata: this._metadataResolver.getDirectiveMetadata(ref)
  23567. })),
  23568. ...pipes.map(ref => ({
  23569. summary: this._metadataResolver.getPipeSummary(ref),
  23570. metadata: this._metadataResolver.getPipeMetadata(ref)
  23571. })),
  23572. ...injectables.map(ref => ({
  23573. summary: this._metadataResolver.getInjectableSummary(ref.symbol),
  23574. metadata: this._metadataResolver.getInjectableSummary(ref.symbol).type
  23575. }))
  23576. ];
  23577. const forJitOutputCtx = this._options.enableSummariesForJit ?
  23578. this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
  23579. null;
  23580. const { json, exportAs } = serializeSummaries(srcFileName, forJitOutputCtx, this._summaryResolver, this._symbolResolver, symbolSummaries, typeData, this._options.createExternalSymbolFactoryReexports);
  23581. exportAs.forEach((entry) => {
  23582. ngFactoryCtx.statements.push(variable(entry.exportAs).set(ngFactoryCtx.importExpr(entry.symbol)).toDeclStmt(null, [
  23583. StmtModifier.Exported
  23584. ]));
  23585. });
  23586. const summaryJson = new GeneratedFile(srcFileName, summaryFileName(srcFileName), json);
  23587. const result = [summaryJson];
  23588. if (forJitOutputCtx) {
  23589. result.push(this._codegenSourceModule(srcFileName, forJitOutputCtx));
  23590. }
  23591. return result;
  23592. }
  23593. _compileModule(outputCtx, ngModule) {
  23594. const providers = [];
  23595. if (this._options.locale) {
  23596. const normalizedLocale = this._options.locale.replace(/_/g, '-');
  23597. providers.push({
  23598. token: createTokenForExternalReference(this.reflector, Identifiers.LOCALE_ID),
  23599. useValue: normalizedLocale,
  23600. });
  23601. }
  23602. if (this._options.i18nFormat) {
  23603. providers.push({
  23604. token: createTokenForExternalReference(this.reflector, Identifiers.TRANSLATIONS_FORMAT),
  23605. useValue: this._options.i18nFormat
  23606. });
  23607. }
  23608. this._ngModuleCompiler.compile(outputCtx, ngModule, providers);
  23609. }
  23610. _compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix) {
  23611. const hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta);
  23612. const hostViewFactoryVar = this._compileComponent(outputCtx, hostMeta, ngModule, [compMeta.type], null, fileSuffix)
  23613. .viewClassVar;
  23614. const compFactoryVar = componentFactoryName(compMeta.type.reference);
  23615. const inputsExprs = [];
  23616. for (let propName in compMeta.inputs) {
  23617. const templateName = compMeta.inputs[propName];
  23618. // Don't quote so that the key gets minified...
  23619. inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  23620. }
  23621. const outputsExprs = [];
  23622. for (let propName in compMeta.outputs) {
  23623. const templateName = compMeta.outputs[propName];
  23624. // Don't quote so that the key gets minified...
  23625. outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  23626. }
  23627. outputCtx.statements.push(variable(compFactoryVar)
  23628. .set(importExpr(Identifiers.createComponentFactory).callFn([
  23629. literal(compMeta.selector), outputCtx.importExpr(compMeta.type.reference),
  23630. variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
  23631. new LiteralMapExpr(outputsExprs),
  23632. literalArr(compMeta.template.ngContentSelectors.map(selector => literal(selector)))
  23633. ]))
  23634. .toDeclStmt(importType(Identifiers.ComponentFactory, [expressionType(outputCtx.importExpr(compMeta.type.reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]));
  23635. }
  23636. _compileComponent(outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix) {
  23637. const { template: parsedTemplate, pipes: usedPipes } = this._parseTemplate(compMeta, ngModule, directiveIdentifiers);
  23638. const stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
  23639. const viewResult = this._viewCompiler.compileComponent(outputCtx, compMeta, parsedTemplate, stylesExpr, usedPipes);
  23640. if (componentStyles) {
  23641. _resolveStyleStatements(this._symbolResolver, componentStyles, this._styleCompiler.needsStyleShim(compMeta), fileSuffix);
  23642. }
  23643. return viewResult;
  23644. }
  23645. _parseTemplate(compMeta, ngModule, directiveIdentifiers) {
  23646. if (this._templateAstCache.has(compMeta.type.reference)) {
  23647. return this._templateAstCache.get(compMeta.type.reference);
  23648. }
  23649. const preserveWhitespaces = compMeta.template.preserveWhitespaces;
  23650. const directives = directiveIdentifiers.map(dir => this._metadataResolver.getDirectiveSummary(dir.reference));
  23651. const pipes = ngModule.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
  23652. const result = this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  23653. this._templateAstCache.set(compMeta.type.reference, result);
  23654. return result;
  23655. }
  23656. _createOutputContext(genFilePath) {
  23657. const importExpr$1 = (symbol, typeParams = null, useSummaries = true) => {
  23658. if (!(symbol instanceof StaticSymbol)) {
  23659. throw new Error(`Internal error: unknown identifier ${JSON.stringify(symbol)}`);
  23660. }
  23661. const arity = this._symbolResolver.getTypeArity(symbol) || 0;
  23662. const { filePath, name, members } = this._symbolResolver.getImportAs(symbol, useSummaries) || symbol;
  23663. const importModule = this._fileNameToModuleName(filePath, genFilePath);
  23664. // It should be good enough to compare filePath to genFilePath and if they are equal
  23665. // there is a self reference. However, ngfactory files generate to .ts but their
  23666. // symbols have .d.ts so a simple compare is insufficient. They should be canonical
  23667. // and is tracked by #17705.
  23668. const selfReference = this._fileNameToModuleName(genFilePath, genFilePath);
  23669. const moduleName = importModule === selfReference ? null : importModule;
  23670. // If we are in a type expression that refers to a generic type then supply
  23671. // the required type parameters. If there were not enough type parameters
  23672. // supplied, supply any as the type. Outside a type expression the reference
  23673. // should not supply type parameters and be treated as a simple value reference
  23674. // to the constructor function itself.
  23675. const suppliedTypeParams = typeParams || [];
  23676. const missingTypeParamsCount = arity - suppliedTypeParams.length;
  23677. const allTypeParams = suppliedTypeParams.concat(new Array(missingTypeParamsCount).fill(DYNAMIC_TYPE));
  23678. return members.reduce((expr, memberName) => expr.prop(memberName), importExpr(new ExternalReference(moduleName, name, null), allTypeParams));
  23679. };
  23680. return { statements: [], genFilePath, importExpr: importExpr$1, constantPool: new ConstantPool() };
  23681. }
  23682. _fileNameToModuleName(importedFilePath, containingFilePath) {
  23683. return this._summaryResolver.getKnownModuleName(importedFilePath) ||
  23684. this._symbolResolver.getKnownModuleName(importedFilePath) ||
  23685. this._host.fileNameToModuleName(importedFilePath, containingFilePath);
  23686. }
  23687. _codegenStyles(srcFileUrl, compMeta, stylesheetMetadata, isShimmed, fileSuffix) {
  23688. const outputCtx = this._createOutputContext(_stylesModuleUrl(stylesheetMetadata.moduleUrl, isShimmed, fileSuffix));
  23689. const compiledStylesheet = this._styleCompiler.compileStyles(outputCtx, compMeta, stylesheetMetadata, isShimmed);
  23690. _resolveStyleStatements(this._symbolResolver, compiledStylesheet, isShimmed, fileSuffix);
  23691. return this._codegenSourceModule(srcFileUrl, outputCtx);
  23692. }
  23693. _codegenSourceModule(srcFileUrl, ctx) {
  23694. return new GeneratedFile(srcFileUrl, ctx.genFilePath, ctx.statements);
  23695. }
  23696. listLazyRoutes(entryRoute, analyzedModules) {
  23697. const self = this;
  23698. if (entryRoute) {
  23699. const symbol = parseLazyRoute(entryRoute, this.reflector).referencedModule;
  23700. return visitLazyRoute(symbol);
  23701. }
  23702. else if (analyzedModules) {
  23703. const allLazyRoutes = [];
  23704. for (const ngModule of analyzedModules.ngModules) {
  23705. const lazyRoutes = listLazyRoutes(ngModule, this.reflector);
  23706. for (const lazyRoute of lazyRoutes) {
  23707. allLazyRoutes.push(lazyRoute);
  23708. }
  23709. }
  23710. return allLazyRoutes;
  23711. }
  23712. else {
  23713. throw new Error(`Either route or analyzedModules has to be specified!`);
  23714. }
  23715. function visitLazyRoute(symbol, seenRoutes = new Set(), allLazyRoutes = []) {
  23716. // Support pointing to default exports, but stop recursing there,
  23717. // as the StaticReflector does not yet support default exports.
  23718. if (seenRoutes.has(symbol) || !symbol.name) {
  23719. return allLazyRoutes;
  23720. }
  23721. seenRoutes.add(symbol);
  23722. const lazyRoutes = listLazyRoutes(self._metadataResolver.getNgModuleMetadata(symbol, true), self.reflector);
  23723. for (const lazyRoute of lazyRoutes) {
  23724. allLazyRoutes.push(lazyRoute);
  23725. visitLazyRoute(lazyRoute.referencedModule, seenRoutes, allLazyRoutes);
  23726. }
  23727. return allLazyRoutes;
  23728. }
  23729. }
  23730. }
  23731. function _createEmptyStub(outputCtx) {
  23732. // Note: We need to produce at least one import statement so that
  23733. // TypeScript knows that the file is an es6 module. Otherwise our generated
  23734. // exports / imports won't be emitted properly by TypeScript.
  23735. outputCtx.statements.push(importExpr(Identifiers.ComponentFactory).toStmt());
  23736. }
  23737. function _resolveStyleStatements(symbolResolver, compileResult, needsShim, fileSuffix) {
  23738. compileResult.dependencies.forEach((dep) => {
  23739. dep.setValue(symbolResolver.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, needsShim, fileSuffix), dep.name));
  23740. });
  23741. }
  23742. function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
  23743. return `${stylesheetUrl}${shim ? '.shim' : ''}.ngstyle${suffix}`;
  23744. }
  23745. function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  23746. const files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
  23747. return mergeAnalyzedFiles(files);
  23748. }
  23749. function analyzeAndValidateNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  23750. return validateAnalyzedModules(analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver));
  23751. }
  23752. function validateAnalyzedModules(analyzedModules) {
  23753. if (analyzedModules.symbolsMissingModule && analyzedModules.symbolsMissingModule.length) {
  23754. const messages = analyzedModules.symbolsMissingModule.map(s => `Cannot determine the module for class ${s.name} in ${s.filePath}! Add ${s.name} to the NgModule to fix it.`);
  23755. throw syntaxError(messages.join('\n'));
  23756. }
  23757. return analyzedModules;
  23758. }
  23759. // Analyzes all of the program files,
  23760. // including files that are not part of the program
  23761. // but are referenced by an NgModule.
  23762. function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
  23763. const seenFiles = new Set();
  23764. const files = [];
  23765. const visitFile = (fileName) => {
  23766. if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
  23767. return false;
  23768. }
  23769. seenFiles.add(fileName);
  23770. const analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
  23771. files.push(analyzedFile);
  23772. analyzedFile.ngModules.forEach(ngModule => {
  23773. ngModule.transitiveModule.modules.forEach(modMeta => visitFile(modMeta.reference.filePath));
  23774. });
  23775. };
  23776. fileNames.forEach((fileName) => visitFile(fileName));
  23777. return files;
  23778. }
  23779. function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
  23780. const directives = [];
  23781. const pipes = [];
  23782. const injectables = [];
  23783. const ngModules = [];
  23784. const hasDecorators = staticSymbolResolver.hasDecorators(fileName);
  23785. let exportsNonSourceFiles = false;
  23786. // Don't analyze .d.ts files that have no decorators as a shortcut
  23787. // to speed up the analysis. This prevents us from
  23788. // resolving the references in these files.
  23789. // Note: exportsNonSourceFiles is only needed when compiling with summaries,
  23790. // which is not the case when .d.ts files are treated as input files.
  23791. if (!fileName.endsWith('.d.ts') || hasDecorators) {
  23792. staticSymbolResolver.getSymbolsOf(fileName).forEach((symbol) => {
  23793. const resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  23794. const symbolMeta = resolvedSymbol.metadata;
  23795. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  23796. return;
  23797. }
  23798. let isNgSymbol = false;
  23799. if (symbolMeta.__symbolic === 'class') {
  23800. if (metadataResolver.isDirective(symbol)) {
  23801. isNgSymbol = true;
  23802. directives.push(symbol);
  23803. }
  23804. else if (metadataResolver.isPipe(symbol)) {
  23805. isNgSymbol = true;
  23806. pipes.push(symbol);
  23807. }
  23808. else if (metadataResolver.isNgModule(symbol)) {
  23809. const ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
  23810. if (ngModule) {
  23811. isNgSymbol = true;
  23812. ngModules.push(ngModule);
  23813. }
  23814. }
  23815. else if (metadataResolver.isInjectable(symbol)) {
  23816. isNgSymbol = true;
  23817. const injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  23818. if (injectable) {
  23819. injectables.push(injectable);
  23820. }
  23821. }
  23822. }
  23823. if (!isNgSymbol) {
  23824. exportsNonSourceFiles =
  23825. exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
  23826. }
  23827. });
  23828. }
  23829. return {
  23830. fileName, directives, pipes, ngModules, injectables, exportsNonSourceFiles,
  23831. };
  23832. }
  23833. function analyzeFileForInjectables(host, staticSymbolResolver, metadataResolver, fileName) {
  23834. const injectables = [];
  23835. const shallowModules = [];
  23836. if (staticSymbolResolver.hasDecorators(fileName)) {
  23837. staticSymbolResolver.getSymbolsOf(fileName).forEach((symbol) => {
  23838. const resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  23839. const symbolMeta = resolvedSymbol.metadata;
  23840. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  23841. return;
  23842. }
  23843. if (symbolMeta.__symbolic === 'class') {
  23844. if (metadataResolver.isInjectable(symbol)) {
  23845. const injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  23846. if (injectable) {
  23847. injectables.push(injectable);
  23848. }
  23849. }
  23850. else if (metadataResolver.isNgModule(symbol)) {
  23851. const module = metadataResolver.getShallowModuleMetadata(symbol);
  23852. if (module) {
  23853. shallowModules.push(module);
  23854. }
  23855. }
  23856. }
  23857. });
  23858. }
  23859. return { fileName, injectables, shallowModules };
  23860. }
  23861. function isValueExportingNonSourceFile(host, metadata) {
  23862. let exportsNonSourceFiles = false;
  23863. class Visitor {
  23864. visitArray(arr, context) { arr.forEach(v => visitValue(v, this, context)); }
  23865. visitStringMap(map, context) {
  23866. Object.keys(map).forEach((key) => visitValue(map[key], this, context));
  23867. }
  23868. visitPrimitive(value, context) { }
  23869. visitOther(value, context) {
  23870. if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
  23871. exportsNonSourceFiles = true;
  23872. }
  23873. }
  23874. }
  23875. visitValue(metadata, new Visitor(), null);
  23876. return exportsNonSourceFiles;
  23877. }
  23878. function mergeAnalyzedFiles(analyzedFiles) {
  23879. const allNgModules = [];
  23880. const ngModuleByPipeOrDirective = new Map();
  23881. const allPipesAndDirectives = new Set();
  23882. analyzedFiles.forEach(af => {
  23883. af.ngModules.forEach(ngModule => {
  23884. allNgModules.push(ngModule);
  23885. ngModule.declaredDirectives.forEach(d => ngModuleByPipeOrDirective.set(d.reference, ngModule));
  23886. ngModule.declaredPipes.forEach(p => ngModuleByPipeOrDirective.set(p.reference, ngModule));
  23887. });
  23888. af.directives.forEach(d => allPipesAndDirectives.add(d));
  23889. af.pipes.forEach(p => allPipesAndDirectives.add(p));
  23890. });
  23891. const symbolsMissingModule = [];
  23892. allPipesAndDirectives.forEach(ref => {
  23893. if (!ngModuleByPipeOrDirective.has(ref)) {
  23894. symbolsMissingModule.push(ref);
  23895. }
  23896. });
  23897. return {
  23898. ngModules: allNgModules,
  23899. ngModuleByPipeOrDirective,
  23900. symbolsMissingModule,
  23901. files: analyzedFiles
  23902. };
  23903. }
  23904. function mergeAndValidateNgFiles(files) {
  23905. return validateAnalyzedModules(mergeAnalyzedFiles(files));
  23906. }
  23907. /**
  23908. * @license
  23909. * Copyright Google Inc. All Rights Reserved.
  23910. *
  23911. * Use of this source code is governed by an MIT-style license that can be
  23912. * found in the LICENSE file at https://angular.io/license
  23913. */
  23914. const FORMATTED_MESSAGE = 'ngFormattedMessage';
  23915. function indentStr(level) {
  23916. if (level <= 0)
  23917. return '';
  23918. if (level < 6)
  23919. return ['', ' ', ' ', ' ', ' ', ' '][level];
  23920. const half = indentStr(Math.floor(level / 2));
  23921. return half + half + (level % 2 === 1 ? ' ' : '');
  23922. }
  23923. function formatChain(chain, indent = 0) {
  23924. if (!chain)
  23925. return '';
  23926. const position = chain.position ?
  23927. `${chain.position.fileName}(${chain.position.line + 1},${chain.position.column + 1})` :
  23928. '';
  23929. const prefix = position && indent === 0 ? `${position}: ` : '';
  23930. const postfix = position && indent !== 0 ? ` at ${position}` : '';
  23931. const message = `${prefix}${chain.message}${postfix}`;
  23932. return `${indentStr(indent)}${message}${(chain.next && ('\n' + formatChain(chain.next, indent + 2))) || ''}`;
  23933. }
  23934. function formattedError(chain) {
  23935. const message = formatChain(chain) + '.';
  23936. const error = syntaxError(message);
  23937. error[FORMATTED_MESSAGE] = true;
  23938. error.chain = chain;
  23939. error.position = chain.position;
  23940. return error;
  23941. }
  23942. function isFormattedError(error) {
  23943. return !!error[FORMATTED_MESSAGE];
  23944. }
  23945. /**
  23946. * @license
  23947. * Copyright Google Inc. All Rights Reserved.
  23948. *
  23949. * Use of this source code is governed by an MIT-style license that can be
  23950. * found in the LICENSE file at https://angular.io/license
  23951. */
  23952. const ANGULAR_CORE = '@angular/core';
  23953. const ANGULAR_ROUTER = '@angular/router';
  23954. const HIDDEN_KEY = /^\$.*\$$/;
  23955. const IGNORE = {
  23956. __symbolic: 'ignore'
  23957. };
  23958. const USE_VALUE$1 = 'useValue';
  23959. const PROVIDE = 'provide';
  23960. const REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
  23961. const TYPEGUARD_POSTFIX = 'TypeGuard';
  23962. const USE_IF = 'UseIf';
  23963. function shouldIgnore(value) {
  23964. return value && value.__symbolic == 'ignore';
  23965. }
  23966. /**
  23967. * A static reflector implements enough of the Reflector API that is necessary to compile
  23968. * templates statically.
  23969. */
  23970. class StaticReflector {
  23971. constructor(summaryResolver, symbolResolver, knownMetadataClasses = [], knownMetadataFunctions = [], errorRecorder) {
  23972. this.summaryResolver = summaryResolver;
  23973. this.symbolResolver = symbolResolver;
  23974. this.errorRecorder = errorRecorder;
  23975. this.annotationCache = new Map();
  23976. this.shallowAnnotationCache = new Map();
  23977. this.propertyCache = new Map();
  23978. this.parameterCache = new Map();
  23979. this.methodCache = new Map();
  23980. this.staticCache = new Map();
  23981. this.conversionMap = new Map();
  23982. this.resolvedExternalReferences = new Map();
  23983. this.annotationForParentClassWithSummaryKind = new Map();
  23984. this.initializeConversionMap();
  23985. knownMetadataClasses.forEach((kc) => this._registerDecoratorOrConstructor(this.getStaticSymbol(kc.filePath, kc.name), kc.ctor));
  23986. knownMetadataFunctions.forEach((kf) => this._registerFunction(this.getStaticSymbol(kf.filePath, kf.name), kf.fn));
  23987. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Directive, [createDirective, createComponent]);
  23988. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Pipe, [createPipe]);
  23989. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.NgModule, [createNgModule]);
  23990. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
  23991. }
  23992. componentModuleUrl(typeOrFunc) {
  23993. const staticSymbol = this.findSymbolDeclaration(typeOrFunc);
  23994. return this.symbolResolver.getResourcePath(staticSymbol);
  23995. }
  23996. resolveExternalReference(ref, containingFile) {
  23997. let key = undefined;
  23998. if (!containingFile) {
  23999. key = `${ref.moduleName}:${ref.name}`;
  24000. const declarationSymbol = this.resolvedExternalReferences.get(key);
  24001. if (declarationSymbol)
  24002. return declarationSymbol;
  24003. }
  24004. const refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
  24005. const declarationSymbol = this.findSymbolDeclaration(refSymbol);
  24006. if (!containingFile) {
  24007. this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
  24008. this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
  24009. }
  24010. if (key) {
  24011. this.resolvedExternalReferences.set(key, declarationSymbol);
  24012. }
  24013. return declarationSymbol;
  24014. }
  24015. findDeclaration(moduleUrl, name, containingFile) {
  24016. return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
  24017. }
  24018. tryFindDeclaration(moduleUrl, name, containingFile) {
  24019. return this.symbolResolver.ignoreErrorsFor(() => this.findDeclaration(moduleUrl, name, containingFile));
  24020. }
  24021. findSymbolDeclaration(symbol) {
  24022. const resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  24023. if (resolvedSymbol) {
  24024. let resolvedMetadata = resolvedSymbol.metadata;
  24025. if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
  24026. resolvedMetadata = resolvedMetadata.symbol;
  24027. }
  24028. if (resolvedMetadata instanceof StaticSymbol) {
  24029. return this.findSymbolDeclaration(resolvedSymbol.metadata);
  24030. }
  24031. }
  24032. return symbol;
  24033. }
  24034. tryAnnotations(type) {
  24035. const originalRecorder = this.errorRecorder;
  24036. this.errorRecorder = (error, fileName) => { };
  24037. try {
  24038. return this.annotations(type);
  24039. }
  24040. finally {
  24041. this.errorRecorder = originalRecorder;
  24042. }
  24043. }
  24044. annotations(type) {
  24045. return this._annotations(type, (type, decorators) => this.simplify(type, decorators), this.annotationCache);
  24046. }
  24047. shallowAnnotations(type) {
  24048. return this._annotations(type, (type, decorators) => this.simplify(type, decorators, true), this.shallowAnnotationCache);
  24049. }
  24050. _annotations(type, simplify, annotationCache) {
  24051. let annotations = annotationCache.get(type);
  24052. if (!annotations) {
  24053. annotations = [];
  24054. const classMetadata = this.getTypeMetadata(type);
  24055. const parentType = this.findParentType(type, classMetadata);
  24056. if (parentType) {
  24057. const parentAnnotations = this.annotations(parentType);
  24058. annotations.push(...parentAnnotations);
  24059. }
  24060. let ownAnnotations = [];
  24061. if (classMetadata['decorators']) {
  24062. ownAnnotations = simplify(type, classMetadata['decorators']);
  24063. if (ownAnnotations) {
  24064. annotations.push(...ownAnnotations);
  24065. }
  24066. }
  24067. if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
  24068. this.summaryResolver.isLibraryFile(parentType.filePath)) {
  24069. const summary = this.summaryResolver.resolveSummary(parentType);
  24070. if (summary && summary.type) {
  24071. const requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
  24072. const typeHasRequiredAnnotation = requiredAnnotationTypes.some((requiredType) => ownAnnotations.some(ann => requiredType.isTypeOf(ann)));
  24073. if (!typeHasRequiredAnnotation) {
  24074. 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`,
  24075. /* summary */ undefined, `Please add a ${requiredAnnotationTypes.map((type) => type.ngMetadataName).join(' or ')} decorator to the class`), type), type);
  24076. }
  24077. }
  24078. }
  24079. annotationCache.set(type, annotations.filter(ann => !!ann));
  24080. }
  24081. return annotations;
  24082. }
  24083. propMetadata(type) {
  24084. let propMetadata = this.propertyCache.get(type);
  24085. if (!propMetadata) {
  24086. const classMetadata = this.getTypeMetadata(type);
  24087. propMetadata = {};
  24088. const parentType = this.findParentType(type, classMetadata);
  24089. if (parentType) {
  24090. const parentPropMetadata = this.propMetadata(parentType);
  24091. Object.keys(parentPropMetadata).forEach((parentProp) => {
  24092. propMetadata[parentProp] = parentPropMetadata[parentProp];
  24093. });
  24094. }
  24095. const members = classMetadata['members'] || {};
  24096. Object.keys(members).forEach((propName) => {
  24097. const propData = members[propName];
  24098. const prop = propData
  24099. .find(a => a['__symbolic'] == 'property' || a['__symbolic'] == 'method');
  24100. const decorators = [];
  24101. if (propMetadata[propName]) {
  24102. decorators.push(...propMetadata[propName]);
  24103. }
  24104. propMetadata[propName] = decorators;
  24105. if (prop && prop['decorators']) {
  24106. decorators.push(...this.simplify(type, prop['decorators']));
  24107. }
  24108. });
  24109. this.propertyCache.set(type, propMetadata);
  24110. }
  24111. return propMetadata;
  24112. }
  24113. parameters(type) {
  24114. if (!(type instanceof StaticSymbol)) {
  24115. this.reportError(new Error(`parameters received ${JSON.stringify(type)} which is not a StaticSymbol`), type);
  24116. return [];
  24117. }
  24118. try {
  24119. let parameters = this.parameterCache.get(type);
  24120. if (!parameters) {
  24121. const classMetadata = this.getTypeMetadata(type);
  24122. const parentType = this.findParentType(type, classMetadata);
  24123. const members = classMetadata ? classMetadata['members'] : null;
  24124. const ctorData = members ? members['__ctor__'] : null;
  24125. if (ctorData) {
  24126. const ctor = ctorData.find(a => a['__symbolic'] == 'constructor');
  24127. const rawParameterTypes = ctor['parameters'] || [];
  24128. const parameterDecorators = this.simplify(type, ctor['parameterDecorators'] || []);
  24129. parameters = [];
  24130. rawParameterTypes.forEach((rawParamType, index) => {
  24131. const nestedResult = [];
  24132. const paramType = this.trySimplify(type, rawParamType);
  24133. if (paramType)
  24134. nestedResult.push(paramType);
  24135. const decorators = parameterDecorators ? parameterDecorators[index] : null;
  24136. if (decorators) {
  24137. nestedResult.push(...decorators);
  24138. }
  24139. parameters.push(nestedResult);
  24140. });
  24141. }
  24142. else if (parentType) {
  24143. parameters = this.parameters(parentType);
  24144. }
  24145. if (!parameters) {
  24146. parameters = [];
  24147. }
  24148. this.parameterCache.set(type, parameters);
  24149. }
  24150. return parameters;
  24151. }
  24152. catch (e) {
  24153. console.error(`Failed on type ${JSON.stringify(type)} with error ${e}`);
  24154. throw e;
  24155. }
  24156. }
  24157. _methodNames(type) {
  24158. let methodNames = this.methodCache.get(type);
  24159. if (!methodNames) {
  24160. const classMetadata = this.getTypeMetadata(type);
  24161. methodNames = {};
  24162. const parentType = this.findParentType(type, classMetadata);
  24163. if (parentType) {
  24164. const parentMethodNames = this._methodNames(parentType);
  24165. Object.keys(parentMethodNames).forEach((parentProp) => {
  24166. methodNames[parentProp] = parentMethodNames[parentProp];
  24167. });
  24168. }
  24169. const members = classMetadata['members'] || {};
  24170. Object.keys(members).forEach((propName) => {
  24171. const propData = members[propName];
  24172. const isMethod = propData.some(a => a['__symbolic'] == 'method');
  24173. methodNames[propName] = methodNames[propName] || isMethod;
  24174. });
  24175. this.methodCache.set(type, methodNames);
  24176. }
  24177. return methodNames;
  24178. }
  24179. _staticMembers(type) {
  24180. let staticMembers = this.staticCache.get(type);
  24181. if (!staticMembers) {
  24182. const classMetadata = this.getTypeMetadata(type);
  24183. const staticMemberData = classMetadata['statics'] || {};
  24184. staticMembers = Object.keys(staticMemberData);
  24185. this.staticCache.set(type, staticMembers);
  24186. }
  24187. return staticMembers;
  24188. }
  24189. findParentType(type, classMetadata) {
  24190. const parentType = this.trySimplify(type, classMetadata['extends']);
  24191. if (parentType instanceof StaticSymbol) {
  24192. return parentType;
  24193. }
  24194. }
  24195. hasLifecycleHook(type, lcProperty) {
  24196. if (!(type instanceof StaticSymbol)) {
  24197. this.reportError(new Error(`hasLifecycleHook received ${JSON.stringify(type)} which is not a StaticSymbol`), type);
  24198. }
  24199. try {
  24200. return !!this._methodNames(type)[lcProperty];
  24201. }
  24202. catch (e) {
  24203. console.error(`Failed on type ${JSON.stringify(type)} with error ${e}`);
  24204. throw e;
  24205. }
  24206. }
  24207. guards(type) {
  24208. if (!(type instanceof StaticSymbol)) {
  24209. this.reportError(new Error(`guards received ${JSON.stringify(type)} which is not a StaticSymbol`), type);
  24210. return {};
  24211. }
  24212. const staticMembers = this._staticMembers(type);
  24213. const result = {};
  24214. for (let name of staticMembers) {
  24215. if (name.endsWith(TYPEGUARD_POSTFIX)) {
  24216. let property = name.substr(0, name.length - TYPEGUARD_POSTFIX.length);
  24217. let value;
  24218. if (property.endsWith(USE_IF)) {
  24219. property = name.substr(0, property.length - USE_IF.length);
  24220. value = USE_IF;
  24221. }
  24222. else {
  24223. value = this.getStaticSymbol(type.filePath, type.name, [name]);
  24224. }
  24225. result[property] = value;
  24226. }
  24227. }
  24228. return result;
  24229. }
  24230. _registerDecoratorOrConstructor(type, ctor) {
  24231. this.conversionMap.set(type, (context, args) => new ctor(...args));
  24232. }
  24233. _registerFunction(type, fn) {
  24234. this.conversionMap.set(type, (context, args) => fn.apply(undefined, args));
  24235. }
  24236. initializeConversionMap() {
  24237. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
  24238. this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
  24239. this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
  24240. this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
  24241. this.ANALYZE_FOR_ENTRY_COMPONENTS =
  24242. this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
  24243. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  24244. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  24245. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  24246. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
  24247. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  24248. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
  24249. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
  24250. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
  24251. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
  24252. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
  24253. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
  24254. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
  24255. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
  24256. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
  24257. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
  24258. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
  24259. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
  24260. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
  24261. // Note: Some metadata classes can be used directly with Provider.deps.
  24262. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  24263. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  24264. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  24265. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  24266. }
  24267. /**
  24268. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  24269. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  24270. *
  24271. * @param declarationFile the absolute path of the file where the symbol is declared
  24272. * @param name the name of the type.
  24273. */
  24274. getStaticSymbol(declarationFile, name, members) {
  24275. return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
  24276. }
  24277. /**
  24278. * Simplify but discard any errors
  24279. */
  24280. trySimplify(context, value) {
  24281. const originalRecorder = this.errorRecorder;
  24282. this.errorRecorder = (error, fileName) => { };
  24283. const result = this.simplify(context, value);
  24284. this.errorRecorder = originalRecorder;
  24285. return result;
  24286. }
  24287. /** @internal */
  24288. simplify(context, value, lazy = false) {
  24289. const self = this;
  24290. let scope = BindingScope$1.empty;
  24291. const calling = new Map();
  24292. function simplifyInContext(context, value, depth, references) {
  24293. function resolveReferenceValue(staticSymbol) {
  24294. const resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
  24295. return resolvedSymbol ? resolvedSymbol.metadata : null;
  24296. }
  24297. function simplifyEagerly(value) {
  24298. return simplifyInContext(context, value, depth, 0);
  24299. }
  24300. function simplifyLazily(value) {
  24301. return simplifyInContext(context, value, depth, references + 1);
  24302. }
  24303. function simplifyNested(nestedContext, value) {
  24304. if (nestedContext === context) {
  24305. // If the context hasn't changed let the exception propagate unmodified.
  24306. return simplifyInContext(nestedContext, value, depth + 1, references);
  24307. }
  24308. try {
  24309. return simplifyInContext(nestedContext, value, depth + 1, references);
  24310. }
  24311. catch (e) {
  24312. if (isMetadataError(e)) {
  24313. // Propagate the message text up but add a message to the chain that explains how we got
  24314. // here.
  24315. // e.chain implies e.symbol
  24316. const summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
  24317. const summary = `'${nestedContext.name}' ${summaryMsg}`;
  24318. const chain = { message: summary, position: e.position, next: e.chain };
  24319. // TODO(chuckj): retrieve the position information indirectly from the collectors node
  24320. // map if the metadata is from a .ts file.
  24321. self.error({
  24322. message: e.message,
  24323. advise: e.advise,
  24324. context: e.context, chain,
  24325. symbol: nestedContext
  24326. }, context);
  24327. }
  24328. else {
  24329. // It is probably an internal error.
  24330. throw e;
  24331. }
  24332. }
  24333. }
  24334. function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
  24335. if (targetFunction && targetFunction['__symbolic'] == 'function') {
  24336. if (calling.get(functionSymbol)) {
  24337. self.error({
  24338. message: 'Recursion is not supported',
  24339. summary: `called '${functionSymbol.name}' recursively`,
  24340. value: targetFunction
  24341. }, functionSymbol);
  24342. }
  24343. try {
  24344. const value = targetFunction['value'];
  24345. if (value && (depth != 0 || value.__symbolic != 'error')) {
  24346. const parameters = targetFunction['parameters'];
  24347. const defaults = targetFunction.defaults;
  24348. args = args.map(arg => simplifyNested(context, arg))
  24349. .map(arg => shouldIgnore(arg) ? undefined : arg);
  24350. if (defaults && defaults.length > args.length) {
  24351. args.push(...defaults.slice(args.length).map((value) => simplify(value)));
  24352. }
  24353. calling.set(functionSymbol, true);
  24354. const functionScope = BindingScope$1.build();
  24355. for (let i = 0; i < parameters.length; i++) {
  24356. functionScope.define(parameters[i], args[i]);
  24357. }
  24358. const oldScope = scope;
  24359. let result;
  24360. try {
  24361. scope = functionScope.done();
  24362. result = simplifyNested(functionSymbol, value);
  24363. }
  24364. finally {
  24365. scope = oldScope;
  24366. }
  24367. return result;
  24368. }
  24369. }
  24370. finally {
  24371. calling.delete(functionSymbol);
  24372. }
  24373. }
  24374. if (depth === 0) {
  24375. // If depth is 0 we are evaluating the top level expression that is describing element
  24376. // decorator. In this case, it is a decorator we don't understand, such as a custom
  24377. // non-angular decorator, and we should just ignore it.
  24378. return IGNORE;
  24379. }
  24380. let position = undefined;
  24381. if (targetExpression && targetExpression.__symbolic == 'resolved') {
  24382. const line = targetExpression.line;
  24383. const character = targetExpression.character;
  24384. const fileName = targetExpression.fileName;
  24385. if (fileName != null && line != null && character != null) {
  24386. position = { fileName, line, column: character };
  24387. }
  24388. }
  24389. self.error({
  24390. message: FUNCTION_CALL_NOT_SUPPORTED,
  24391. context: functionSymbol,
  24392. value: targetFunction, position
  24393. }, context);
  24394. }
  24395. function simplify(expression) {
  24396. if (isPrimitive(expression)) {
  24397. return expression;
  24398. }
  24399. if (expression instanceof Array) {
  24400. const result = [];
  24401. for (const item of expression) {
  24402. // Check for a spread expression
  24403. if (item && item.__symbolic === 'spread') {
  24404. // We call with references as 0 because we require the actual value and cannot
  24405. // tolerate a reference here.
  24406. const spreadArray = simplifyEagerly(item.expression);
  24407. if (Array.isArray(spreadArray)) {
  24408. for (const spreadItem of spreadArray) {
  24409. result.push(spreadItem);
  24410. }
  24411. continue;
  24412. }
  24413. }
  24414. const value = simplify(item);
  24415. if (shouldIgnore(value)) {
  24416. continue;
  24417. }
  24418. result.push(value);
  24419. }
  24420. return result;
  24421. }
  24422. if (expression instanceof StaticSymbol) {
  24423. // Stop simplification at builtin symbols or if we are in a reference context and
  24424. // the symbol doesn't have members.
  24425. if (expression === self.injectionToken || self.conversionMap.has(expression) ||
  24426. (references > 0 && !expression.members.length)) {
  24427. return expression;
  24428. }
  24429. else {
  24430. const staticSymbol = expression;
  24431. const declarationValue = resolveReferenceValue(staticSymbol);
  24432. if (declarationValue != null) {
  24433. return simplifyNested(staticSymbol, declarationValue);
  24434. }
  24435. else {
  24436. return staticSymbol;
  24437. }
  24438. }
  24439. }
  24440. if (expression) {
  24441. if (expression['__symbolic']) {
  24442. let staticSymbol;
  24443. switch (expression['__symbolic']) {
  24444. case 'binop':
  24445. let left = simplify(expression['left']);
  24446. if (shouldIgnore(left))
  24447. return left;
  24448. let right = simplify(expression['right']);
  24449. if (shouldIgnore(right))
  24450. return right;
  24451. switch (expression['operator']) {
  24452. case '&&':
  24453. return left && right;
  24454. case '||':
  24455. return left || right;
  24456. case '|':
  24457. return left | right;
  24458. case '^':
  24459. return left ^ right;
  24460. case '&':
  24461. return left & right;
  24462. case '==':
  24463. return left == right;
  24464. case '!=':
  24465. return left != right;
  24466. case '===':
  24467. return left === right;
  24468. case '!==':
  24469. return left !== right;
  24470. case '<':
  24471. return left < right;
  24472. case '>':
  24473. return left > right;
  24474. case '<=':
  24475. return left <= right;
  24476. case '>=':
  24477. return left >= right;
  24478. case '<<':
  24479. return left << right;
  24480. case '>>':
  24481. return left >> right;
  24482. case '+':
  24483. return left + right;
  24484. case '-':
  24485. return left - right;
  24486. case '*':
  24487. return left * right;
  24488. case '/':
  24489. return left / right;
  24490. case '%':
  24491. return left % right;
  24492. }
  24493. return null;
  24494. case 'if':
  24495. let condition = simplify(expression['condition']);
  24496. return condition ? simplify(expression['thenExpression']) :
  24497. simplify(expression['elseExpression']);
  24498. case 'pre':
  24499. let operand = simplify(expression['operand']);
  24500. if (shouldIgnore(operand))
  24501. return operand;
  24502. switch (expression['operator']) {
  24503. case '+':
  24504. return operand;
  24505. case '-':
  24506. return -operand;
  24507. case '!':
  24508. return !operand;
  24509. case '~':
  24510. return ~operand;
  24511. }
  24512. return null;
  24513. case 'index':
  24514. let indexTarget = simplifyEagerly(expression['expression']);
  24515. let index = simplifyEagerly(expression['index']);
  24516. if (indexTarget && isPrimitive(index))
  24517. return indexTarget[index];
  24518. return null;
  24519. case 'select':
  24520. const member = expression['member'];
  24521. let selectContext = context;
  24522. let selectTarget = simplify(expression['expression']);
  24523. if (selectTarget instanceof StaticSymbol) {
  24524. const members = selectTarget.members.concat(member);
  24525. selectContext =
  24526. self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
  24527. const declarationValue = resolveReferenceValue(selectContext);
  24528. if (declarationValue != null) {
  24529. return simplifyNested(selectContext, declarationValue);
  24530. }
  24531. else {
  24532. return selectContext;
  24533. }
  24534. }
  24535. if (selectTarget && isPrimitive(member))
  24536. return simplifyNested(selectContext, selectTarget[member]);
  24537. return null;
  24538. case 'reference':
  24539. // Note: This only has to deal with variable references, as symbol references have
  24540. // been converted into 'resolved'
  24541. // in the StaticSymbolResolver.
  24542. const name = expression['name'];
  24543. const localValue = scope.resolve(name);
  24544. if (localValue != BindingScope$1.missing) {
  24545. return localValue;
  24546. }
  24547. break;
  24548. case 'resolved':
  24549. try {
  24550. return simplify(expression.symbol);
  24551. }
  24552. catch (e) {
  24553. // If an error is reported evaluating the symbol record the position of the
  24554. // reference in the error so it can
  24555. // be reported in the error message generated from the exception.
  24556. if (isMetadataError(e) && expression.fileName != null &&
  24557. expression.line != null && expression.character != null) {
  24558. e.position = {
  24559. fileName: expression.fileName,
  24560. line: expression.line,
  24561. column: expression.character
  24562. };
  24563. }
  24564. throw e;
  24565. }
  24566. case 'class':
  24567. return context;
  24568. case 'function':
  24569. return context;
  24570. case 'new':
  24571. case 'call':
  24572. // Determine if the function is a built-in conversion
  24573. staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
  24574. if (staticSymbol instanceof StaticSymbol) {
  24575. if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
  24576. // if somebody calls new InjectionToken, don't create an InjectionToken,
  24577. // but rather return the symbol to which the InjectionToken is assigned to.
  24578. // OpaqueToken is supported too as it is required by the language service to
  24579. // support v4 and prior versions of Angular.
  24580. return context;
  24581. }
  24582. const argExpressions = expression['arguments'] || [];
  24583. let converter = self.conversionMap.get(staticSymbol);
  24584. if (converter) {
  24585. const args = argExpressions.map(arg => simplifyNested(context, arg))
  24586. .map(arg => shouldIgnore(arg) ? undefined : arg);
  24587. return converter(context, args);
  24588. }
  24589. else {
  24590. // Determine if the function is one we can simplify.
  24591. const targetFunction = resolveReferenceValue(staticSymbol);
  24592. return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
  24593. }
  24594. }
  24595. return IGNORE;
  24596. case 'error':
  24597. let message = expression.message;
  24598. if (expression['line'] != null) {
  24599. self.error({
  24600. message,
  24601. context: expression.context,
  24602. value: expression,
  24603. position: {
  24604. fileName: expression['fileName'],
  24605. line: expression['line'],
  24606. column: expression['character']
  24607. }
  24608. }, context);
  24609. }
  24610. else {
  24611. self.error({ message, context: expression.context }, context);
  24612. }
  24613. return IGNORE;
  24614. case 'ignore':
  24615. return expression;
  24616. }
  24617. return null;
  24618. }
  24619. return mapStringMap(expression, (value, name) => {
  24620. if (REFERENCE_SET.has(name)) {
  24621. if (name === USE_VALUE$1 && PROVIDE in expression) {
  24622. // If this is a provider expression, check for special tokens that need the value
  24623. // during analysis.
  24624. const provide = simplify(expression.provide);
  24625. if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
  24626. return simplify(value);
  24627. }
  24628. }
  24629. return simplifyLazily(value);
  24630. }
  24631. return simplify(value);
  24632. });
  24633. }
  24634. return IGNORE;
  24635. }
  24636. return simplify(value);
  24637. }
  24638. let result;
  24639. try {
  24640. result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
  24641. }
  24642. catch (e) {
  24643. if (this.errorRecorder) {
  24644. this.reportError(e, context);
  24645. }
  24646. else {
  24647. throw formatMetadataError(e, context);
  24648. }
  24649. }
  24650. if (shouldIgnore(result)) {
  24651. return undefined;
  24652. }
  24653. return result;
  24654. }
  24655. getTypeMetadata(type) {
  24656. const resolvedSymbol = this.symbolResolver.resolveSymbol(type);
  24657. return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
  24658. { __symbolic: 'class' };
  24659. }
  24660. reportError(error, context, path) {
  24661. if (this.errorRecorder) {
  24662. this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
  24663. }
  24664. else {
  24665. throw error;
  24666. }
  24667. }
  24668. error({ message, summary, advise, position, context, value, symbol, chain }, reportingContext) {
  24669. this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
  24670. }
  24671. }
  24672. const METADATA_ERROR = 'ngMetadataError';
  24673. function metadataError(message, summary, advise, position, symbol, context, chain) {
  24674. const error = syntaxError(message);
  24675. error[METADATA_ERROR] = true;
  24676. if (advise)
  24677. error.advise = advise;
  24678. if (position)
  24679. error.position = position;
  24680. if (summary)
  24681. error.summary = summary;
  24682. if (context)
  24683. error.context = context;
  24684. if (chain)
  24685. error.chain = chain;
  24686. if (symbol)
  24687. error.symbol = symbol;
  24688. return error;
  24689. }
  24690. function isMetadataError(error) {
  24691. return !!error[METADATA_ERROR];
  24692. }
  24693. const REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
  24694. const VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
  24695. const DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
  24696. const COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
  24697. const FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
  24698. const REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
  24699. const LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
  24700. function expandedMessage(message, context) {
  24701. switch (message) {
  24702. case REFERENCE_TO_NONEXPORTED_CLASS:
  24703. if (context && context.className) {
  24704. return `References to a non-exported class are not supported in decorators but ${context.className} was referenced.`;
  24705. }
  24706. break;
  24707. case VARIABLE_NOT_INITIALIZED:
  24708. return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
  24709. case DESTRUCTURE_NOT_SUPPORTED:
  24710. return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
  24711. case COULD_NOT_RESOLVE_TYPE:
  24712. if (context && context.typeName) {
  24713. return `Could not resolve type ${context.typeName}`;
  24714. }
  24715. break;
  24716. case FUNCTION_CALL_NOT_SUPPORTED:
  24717. if (context && context.name) {
  24718. return `Function calls are not supported in decorators but '${context.name}' was called`;
  24719. }
  24720. return 'Function calls are not supported in decorators';
  24721. case REFERENCE_TO_LOCAL_SYMBOL:
  24722. if (context && context.name) {
  24723. return `Reference to a local (non-exported) symbols are not supported in decorators but '${context.name}' was referenced`;
  24724. }
  24725. break;
  24726. case LAMBDA_NOT_SUPPORTED:
  24727. return `Function expressions are not supported in decorators`;
  24728. }
  24729. return message;
  24730. }
  24731. function messageAdvise(message, context) {
  24732. switch (message) {
  24733. case REFERENCE_TO_NONEXPORTED_CLASS:
  24734. if (context && context.className) {
  24735. return `Consider exporting '${context.className}'`;
  24736. }
  24737. break;
  24738. case DESTRUCTURE_NOT_SUPPORTED:
  24739. return 'Consider simplifying to avoid destructuring';
  24740. case REFERENCE_TO_LOCAL_SYMBOL:
  24741. if (context && context.name) {
  24742. return `Consider exporting '${context.name}'`;
  24743. }
  24744. break;
  24745. case LAMBDA_NOT_SUPPORTED:
  24746. return `Consider changing the function expression into an exported function`;
  24747. }
  24748. return undefined;
  24749. }
  24750. function errorSummary(error) {
  24751. if (error.summary) {
  24752. return error.summary;
  24753. }
  24754. switch (error.message) {
  24755. case REFERENCE_TO_NONEXPORTED_CLASS:
  24756. if (error.context && error.context.className) {
  24757. return `references non-exported class ${error.context.className}`;
  24758. }
  24759. break;
  24760. case VARIABLE_NOT_INITIALIZED:
  24761. return 'is not initialized';
  24762. case DESTRUCTURE_NOT_SUPPORTED:
  24763. return 'is a destructured variable';
  24764. case COULD_NOT_RESOLVE_TYPE:
  24765. return 'could not be resolved';
  24766. case FUNCTION_CALL_NOT_SUPPORTED:
  24767. if (error.context && error.context.name) {
  24768. return `calls '${error.context.name}'`;
  24769. }
  24770. return `calls a function`;
  24771. case REFERENCE_TO_LOCAL_SYMBOL:
  24772. if (error.context && error.context.name) {
  24773. return `references local variable ${error.context.name}`;
  24774. }
  24775. return `references a local variable`;
  24776. }
  24777. return 'contains the error';
  24778. }
  24779. function mapStringMap(input, transform) {
  24780. if (!input)
  24781. return {};
  24782. const result = {};
  24783. Object.keys(input).forEach((key) => {
  24784. const value = transform(input[key], key);
  24785. if (!shouldIgnore(value)) {
  24786. if (HIDDEN_KEY.test(key)) {
  24787. Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
  24788. }
  24789. else {
  24790. result[key] = value;
  24791. }
  24792. }
  24793. });
  24794. return result;
  24795. }
  24796. function isPrimitive(o) {
  24797. return o === null || (typeof o !== 'function' && typeof o !== 'object');
  24798. }
  24799. class BindingScope$1 {
  24800. static build() {
  24801. const current = new Map();
  24802. return {
  24803. define: function (name, value) {
  24804. current.set(name, value);
  24805. return this;
  24806. },
  24807. done: function () {
  24808. return current.size > 0 ? new PopulatedScope(current) : BindingScope$1.empty;
  24809. }
  24810. };
  24811. }
  24812. }
  24813. BindingScope$1.missing = {};
  24814. BindingScope$1.empty = { resolve: name => BindingScope$1.missing };
  24815. class PopulatedScope extends BindingScope$1 {
  24816. constructor(bindings) {
  24817. super();
  24818. this.bindings = bindings;
  24819. }
  24820. resolve(name) {
  24821. return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
  24822. }
  24823. }
  24824. function formatMetadataMessageChain(chain, advise) {
  24825. const expanded = expandedMessage(chain.message, chain.context);
  24826. const nesting = chain.symbol ? ` in '${chain.symbol.name}'` : '';
  24827. const message = `${expanded}${nesting}`;
  24828. const position = chain.position;
  24829. const next = chain.next ?
  24830. formatMetadataMessageChain(chain.next, advise) :
  24831. advise ? { message: advise } : undefined;
  24832. return { message, position, next };
  24833. }
  24834. function formatMetadataError(e, context) {
  24835. if (isMetadataError(e)) {
  24836. // Produce a formatted version of the and leaving enough information in the original error
  24837. // to recover the formatting information to eventually produce a diagnostic error message.
  24838. const position = e.position;
  24839. const chain = {
  24840. message: `Error during template compile of '${context.name}'`,
  24841. position: position,
  24842. next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
  24843. };
  24844. const advise = e.advise || messageAdvise(e.message, e.context);
  24845. return formattedError(formatMetadataMessageChain(chain, advise));
  24846. }
  24847. return e;
  24848. }
  24849. /**
  24850. * @license
  24851. * Copyright Google Inc. All Rights Reserved.
  24852. *
  24853. * Use of this source code is governed by an MIT-style license that can be
  24854. * found in the LICENSE file at https://angular.io/license
  24855. */
  24856. class AotSummaryResolver {
  24857. constructor(host, staticSymbolCache) {
  24858. this.host = host;
  24859. this.staticSymbolCache = staticSymbolCache;
  24860. // Note: this will only contain StaticSymbols without members!
  24861. this.summaryCache = new Map();
  24862. this.loadedFilePaths = new Map();
  24863. // Note: this will only contain StaticSymbols without members!
  24864. this.importAs = new Map();
  24865. this.knownFileNameToModuleNames = new Map();
  24866. }
  24867. isLibraryFile(filePath) {
  24868. // Note: We need to strip the .ngfactory. file path,
  24869. // so this method also works for generated files
  24870. // (for which host.isSourceFile will always return false).
  24871. return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
  24872. }
  24873. toSummaryFileName(filePath, referringSrcFileName) {
  24874. return this.host.toSummaryFileName(filePath, referringSrcFileName);
  24875. }
  24876. fromSummaryFileName(fileName, referringLibFileName) {
  24877. return this.host.fromSummaryFileName(fileName, referringLibFileName);
  24878. }
  24879. resolveSummary(staticSymbol) {
  24880. const rootSymbol = staticSymbol.members.length ?
  24881. this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
  24882. staticSymbol;
  24883. let summary = this.summaryCache.get(rootSymbol);
  24884. if (!summary) {
  24885. this._loadSummaryFile(staticSymbol.filePath);
  24886. summary = this.summaryCache.get(staticSymbol);
  24887. }
  24888. return (rootSymbol === staticSymbol && summary) || null;
  24889. }
  24890. getSymbolsOf(filePath) {
  24891. if (this._loadSummaryFile(filePath)) {
  24892. return Array.from(this.summaryCache.keys()).filter((symbol) => symbol.filePath === filePath);
  24893. }
  24894. return null;
  24895. }
  24896. getImportAs(staticSymbol) {
  24897. staticSymbol.assertNoMembers();
  24898. return this.importAs.get(staticSymbol);
  24899. }
  24900. /**
  24901. * Converts a file path to a module name that can be used as an `import`.
  24902. */
  24903. getKnownModuleName(importedFilePath) {
  24904. return this.knownFileNameToModuleNames.get(importedFilePath) || null;
  24905. }
  24906. addSummary(summary) { this.summaryCache.set(summary.symbol, summary); }
  24907. _loadSummaryFile(filePath) {
  24908. let hasSummary = this.loadedFilePaths.get(filePath);
  24909. if (hasSummary != null) {
  24910. return hasSummary;
  24911. }
  24912. let json = null;
  24913. if (this.isLibraryFile(filePath)) {
  24914. const summaryFilePath = summaryFileName(filePath);
  24915. try {
  24916. json = this.host.loadSummary(summaryFilePath);
  24917. }
  24918. catch (e) {
  24919. console.error(`Error loading summary file ${summaryFilePath}`);
  24920. throw e;
  24921. }
  24922. }
  24923. hasSummary = json != null;
  24924. this.loadedFilePaths.set(filePath, hasSummary);
  24925. if (json) {
  24926. const { moduleName, summaries, importAs } = deserializeSummaries(this.staticSymbolCache, this, filePath, json);
  24927. summaries.forEach((summary) => this.summaryCache.set(summary.symbol, summary));
  24928. if (moduleName) {
  24929. this.knownFileNameToModuleNames.set(filePath, moduleName);
  24930. }
  24931. importAs.forEach((importAs) => { this.importAs.set(importAs.symbol, importAs.importAs); });
  24932. }
  24933. return hasSummary;
  24934. }
  24935. }
  24936. /**
  24937. * @license
  24938. * Copyright Google Inc. All Rights Reserved.
  24939. *
  24940. * Use of this source code is governed by an MIT-style license that can be
  24941. * found in the LICENSE file at https://angular.io/license
  24942. */
  24943. function createAotUrlResolver(host) {
  24944. return {
  24945. resolve: (basePath, url) => {
  24946. const filePath = host.resourceNameToFileName(url, basePath);
  24947. if (!filePath) {
  24948. throw syntaxError(`Couldn't resolve resource ${url} from ${basePath}`);
  24949. }
  24950. return filePath;
  24951. }
  24952. };
  24953. }
  24954. /**
  24955. * Creates a new AotCompiler based on options and a host.
  24956. */
  24957. function createAotCompiler(compilerHost, options, errorCollector) {
  24958. let translations = options.translations || '';
  24959. const urlResolver = createAotUrlResolver(compilerHost);
  24960. const symbolCache = new StaticSymbolCache();
  24961. const summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
  24962. const symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
  24963. const staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector);
  24964. let htmlParser;
  24965. if (!!options.enableIvy) {
  24966. // Ivy handles i18n at the compiler level so we must use a regular parser
  24967. htmlParser = new HtmlParser();
  24968. }
  24969. else {
  24970. htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console);
  24971. }
  24972. const config = new CompilerConfig({
  24973. defaultEncapsulation: ViewEncapsulation.Emulated,
  24974. useJit: false,
  24975. missingTranslation: options.missingTranslation,
  24976. preserveWhitespaces: options.preserveWhitespaces,
  24977. strictInjectionParameters: options.strictInjectionParameters,
  24978. });
  24979. const normalizer = new DirectiveNormalizer({ get: (url) => compilerHost.loadResource(url) }, urlResolver, htmlParser, config);
  24980. const expressionParser = new Parser$1(new Lexer());
  24981. const elementSchemaRegistry = new DomElementSchemaRegistry();
  24982. const tmplParser = new TemplateParser(config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []);
  24983. const resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector);
  24984. // TODO(vicb): do not pass options.i18nFormat here
  24985. const viewCompiler = new ViewCompiler(staticReflector);
  24986. const typeCheckCompiler = new TypeCheckCompiler(options, staticReflector);
  24987. const compiler = new AotCompiler(config, options, compilerHost, staticReflector, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, typeCheckCompiler, new NgModuleCompiler(staticReflector), new InjectableCompiler(staticReflector, !!options.enableIvy), new TypeScriptEmitter(), summaryResolver, symbolResolver);
  24988. return { compiler, reflector: staticReflector };
  24989. }
  24990. class SummaryResolver {
  24991. }
  24992. class JitSummaryResolver {
  24993. constructor() {
  24994. this._summaries = new Map();
  24995. }
  24996. isLibraryFile() { return false; }
  24997. toSummaryFileName(fileName) { return fileName; }
  24998. fromSummaryFileName(fileName) { return fileName; }
  24999. resolveSummary(reference) {
  25000. return this._summaries.get(reference) || null;
  25001. }
  25002. getSymbolsOf() { return []; }
  25003. getImportAs(reference) { return reference; }
  25004. getKnownModuleName(fileName) { return null; }
  25005. addSummary(summary) { this._summaries.set(summary.symbol, summary); }
  25006. }
  25007. /**
  25008. * @license
  25009. * Copyright Google Inc. All Rights Reserved.
  25010. *
  25011. * Use of this source code is governed by an MIT-style license that can be
  25012. * found in the LICENSE file at https://angular.io/license
  25013. */
  25014. function interpretStatements(statements, reflector) {
  25015. const ctx = new _ExecutionContext(null, null, null, new Map());
  25016. const visitor = new StatementInterpreter(reflector);
  25017. visitor.visitAllStatements(statements, ctx);
  25018. const result = {};
  25019. ctx.exports.forEach((exportName) => { result[exportName] = ctx.vars.get(exportName); });
  25020. return result;
  25021. }
  25022. function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
  25023. const childCtx = ctx.createChildWihtLocalVars();
  25024. for (let i = 0; i < varNames.length; i++) {
  25025. childCtx.vars.set(varNames[i], varValues[i]);
  25026. }
  25027. const result = visitor.visitAllStatements(statements, childCtx);
  25028. return result ? result.value : null;
  25029. }
  25030. class _ExecutionContext {
  25031. constructor(parent, instance, className, vars) {
  25032. this.parent = parent;
  25033. this.instance = instance;
  25034. this.className = className;
  25035. this.vars = vars;
  25036. this.exports = [];
  25037. }
  25038. createChildWihtLocalVars() {
  25039. return new _ExecutionContext(this, this.instance, this.className, new Map());
  25040. }
  25041. }
  25042. class ReturnValue {
  25043. constructor(value) {
  25044. this.value = value;
  25045. }
  25046. }
  25047. function createDynamicClass(_classStmt, _ctx, _visitor) {
  25048. const propertyDescriptors = {};
  25049. _classStmt.getters.forEach((getter) => {
  25050. // Note: use `function` instead of arrow function to capture `this`
  25051. propertyDescriptors[getter.name] = {
  25052. configurable: false,
  25053. get: function () {
  25054. const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  25055. return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
  25056. }
  25057. };
  25058. });
  25059. _classStmt.methods.forEach(function (method) {
  25060. const paramNames = method.params.map(param => param.name);
  25061. // Note: use `function` instead of arrow function to capture `this`
  25062. propertyDescriptors[method.name] = {
  25063. writable: false,
  25064. configurable: false,
  25065. value: function (...args) {
  25066. const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  25067. return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
  25068. }
  25069. };
  25070. });
  25071. const ctorParamNames = _classStmt.constructorMethod.params.map(param => param.name);
  25072. // Note: use `function` instead of arrow function to capture `this`
  25073. const ctor = function (...args) {
  25074. const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  25075. _classStmt.fields.forEach((field) => { this[field.name] = undefined; });
  25076. _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
  25077. };
  25078. const superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
  25079. ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
  25080. return ctor;
  25081. }
  25082. class StatementInterpreter {
  25083. constructor(reflector) {
  25084. this.reflector = reflector;
  25085. }
  25086. debugAst(ast) { return debugOutputAstAsTypeScript(ast); }
  25087. visitDeclareVarStmt(stmt, ctx) {
  25088. const initialValue = stmt.value ? stmt.value.visitExpression(this, ctx) : undefined;
  25089. ctx.vars.set(stmt.name, initialValue);
  25090. if (stmt.hasModifier(StmtModifier.Exported)) {
  25091. ctx.exports.push(stmt.name);
  25092. }
  25093. return null;
  25094. }
  25095. visitWriteVarExpr(expr, ctx) {
  25096. const value = expr.value.visitExpression(this, ctx);
  25097. let currCtx = ctx;
  25098. while (currCtx != null) {
  25099. if (currCtx.vars.has(expr.name)) {
  25100. currCtx.vars.set(expr.name, value);
  25101. return value;
  25102. }
  25103. currCtx = currCtx.parent;
  25104. }
  25105. throw new Error(`Not declared variable ${expr.name}`);
  25106. }
  25107. visitWrappedNodeExpr(ast, ctx) {
  25108. throw new Error('Cannot interpret a WrappedNodeExpr.');
  25109. }
  25110. visitTypeofExpr(ast, ctx) {
  25111. throw new Error('Cannot interpret a TypeofExpr');
  25112. }
  25113. visitReadVarExpr(ast, ctx) {
  25114. let varName = ast.name;
  25115. if (ast.builtin != null) {
  25116. switch (ast.builtin) {
  25117. case BuiltinVar.Super:
  25118. return ctx.instance.__proto__;
  25119. case BuiltinVar.This:
  25120. return ctx.instance;
  25121. case BuiltinVar.CatchError:
  25122. varName = CATCH_ERROR_VAR$2;
  25123. break;
  25124. case BuiltinVar.CatchStack:
  25125. varName = CATCH_STACK_VAR$2;
  25126. break;
  25127. default:
  25128. throw new Error(`Unknown builtin variable ${ast.builtin}`);
  25129. }
  25130. }
  25131. let currCtx = ctx;
  25132. while (currCtx != null) {
  25133. if (currCtx.vars.has(varName)) {
  25134. return currCtx.vars.get(varName);
  25135. }
  25136. currCtx = currCtx.parent;
  25137. }
  25138. throw new Error(`Not declared variable ${varName}`);
  25139. }
  25140. visitWriteKeyExpr(expr, ctx) {
  25141. const receiver = expr.receiver.visitExpression(this, ctx);
  25142. const index = expr.index.visitExpression(this, ctx);
  25143. const value = expr.value.visitExpression(this, ctx);
  25144. receiver[index] = value;
  25145. return value;
  25146. }
  25147. visitWritePropExpr(expr, ctx) {
  25148. const receiver = expr.receiver.visitExpression(this, ctx);
  25149. const value = expr.value.visitExpression(this, ctx);
  25150. receiver[expr.name] = value;
  25151. return value;
  25152. }
  25153. visitInvokeMethodExpr(expr, ctx) {
  25154. const receiver = expr.receiver.visitExpression(this, ctx);
  25155. const args = this.visitAllExpressions(expr.args, ctx);
  25156. let result;
  25157. if (expr.builtin != null) {
  25158. switch (expr.builtin) {
  25159. case BuiltinMethod.ConcatArray:
  25160. result = receiver.concat(...args);
  25161. break;
  25162. case BuiltinMethod.SubscribeObservable:
  25163. result = receiver.subscribe({ next: args[0] });
  25164. break;
  25165. case BuiltinMethod.Bind:
  25166. result = receiver.bind(...args);
  25167. break;
  25168. default:
  25169. throw new Error(`Unknown builtin method ${expr.builtin}`);
  25170. }
  25171. }
  25172. else {
  25173. result = receiver[expr.name].apply(receiver, args);
  25174. }
  25175. return result;
  25176. }
  25177. visitInvokeFunctionExpr(stmt, ctx) {
  25178. const args = this.visitAllExpressions(stmt.args, ctx);
  25179. const fnExpr = stmt.fn;
  25180. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
  25181. ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
  25182. return null;
  25183. }
  25184. else {
  25185. const fn = stmt.fn.visitExpression(this, ctx);
  25186. return fn.apply(null, args);
  25187. }
  25188. }
  25189. visitReturnStmt(stmt, ctx) {
  25190. return new ReturnValue(stmt.value.visitExpression(this, ctx));
  25191. }
  25192. visitDeclareClassStmt(stmt, ctx) {
  25193. const clazz = createDynamicClass(stmt, ctx, this);
  25194. ctx.vars.set(stmt.name, clazz);
  25195. if (stmt.hasModifier(StmtModifier.Exported)) {
  25196. ctx.exports.push(stmt.name);
  25197. }
  25198. return null;
  25199. }
  25200. visitExpressionStmt(stmt, ctx) {
  25201. return stmt.expr.visitExpression(this, ctx);
  25202. }
  25203. visitIfStmt(stmt, ctx) {
  25204. const condition = stmt.condition.visitExpression(this, ctx);
  25205. if (condition) {
  25206. return this.visitAllStatements(stmt.trueCase, ctx);
  25207. }
  25208. else if (stmt.falseCase != null) {
  25209. return this.visitAllStatements(stmt.falseCase, ctx);
  25210. }
  25211. return null;
  25212. }
  25213. visitTryCatchStmt(stmt, ctx) {
  25214. try {
  25215. return this.visitAllStatements(stmt.bodyStmts, ctx);
  25216. }
  25217. catch (e) {
  25218. const childCtx = ctx.createChildWihtLocalVars();
  25219. childCtx.vars.set(CATCH_ERROR_VAR$2, e);
  25220. childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
  25221. return this.visitAllStatements(stmt.catchStmts, childCtx);
  25222. }
  25223. }
  25224. visitThrowStmt(stmt, ctx) {
  25225. throw stmt.error.visitExpression(this, ctx);
  25226. }
  25227. visitCommentStmt(stmt, context) { return null; }
  25228. visitJSDocCommentStmt(stmt, context) { return null; }
  25229. visitInstantiateExpr(ast, ctx) {
  25230. const args = this.visitAllExpressions(ast.args, ctx);
  25231. const clazz = ast.classExpr.visitExpression(this, ctx);
  25232. return new clazz(...args);
  25233. }
  25234. visitLiteralExpr(ast, ctx) { return ast.value; }
  25235. visitExternalExpr(ast, ctx) {
  25236. return this.reflector.resolveExternalReference(ast.value);
  25237. }
  25238. visitConditionalExpr(ast, ctx) {
  25239. if (ast.condition.visitExpression(this, ctx)) {
  25240. return ast.trueCase.visitExpression(this, ctx);
  25241. }
  25242. else if (ast.falseCase != null) {
  25243. return ast.falseCase.visitExpression(this, ctx);
  25244. }
  25245. return null;
  25246. }
  25247. visitNotExpr(ast, ctx) {
  25248. return !ast.condition.visitExpression(this, ctx);
  25249. }
  25250. visitAssertNotNullExpr(ast, ctx) {
  25251. return ast.condition.visitExpression(this, ctx);
  25252. }
  25253. visitCastExpr(ast, ctx) {
  25254. return ast.value.visitExpression(this, ctx);
  25255. }
  25256. visitFunctionExpr(ast, ctx) {
  25257. const paramNames = ast.params.map((param) => param.name);
  25258. return _declareFn(paramNames, ast.statements, ctx, this);
  25259. }
  25260. visitDeclareFunctionStmt(stmt, ctx) {
  25261. const paramNames = stmt.params.map((param) => param.name);
  25262. ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
  25263. if (stmt.hasModifier(StmtModifier.Exported)) {
  25264. ctx.exports.push(stmt.name);
  25265. }
  25266. return null;
  25267. }
  25268. visitBinaryOperatorExpr(ast, ctx) {
  25269. const lhs = () => ast.lhs.visitExpression(this, ctx);
  25270. const rhs = () => ast.rhs.visitExpression(this, ctx);
  25271. switch (ast.operator) {
  25272. case BinaryOperator.Equals:
  25273. return lhs() == rhs();
  25274. case BinaryOperator.Identical:
  25275. return lhs() === rhs();
  25276. case BinaryOperator.NotEquals:
  25277. return lhs() != rhs();
  25278. case BinaryOperator.NotIdentical:
  25279. return lhs() !== rhs();
  25280. case BinaryOperator.And:
  25281. return lhs() && rhs();
  25282. case BinaryOperator.Or:
  25283. return lhs() || rhs();
  25284. case BinaryOperator.Plus:
  25285. return lhs() + rhs();
  25286. case BinaryOperator.Minus:
  25287. return lhs() - rhs();
  25288. case BinaryOperator.Divide:
  25289. return lhs() / rhs();
  25290. case BinaryOperator.Multiply:
  25291. return lhs() * rhs();
  25292. case BinaryOperator.Modulo:
  25293. return lhs() % rhs();
  25294. case BinaryOperator.Lower:
  25295. return lhs() < rhs();
  25296. case BinaryOperator.LowerEquals:
  25297. return lhs() <= rhs();
  25298. case BinaryOperator.Bigger:
  25299. return lhs() > rhs();
  25300. case BinaryOperator.BiggerEquals:
  25301. return lhs() >= rhs();
  25302. default:
  25303. throw new Error(`Unknown operator ${ast.operator}`);
  25304. }
  25305. }
  25306. visitReadPropExpr(ast, ctx) {
  25307. let result;
  25308. const receiver = ast.receiver.visitExpression(this, ctx);
  25309. result = receiver[ast.name];
  25310. return result;
  25311. }
  25312. visitReadKeyExpr(ast, ctx) {
  25313. const receiver = ast.receiver.visitExpression(this, ctx);
  25314. const prop = ast.index.visitExpression(this, ctx);
  25315. return receiver[prop];
  25316. }
  25317. visitLiteralArrayExpr(ast, ctx) {
  25318. return this.visitAllExpressions(ast.entries, ctx);
  25319. }
  25320. visitLiteralMapExpr(ast, ctx) {
  25321. const result = {};
  25322. ast.entries.forEach(entry => result[entry.key] = entry.value.visitExpression(this, ctx));
  25323. return result;
  25324. }
  25325. visitCommaExpr(ast, context) {
  25326. const values = this.visitAllExpressions(ast.parts, context);
  25327. return values[values.length - 1];
  25328. }
  25329. visitAllExpressions(expressions, ctx) {
  25330. return expressions.map((expr) => expr.visitExpression(this, ctx));
  25331. }
  25332. visitAllStatements(statements, ctx) {
  25333. for (let i = 0; i < statements.length; i++) {
  25334. const stmt = statements[i];
  25335. const val = stmt.visitStatement(this, ctx);
  25336. if (val instanceof ReturnValue) {
  25337. return val;
  25338. }
  25339. }
  25340. return null;
  25341. }
  25342. }
  25343. function _declareFn(varNames, statements, ctx, visitor) {
  25344. return (...args) => _executeFunctionStatements(varNames, args, statements, ctx, visitor);
  25345. }
  25346. const CATCH_ERROR_VAR$2 = 'error';
  25347. const CATCH_STACK_VAR$2 = 'stack';
  25348. /**
  25349. * @license
  25350. * Copyright Google Inc. All Rights Reserved.
  25351. *
  25352. * Use of this source code is governed by an MIT-style license that can be
  25353. * found in the LICENSE file at https://angular.io/license
  25354. */
  25355. /**
  25356. * An internal module of the Angular compiler that begins with component types,
  25357. * extracts templates, and eventually produces a compiled version of the component
  25358. * ready for linking into an application.
  25359. *
  25360. * @security When compiling templates at runtime, you must ensure that the entire template comes
  25361. * from a trusted source. Attacker-controlled data introduced by a template could expose your
  25362. * application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
  25363. */
  25364. class JitCompiler {
  25365. constructor(_metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _summaryResolver, _reflector, _jitEvaluator, _compilerConfig, _console, getExtraNgModuleProviders) {
  25366. this._metadataResolver = _metadataResolver;
  25367. this._templateParser = _templateParser;
  25368. this._styleCompiler = _styleCompiler;
  25369. this._viewCompiler = _viewCompiler;
  25370. this._ngModuleCompiler = _ngModuleCompiler;
  25371. this._summaryResolver = _summaryResolver;
  25372. this._reflector = _reflector;
  25373. this._jitEvaluator = _jitEvaluator;
  25374. this._compilerConfig = _compilerConfig;
  25375. this._console = _console;
  25376. this.getExtraNgModuleProviders = getExtraNgModuleProviders;
  25377. this._compiledTemplateCache = new Map();
  25378. this._compiledHostTemplateCache = new Map();
  25379. this._compiledDirectiveWrapperCache = new Map();
  25380. this._compiledNgModuleCache = new Map();
  25381. this._sharedStylesheetCount = 0;
  25382. this._addedAotSummaries = new Set();
  25383. }
  25384. compileModuleSync(moduleType) {
  25385. return SyncAsync.assertSync(this._compileModuleAndComponents(moduleType, true));
  25386. }
  25387. compileModuleAsync(moduleType) {
  25388. return Promise.resolve(this._compileModuleAndComponents(moduleType, false));
  25389. }
  25390. compileModuleAndAllComponentsSync(moduleType) {
  25391. return SyncAsync.assertSync(this._compileModuleAndAllComponents(moduleType, true));
  25392. }
  25393. compileModuleAndAllComponentsAsync(moduleType) {
  25394. return Promise.resolve(this._compileModuleAndAllComponents(moduleType, false));
  25395. }
  25396. getComponentFactory(component) {
  25397. const summary = this._metadataResolver.getDirectiveSummary(component);
  25398. return summary.componentFactory;
  25399. }
  25400. loadAotSummaries(summaries) {
  25401. this.clearCache();
  25402. this._addAotSummaries(summaries);
  25403. }
  25404. _addAotSummaries(fn) {
  25405. if (this._addedAotSummaries.has(fn)) {
  25406. return;
  25407. }
  25408. this._addedAotSummaries.add(fn);
  25409. const summaries = fn();
  25410. for (let i = 0; i < summaries.length; i++) {
  25411. const entry = summaries[i];
  25412. if (typeof entry === 'function') {
  25413. this._addAotSummaries(entry);
  25414. }
  25415. else {
  25416. const summary = entry;
  25417. this._summaryResolver.addSummary({ symbol: summary.type.reference, metadata: null, type: summary });
  25418. }
  25419. }
  25420. }
  25421. hasAotSummary(ref) { return !!this._summaryResolver.resolveSummary(ref); }
  25422. _filterJitIdentifiers(ids) {
  25423. return ids.map(mod => mod.reference).filter((ref) => !this.hasAotSummary(ref));
  25424. }
  25425. _compileModuleAndComponents(moduleType, isSync) {
  25426. return SyncAsync.then(this._loadModules(moduleType, isSync), () => {
  25427. this._compileComponents(moduleType, null);
  25428. return this._compileModule(moduleType);
  25429. });
  25430. }
  25431. _compileModuleAndAllComponents(moduleType, isSync) {
  25432. return SyncAsync.then(this._loadModules(moduleType, isSync), () => {
  25433. const componentFactories = [];
  25434. this._compileComponents(moduleType, componentFactories);
  25435. return {
  25436. ngModuleFactory: this._compileModule(moduleType),
  25437. componentFactories: componentFactories
  25438. };
  25439. });
  25440. }
  25441. _loadModules(mainModule, isSync) {
  25442. const loading = [];
  25443. const mainNgModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  25444. // Note: for runtime compilation, we want to transitively compile all modules,
  25445. // so we also need to load the declared directives / pipes for all nested modules.
  25446. this._filterJitIdentifiers(mainNgModule.transitiveModule.modules).forEach((nestedNgModule) => {
  25447. // getNgModuleMetadata only returns null if the value passed in is not an NgModule
  25448. const moduleMeta = this._metadataResolver.getNgModuleMetadata(nestedNgModule);
  25449. this._filterJitIdentifiers(moduleMeta.declaredDirectives).forEach((ref) => {
  25450. const promise = this._metadataResolver.loadDirectiveMetadata(moduleMeta.type.reference, ref, isSync);
  25451. if (promise) {
  25452. loading.push(promise);
  25453. }
  25454. });
  25455. this._filterJitIdentifiers(moduleMeta.declaredPipes)
  25456. .forEach((ref) => this._metadataResolver.getOrLoadPipeMetadata(ref));
  25457. });
  25458. return SyncAsync.all(loading);
  25459. }
  25460. _compileModule(moduleType) {
  25461. let ngModuleFactory = this._compiledNgModuleCache.get(moduleType);
  25462. if (!ngModuleFactory) {
  25463. const moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
  25464. // Always provide a bound Compiler
  25465. const extraProviders = this.getExtraNgModuleProviders(moduleMeta.type.reference);
  25466. const outputCtx = createOutputContext();
  25467. const compileResult = this._ngModuleCompiler.compile(outputCtx, moduleMeta, extraProviders);
  25468. ngModuleFactory = this._interpretOrJit(ngModuleJitUrl(moduleMeta), outputCtx.statements)[compileResult.ngModuleFactoryVar];
  25469. this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
  25470. }
  25471. return ngModuleFactory;
  25472. }
  25473. /**
  25474. * @internal
  25475. */
  25476. _compileComponents(mainModule, allComponentFactories) {
  25477. const ngModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  25478. const moduleByJitDirective = new Map();
  25479. const templates = new Set();
  25480. const transJitModules = this._filterJitIdentifiers(ngModule.transitiveModule.modules);
  25481. transJitModules.forEach((localMod) => {
  25482. const localModuleMeta = this._metadataResolver.getNgModuleMetadata(localMod);
  25483. this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach((dirRef) => {
  25484. moduleByJitDirective.set(dirRef, localModuleMeta);
  25485. const dirMeta = this._metadataResolver.getDirectiveMetadata(dirRef);
  25486. if (dirMeta.isComponent) {
  25487. templates.add(this._createCompiledTemplate(dirMeta, localModuleMeta));
  25488. if (allComponentFactories) {
  25489. const template = this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
  25490. templates.add(template);
  25491. allComponentFactories.push(dirMeta.componentFactory);
  25492. }
  25493. }
  25494. });
  25495. });
  25496. transJitModules.forEach((localMod) => {
  25497. const localModuleMeta = this._metadataResolver.getNgModuleMetadata(localMod);
  25498. this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach((dirRef) => {
  25499. const dirMeta = this._metadataResolver.getDirectiveMetadata(dirRef);
  25500. if (dirMeta.isComponent) {
  25501. dirMeta.entryComponents.forEach((entryComponentType) => {
  25502. const moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  25503. templates.add(this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  25504. });
  25505. }
  25506. });
  25507. localModuleMeta.entryComponents.forEach((entryComponentType) => {
  25508. if (!this.hasAotSummary(entryComponentType.componentType)) {
  25509. const moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  25510. templates.add(this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  25511. }
  25512. });
  25513. });
  25514. templates.forEach((template) => this._compileTemplate(template));
  25515. }
  25516. clearCacheFor(type) {
  25517. this._compiledNgModuleCache.delete(type);
  25518. this._metadataResolver.clearCacheFor(type);
  25519. this._compiledHostTemplateCache.delete(type);
  25520. const compiledTemplate = this._compiledTemplateCache.get(type);
  25521. if (compiledTemplate) {
  25522. this._compiledTemplateCache.delete(type);
  25523. }
  25524. }
  25525. clearCache() {
  25526. // Note: don't clear the _addedAotSummaries, as they don't change!
  25527. this._metadataResolver.clearCache();
  25528. this._compiledTemplateCache.clear();
  25529. this._compiledHostTemplateCache.clear();
  25530. this._compiledNgModuleCache.clear();
  25531. }
  25532. _createCompiledHostTemplate(compType, ngModule) {
  25533. if (!ngModule) {
  25534. throw new Error(`Component ${stringify(compType)} is not part of any NgModule or the module has not been imported into your module.`);
  25535. }
  25536. let compiledTemplate = this._compiledHostTemplateCache.get(compType);
  25537. if (!compiledTemplate) {
  25538. const compMeta = this._metadataResolver.getDirectiveMetadata(compType);
  25539. assertComponent(compMeta);
  25540. const hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta, compMeta.componentFactory.viewDefFactory);
  25541. compiledTemplate =
  25542. new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
  25543. this._compiledHostTemplateCache.set(compType, compiledTemplate);
  25544. }
  25545. return compiledTemplate;
  25546. }
  25547. _createCompiledTemplate(compMeta, ngModule) {
  25548. let compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
  25549. if (!compiledTemplate) {
  25550. assertComponent(compMeta);
  25551. compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
  25552. this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
  25553. }
  25554. return compiledTemplate;
  25555. }
  25556. _compileTemplate(template) {
  25557. if (template.isCompiled) {
  25558. return;
  25559. }
  25560. const compMeta = template.compMeta;
  25561. const externalStylesheetsByModuleUrl = new Map();
  25562. const outputContext = createOutputContext();
  25563. const componentStylesheet = this._styleCompiler.compileComponent(outputContext, compMeta);
  25564. compMeta.template.externalStylesheets.forEach((stylesheetMeta) => {
  25565. const compiledStylesheet = this._styleCompiler.compileStyles(createOutputContext(), compMeta, stylesheetMeta);
  25566. externalStylesheetsByModuleUrl.set(stylesheetMeta.moduleUrl, compiledStylesheet);
  25567. });
  25568. this._resolveStylesCompileResult(componentStylesheet, externalStylesheetsByModuleUrl);
  25569. const pipes = template.ngModule.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
  25570. const { template: parsedTemplate, pipes: usedPipes } = this._parseTemplate(compMeta, template.ngModule, template.directives);
  25571. const compileResult = this._viewCompiler.compileComponent(outputContext, compMeta, parsedTemplate, variable(componentStylesheet.stylesVar), usedPipes);
  25572. const evalResult = this._interpretOrJit(templateJitUrl(template.ngModule.type, template.compMeta), outputContext.statements);
  25573. const viewClass = evalResult[compileResult.viewClassVar];
  25574. const rendererType = evalResult[compileResult.rendererTypeVar];
  25575. template.compiled(viewClass, rendererType);
  25576. }
  25577. _parseTemplate(compMeta, ngModule, directiveIdentifiers) {
  25578. // Note: ! is ok here as components always have a template.
  25579. const preserveWhitespaces = compMeta.template.preserveWhitespaces;
  25580. const directives = directiveIdentifiers.map(dir => this._metadataResolver.getDirectiveSummary(dir.reference));
  25581. const pipes = ngModule.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
  25582. return this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  25583. }
  25584. _resolveStylesCompileResult(result, externalStylesheetsByModuleUrl) {
  25585. result.dependencies.forEach((dep, i) => {
  25586. const nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
  25587. const nestedStylesArr = this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
  25588. dep.setValue(nestedStylesArr);
  25589. });
  25590. }
  25591. _resolveAndEvalStylesCompileResult(result, externalStylesheetsByModuleUrl) {
  25592. this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
  25593. return this._interpretOrJit(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.outputCtx.statements)[result.stylesVar];
  25594. }
  25595. _interpretOrJit(sourceUrl, statements) {
  25596. if (!this._compilerConfig.useJit) {
  25597. return interpretStatements(statements, this._reflector);
  25598. }
  25599. else {
  25600. return this._jitEvaluator.evaluateStatements(sourceUrl, statements, this._reflector, this._compilerConfig.jitDevMode);
  25601. }
  25602. }
  25603. }
  25604. class CompiledTemplate {
  25605. constructor(isHost, compType, compMeta, ngModule, directives) {
  25606. this.isHost = isHost;
  25607. this.compType = compType;
  25608. this.compMeta = compMeta;
  25609. this.ngModule = ngModule;
  25610. this.directives = directives;
  25611. this._viewClass = null;
  25612. this.isCompiled = false;
  25613. }
  25614. compiled(viewClass, rendererType) {
  25615. this._viewClass = viewClass;
  25616. this.compMeta.componentViewType.setDelegate(viewClass);
  25617. for (let prop in rendererType) {
  25618. this.compMeta.rendererType[prop] = rendererType[prop];
  25619. }
  25620. this.isCompiled = true;
  25621. }
  25622. }
  25623. function assertComponent(meta) {
  25624. if (!meta.isComponent) {
  25625. throw new Error(`Could not compile '${identifierName(meta.type)}' because it is not a component.`);
  25626. }
  25627. }
  25628. function createOutputContext() {
  25629. const importExpr$1 = (symbol) => importExpr({ name: identifierName(symbol), moduleName: null, runtime: symbol });
  25630. return { statements: [], genFilePath: '', importExpr: importExpr$1, constantPool: new ConstantPool() };
  25631. }
  25632. /**
  25633. * @license
  25634. * Copyright Google Inc. All Rights Reserved.
  25635. *
  25636. * Use of this source code is governed by an MIT-style license that can be
  25637. * found in the LICENSE file at https://angular.io/license
  25638. */
  25639. /**
  25640. * Provides access to reflection data about symbols that the compiler needs.
  25641. */
  25642. class CompileReflector {
  25643. }
  25644. /**
  25645. * @license
  25646. * Copyright Google Inc. All Rights Reserved.
  25647. *
  25648. * Use of this source code is governed by an MIT-style license that can be
  25649. * found in the LICENSE file at https://angular.io/license
  25650. */
  25651. /**
  25652. * Create a {@link UrlResolver} with no package prefix.
  25653. */
  25654. function createUrlResolverWithoutPackagePrefix() {
  25655. return new UrlResolver();
  25656. }
  25657. function createOfflineCompileUrlResolver() {
  25658. return new UrlResolver('.');
  25659. }
  25660. const UrlResolver = class UrlResolverImpl {
  25661. constructor(_packagePrefix = null) {
  25662. this._packagePrefix = _packagePrefix;
  25663. }
  25664. /**
  25665. * Resolves the `url` given the `baseUrl`:
  25666. * - when the `url` is null, the `baseUrl` is returned,
  25667. * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
  25668. * `baseUrl` and `url`,
  25669. * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
  25670. * returned as is (ignoring the `baseUrl`)
  25671. */
  25672. resolve(baseUrl, url) {
  25673. let resolvedUrl = url;
  25674. if (baseUrl != null && baseUrl.length > 0) {
  25675. resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
  25676. }
  25677. const resolvedParts = _split(resolvedUrl);
  25678. let prefix = this._packagePrefix;
  25679. if (prefix != null && resolvedParts != null &&
  25680. resolvedParts[_ComponentIndex.Scheme] == 'package') {
  25681. let path = resolvedParts[_ComponentIndex.Path];
  25682. prefix = prefix.replace(/\/+$/, '');
  25683. path = path.replace(/^\/+/, '');
  25684. return `${prefix}/${path}`;
  25685. }
  25686. return resolvedUrl;
  25687. }
  25688. };
  25689. /**
  25690. * Extract the scheme of a URL.
  25691. */
  25692. function getUrlScheme(url) {
  25693. const match = _split(url);
  25694. return (match && match[_ComponentIndex.Scheme]) || '';
  25695. }
  25696. // The code below is adapted from Traceur:
  25697. // https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
  25698. /**
  25699. * Builds a URI string from already-encoded parts.
  25700. *
  25701. * No encoding is performed. Any component may be omitted as either null or
  25702. * undefined.
  25703. *
  25704. * @param opt_scheme The scheme such as 'http'.
  25705. * @param opt_userInfo The user name before the '@'.
  25706. * @param opt_domain The domain such as 'www.google.com', already
  25707. * URI-encoded.
  25708. * @param opt_port The port number.
  25709. * @param opt_path The path, already URI-encoded. If it is not
  25710. * empty, it must begin with a slash.
  25711. * @param opt_queryData The URI-encoded query data.
  25712. * @param opt_fragment The URI-encoded fragment identifier.
  25713. * @return The fully combined URI.
  25714. */
  25715. function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
  25716. const out = [];
  25717. if (opt_scheme != null) {
  25718. out.push(opt_scheme + ':');
  25719. }
  25720. if (opt_domain != null) {
  25721. out.push('//');
  25722. if (opt_userInfo != null) {
  25723. out.push(opt_userInfo + '@');
  25724. }
  25725. out.push(opt_domain);
  25726. if (opt_port != null) {
  25727. out.push(':' + opt_port);
  25728. }
  25729. }
  25730. if (opt_path != null) {
  25731. out.push(opt_path);
  25732. }
  25733. if (opt_queryData != null) {
  25734. out.push('?' + opt_queryData);
  25735. }
  25736. if (opt_fragment != null) {
  25737. out.push('#' + opt_fragment);
  25738. }
  25739. return out.join('');
  25740. }
  25741. /**
  25742. * A regular expression for breaking a URI into its component parts.
  25743. *
  25744. * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
  25745. * As the "first-match-wins" algorithm is identical to the "greedy"
  25746. * disambiguation method used by POSIX regular expressions, it is natural and
  25747. * commonplace to use a regular expression for parsing the potential five
  25748. * components of a URI reference.
  25749. *
  25750. * The following line is the regular expression for breaking-down a
  25751. * well-formed URI reference into its components.
  25752. *
  25753. * <pre>
  25754. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  25755. * 12 3 4 5 6 7 8 9
  25756. * </pre>
  25757. *
  25758. * The numbers in the second line above are only to assist readability; they
  25759. * indicate the reference points for each subexpression (i.e., each paired
  25760. * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
  25761. * For example, matching the above expression to
  25762. * <pre>
  25763. * http://www.ics.uci.edu/pub/ietf/uri/#Related
  25764. * </pre>
  25765. * results in the following subexpression matches:
  25766. * <pre>
  25767. * $1 = http:
  25768. * $2 = http
  25769. * $3 = //www.ics.uci.edu
  25770. * $4 = www.ics.uci.edu
  25771. * $5 = /pub/ietf/uri/
  25772. * $6 = <undefined>
  25773. * $7 = <undefined>
  25774. * $8 = #Related
  25775. * $9 = Related
  25776. * </pre>
  25777. * where <undefined> indicates that the component is not present, as is the
  25778. * case for the query component in the above example. Therefore, we can
  25779. * determine the value of the five components as
  25780. * <pre>
  25781. * scheme = $2
  25782. * authority = $4
  25783. * path = $5
  25784. * query = $7
  25785. * fragment = $9
  25786. * </pre>
  25787. *
  25788. * The regular expression has been modified slightly to expose the
  25789. * userInfo, domain, and port separately from the authority.
  25790. * The modified version yields
  25791. * <pre>
  25792. * $1 = http scheme
  25793. * $2 = <undefined> userInfo -\
  25794. * $3 = www.ics.uci.edu domain | authority
  25795. * $4 = <undefined> port -/
  25796. * $5 = /pub/ietf/uri/ path
  25797. * $6 = <undefined> query without ?
  25798. * $7 = Related fragment without #
  25799. * </pre>
  25800. * @internal
  25801. */
  25802. const _splitRe = new RegExp('^' +
  25803. '(?:' +
  25804. '([^:/?#.]+)' + // scheme - ignore special characters
  25805. // used by other URL parts such as :,
  25806. // ?, /, #, and .
  25807. ':)?' +
  25808. '(?://' +
  25809. '(?:([^/?#]*)@)?' + // userInfo
  25810. '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
  25811. // digits, dashes, dots, percent
  25812. // escapes, and unicode characters.
  25813. '(?::([0-9]+))?' + // port
  25814. ')?' +
  25815. '([^?#]+)?' + // path
  25816. '(?:\\?([^#]*))?' + // query
  25817. '(?:#(.*))?' + // fragment
  25818. '$');
  25819. /**
  25820. * The index of each URI component in the return value of goog.uri.utils.split.
  25821. * @enum {number}
  25822. */
  25823. var _ComponentIndex;
  25824. (function (_ComponentIndex) {
  25825. _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
  25826. _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
  25827. _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
  25828. _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
  25829. _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
  25830. _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
  25831. _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
  25832. })(_ComponentIndex || (_ComponentIndex = {}));
  25833. /**
  25834. * Splits a URI into its component parts.
  25835. *
  25836. * Each component can be accessed via the component indices; for example:
  25837. * <pre>
  25838. * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
  25839. * </pre>
  25840. *
  25841. * @param uri The URI string to examine.
  25842. * @return Each component still URI-encoded.
  25843. * Each component that is present will contain the encoded value, whereas
  25844. * components that are not present will be undefined or empty, depending
  25845. * on the browser's regular expression implementation. Never null, since
  25846. * arbitrary strings may still look like path names.
  25847. */
  25848. function _split(uri) {
  25849. return uri.match(_splitRe);
  25850. }
  25851. /**
  25852. * Removes dot segments in given path component, as described in
  25853. * RFC 3986, section 5.2.4.
  25854. *
  25855. * @param path A non-empty path component.
  25856. * @return Path component with removed dot segments.
  25857. */
  25858. function _removeDotSegments(path) {
  25859. if (path == '/')
  25860. return '/';
  25861. const leadingSlash = path[0] == '/' ? '/' : '';
  25862. const trailingSlash = path[path.length - 1] === '/' ? '/' : '';
  25863. const segments = path.split('/');
  25864. const out = [];
  25865. let up = 0;
  25866. for (let pos = 0; pos < segments.length; pos++) {
  25867. const segment = segments[pos];
  25868. switch (segment) {
  25869. case '':
  25870. case '.':
  25871. break;
  25872. case '..':
  25873. if (out.length > 0) {
  25874. out.pop();
  25875. }
  25876. else {
  25877. up++;
  25878. }
  25879. break;
  25880. default:
  25881. out.push(segment);
  25882. }
  25883. }
  25884. if (leadingSlash == '') {
  25885. while (up-- > 0) {
  25886. out.unshift('..');
  25887. }
  25888. if (out.length === 0)
  25889. out.push('.');
  25890. }
  25891. return leadingSlash + out.join('/') + trailingSlash;
  25892. }
  25893. /**
  25894. * Takes an array of the parts from split and canonicalizes the path part
  25895. * and then joins all the parts.
  25896. */
  25897. function _joinAndCanonicalizePath(parts) {
  25898. let path = parts[_ComponentIndex.Path];
  25899. path = path == null ? '' : _removeDotSegments(path);
  25900. parts[_ComponentIndex.Path] = path;
  25901. return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
  25902. }
  25903. /**
  25904. * Resolves a URL.
  25905. * @param base The URL acting as the base URL.
  25906. * @param to The URL to resolve.
  25907. */
  25908. function _resolveUrl(base, url) {
  25909. const parts = _split(encodeURI(url));
  25910. const baseParts = _split(base);
  25911. if (parts[_ComponentIndex.Scheme] != null) {
  25912. return _joinAndCanonicalizePath(parts);
  25913. }
  25914. else {
  25915. parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
  25916. }
  25917. for (let i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
  25918. if (parts[i] == null) {
  25919. parts[i] = baseParts[i];
  25920. }
  25921. }
  25922. if (parts[_ComponentIndex.Path][0] == '/') {
  25923. return _joinAndCanonicalizePath(parts);
  25924. }
  25925. let path = baseParts[_ComponentIndex.Path];
  25926. if (path == null)
  25927. path = '/';
  25928. const index = path.lastIndexOf('/');
  25929. path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
  25930. parts[_ComponentIndex.Path] = path;
  25931. return _joinAndCanonicalizePath(parts);
  25932. }
  25933. /**
  25934. * @license
  25935. * Copyright Google Inc. All Rights Reserved.
  25936. *
  25937. * Use of this source code is governed by an MIT-style license that can be
  25938. * found in the LICENSE file at https://angular.io/license
  25939. */
  25940. class Extractor {
  25941. constructor(host, staticSymbolResolver, messageBundle, metadataResolver) {
  25942. this.host = host;
  25943. this.staticSymbolResolver = staticSymbolResolver;
  25944. this.messageBundle = messageBundle;
  25945. this.metadataResolver = metadataResolver;
  25946. }
  25947. extract(rootFiles) {
  25948. const { files, ngModules } = analyzeAndValidateNgModules(rootFiles, this.host, this.staticSymbolResolver, this.metadataResolver);
  25949. return Promise
  25950. .all(ngModules.map(ngModule => this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false)))
  25951. .then(() => {
  25952. const errors = [];
  25953. files.forEach(file => {
  25954. const compMetas = [];
  25955. file.directives.forEach(directiveType => {
  25956. const dirMeta = this.metadataResolver.getDirectiveMetadata(directiveType);
  25957. if (dirMeta && dirMeta.isComponent) {
  25958. compMetas.push(dirMeta);
  25959. }
  25960. });
  25961. compMetas.forEach(compMeta => {
  25962. const html = compMeta.template.template;
  25963. // Template URL points to either an HTML or TS file depending on
  25964. // whether the file is used with `templateUrl:` or `template:`,
  25965. // respectively.
  25966. const templateUrl = compMeta.template.templateUrl;
  25967. const interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  25968. errors.push(...this.messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig));
  25969. });
  25970. });
  25971. if (errors.length) {
  25972. throw new Error(errors.map(e => e.toString()).join('\n'));
  25973. }
  25974. return this.messageBundle;
  25975. });
  25976. }
  25977. static create(host, locale) {
  25978. const htmlParser = new HtmlParser();
  25979. const urlResolver = createAotUrlResolver(host);
  25980. const symbolCache = new StaticSymbolCache();
  25981. const summaryResolver = new AotSummaryResolver(host, symbolCache);
  25982. const staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
  25983. const staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
  25984. const config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false });
  25985. const normalizer = new DirectiveNormalizer({ get: (url) => host.loadResource(url) }, urlResolver, htmlParser, config);
  25986. const elementSchemaRegistry = new DomElementSchemaRegistry();
  25987. const resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
  25988. // TODO(vicb): implicit tags & attributes
  25989. const messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  25990. const extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
  25991. return { extractor, staticReflector };
  25992. }
  25993. }
  25994. /**
  25995. * @license
  25996. * Copyright Google Inc. All Rights Reserved.
  25997. *
  25998. * Use of this source code is governed by an MIT-style license that can be
  25999. * found in the LICENSE file at https://angular.io/license
  26000. */
  26001. /**
  26002. * @license
  26003. * Copyright Google Inc. All Rights Reserved.
  26004. *
  26005. * Use of this source code is governed by an MIT-style license that can be
  26006. * found in the LICENSE file at https://angular.io/license
  26007. */
  26008. /**
  26009. * Processes `Target`s with a given set of directives and performs a binding operation, which
  26010. * returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
  26011. * target.
  26012. */
  26013. class R3TargetBinder {
  26014. constructor(directiveMatcher) {
  26015. this.directiveMatcher = directiveMatcher;
  26016. }
  26017. /**
  26018. * Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
  26019. * metadata about the types referenced in the template.
  26020. */
  26021. bind(target) {
  26022. if (!target.template) {
  26023. // TODO(alxhub): handle targets which contain things like HostBindings, etc.
  26024. throw new Error('Binding without a template not yet supported');
  26025. }
  26026. // First, parse the template into a `Scope` structure. This operation captures the syntactic
  26027. // scopes in the template and makes them available for later use.
  26028. const scope = Scope.apply(target.template);
  26029. // Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
  26030. // - directives: Map of nodes (elements & ng-templates) to the directives on them.
  26031. // - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
  26032. // them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
  26033. // - references: Map of #references to their targets.
  26034. const { directives, bindings, references } = DirectiveBinder.apply(target.template, this.directiveMatcher);
  26035. // Finally, run the TemplateBinder to bind references, variables, and other entities within the
  26036. // template. This extracts all the metadata that doesn't depend on directive matching.
  26037. const { expressions, symbols, nestingLevel, usedPipes } = TemplateBinder.apply(target.template, scope);
  26038. return new R3BoundTarget(target, directives, bindings, references, expressions, symbols, nestingLevel, usedPipes);
  26039. }
  26040. }
  26041. /**
  26042. * Represents a binding scope within a template.
  26043. *
  26044. * Any variables, references, or other named entities declared within the template will
  26045. * be captured and available by name in `namedEntities`. Additionally, child templates will
  26046. * be analyzed and have their child `Scope`s available in `childScopes`.
  26047. */
  26048. class Scope {
  26049. constructor(parentScope) {
  26050. this.parentScope = parentScope;
  26051. /**
  26052. * Named members of the `Scope`, such as `Reference`s or `Variable`s.
  26053. */
  26054. this.namedEntities = new Map();
  26055. /**
  26056. * Child `Scope`s for immediately nested `Template`s.
  26057. */
  26058. this.childScopes = new Map();
  26059. }
  26060. /**
  26061. * Process a template (either as a `Template` sub-template with variables, or a plain array of
  26062. * template `Node`s) and construct its `Scope`.
  26063. */
  26064. static apply(template) {
  26065. const scope = new Scope();
  26066. scope.ingest(template);
  26067. return scope;
  26068. }
  26069. /**
  26070. * Internal method to process the template and populate the `Scope`.
  26071. */
  26072. ingest(template) {
  26073. if (template instanceof Template) {
  26074. // Variables on an <ng-template> are defined in the inner scope.
  26075. template.variables.forEach(node => this.visitVariable(node));
  26076. // Process the nodes of the template.
  26077. template.children.forEach(node => node.visit(this));
  26078. }
  26079. else {
  26080. // No overarching `Template` instance, so process the nodes directly.
  26081. template.forEach(node => node.visit(this));
  26082. }
  26083. }
  26084. visitElement(element) {
  26085. // `Element`s in the template may have `Reference`s which are captured in the scope.
  26086. element.references.forEach(node => this.visitReference(node));
  26087. // Recurse into the `Element`'s children.
  26088. element.children.forEach(node => node.visit(this));
  26089. }
  26090. visitTemplate(template) {
  26091. // References on a <ng-template> are defined in the outer scope, so capture them before
  26092. // processing the template's child scope.
  26093. template.references.forEach(node => this.visitReference(node));
  26094. // Next, create an inner scope and process the template within it.
  26095. const scope = new Scope(this);
  26096. scope.ingest(template);
  26097. this.childScopes.set(template, scope);
  26098. }
  26099. visitVariable(variable) {
  26100. // Declare the variable if it's not already.
  26101. this.maybeDeclare(variable);
  26102. }
  26103. visitReference(reference) {
  26104. // Declare the variable if it's not already.
  26105. this.maybeDeclare(reference);
  26106. }
  26107. // Unused visitors.
  26108. visitContent(content) { }
  26109. visitBoundAttribute(attr) { }
  26110. visitBoundEvent(event) { }
  26111. visitBoundText(text) { }
  26112. visitText(text) { }
  26113. visitTextAttribute(attr) { }
  26114. visitIcu(icu) { }
  26115. maybeDeclare(thing) {
  26116. // Declare something with a name, as long as that name isn't taken.
  26117. if (!this.namedEntities.has(thing.name)) {
  26118. this.namedEntities.set(thing.name, thing);
  26119. }
  26120. }
  26121. /**
  26122. * Look up a variable within this `Scope`.
  26123. *
  26124. * This can recurse into a parent `Scope` if it's available.
  26125. */
  26126. lookup(name) {
  26127. if (this.namedEntities.has(name)) {
  26128. // Found in the local scope.
  26129. return this.namedEntities.get(name);
  26130. }
  26131. else if (this.parentScope !== undefined) {
  26132. // Not in the local scope, but there's a parent scope so check there.
  26133. return this.parentScope.lookup(name);
  26134. }
  26135. else {
  26136. // At the top level and it wasn't found.
  26137. return null;
  26138. }
  26139. }
  26140. /**
  26141. * Get the child scope for a `Template`.
  26142. *
  26143. * This should always be defined.
  26144. */
  26145. getChildScope(template) {
  26146. const res = this.childScopes.get(template);
  26147. if (res === undefined) {
  26148. throw new Error(`Assertion error: child scope for ${template} not found`);
  26149. }
  26150. return res;
  26151. }
  26152. }
  26153. /**
  26154. * Processes a template and matches directives on nodes (elements and templates).
  26155. *
  26156. * Usually used via the static `apply()` method.
  26157. */
  26158. class DirectiveBinder {
  26159. constructor(matcher, directives, bindings, references) {
  26160. this.matcher = matcher;
  26161. this.directives = directives;
  26162. this.bindings = bindings;
  26163. this.references = references;
  26164. }
  26165. /**
  26166. * Process a template (list of `Node`s) and perform directive matching against each node.
  26167. *
  26168. * @param template the list of template `Node`s to match (recursively).
  26169. * @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
  26170. * this template.
  26171. * @returns three maps which contain information about directives in the template: the
  26172. * `directives` map which lists directives matched on each node, the `bindings` map which
  26173. * indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
  26174. * map which resolves #references (`Reference`s) within the template to the named directive or
  26175. * template node.
  26176. */
  26177. static apply(template, selectorMatcher) {
  26178. const directives = new Map();
  26179. const bindings = new Map();
  26180. const references = new Map();
  26181. const matcher = new DirectiveBinder(selectorMatcher, directives, bindings, references);
  26182. matcher.ingest(template);
  26183. return { directives, bindings, references };
  26184. }
  26185. ingest(template) { template.forEach(node => node.visit(this)); }
  26186. visitElement(element) { this.visitElementOrTemplate(element.name, element); }
  26187. visitTemplate(template) { this.visitElementOrTemplate('ng-template', template); }
  26188. visitElementOrTemplate(tag, node) {
  26189. // First, determine the HTML shape of the node for the purpose of directive matching.
  26190. // Do this by building up a `CssSelector` for the node.
  26191. const cssSelector = new CssSelector();
  26192. cssSelector.setElement(tag);
  26193. // Add attributes to the CSS selector.
  26194. const attrs = getAttrsForDirectiveMatching(node);
  26195. Object.getOwnPropertyNames(attrs).forEach((name) => {
  26196. const value = attrs[name];
  26197. cssSelector.addAttribute(name, value);
  26198. // Treat the 'class' attribute specially.
  26199. if (name.toLowerCase() === 'class') {
  26200. const classes = value.trim().split(/\s+/g);
  26201. classes.forEach(className => cssSelector.addClassName(className));
  26202. }
  26203. });
  26204. // Next, use the `SelectorMatcher` to get the list of directives on the node.
  26205. const directives = [];
  26206. this.matcher.match(cssSelector, (_, directive) => directives.push(directive));
  26207. if (directives.length > 0) {
  26208. this.directives.set(node, directives);
  26209. }
  26210. // Resolve any references that are created on this node.
  26211. node.references.forEach(ref => {
  26212. let dirTarget = null;
  26213. // If the reference expression is empty, then it matches the "primary" directive on the node
  26214. // (if there is one). Otherwise it matches the host node itself (either an element or
  26215. // <ng-template> node).
  26216. if (ref.value.trim() === '') {
  26217. // This could be a reference to a component if there is one.
  26218. dirTarget = directives.find(dir => dir.isComponent) || null;
  26219. }
  26220. else {
  26221. // This is a reference to a directive exported via exportAs. One should exist.
  26222. dirTarget =
  26223. directives.find(dir => dir.exportAs !== null && dir.exportAs.some(value => value === ref.value)) ||
  26224. null;
  26225. // Check if a matching directive was found, and error if it wasn't.
  26226. if (dirTarget === null) {
  26227. // TODO(alxhub): Return an error value here that can be used for template validation.
  26228. throw new Error(`Assertion error: failed to find directive with exportAs: ${ref.value}`);
  26229. }
  26230. }
  26231. if (dirTarget !== null) {
  26232. // This reference points to a directive.
  26233. this.references.set(ref, { directive: dirTarget, node });
  26234. }
  26235. else {
  26236. // This reference points to the node itself.
  26237. this.references.set(ref, node);
  26238. }
  26239. });
  26240. // Associate attributes/bindings on the node with directives or with the node itself.
  26241. const processAttribute = (attribute) => {
  26242. let dir = directives.find(dir => dir.inputs.hasOwnProperty(attribute.name));
  26243. if (dir !== undefined) {
  26244. this.bindings.set(attribute, dir);
  26245. }
  26246. else {
  26247. this.bindings.set(attribute, node);
  26248. }
  26249. };
  26250. node.attributes.forEach(processAttribute);
  26251. node.inputs.forEach(processAttribute);
  26252. node.outputs.forEach(processAttribute);
  26253. if (node instanceof Template) {
  26254. node.templateAttrs.forEach(processAttribute);
  26255. }
  26256. // Recurse into the node's children.
  26257. node.children.forEach(child => child.visit(this));
  26258. }
  26259. // Unused visitors.
  26260. visitContent(content) { }
  26261. visitVariable(variable) { }
  26262. visitReference(reference) { }
  26263. visitTextAttribute(attribute) { }
  26264. visitBoundAttribute(attribute) { }
  26265. visitBoundEvent(attribute) { }
  26266. visitBoundAttributeOrEvent(node) { }
  26267. visitText(text) { }
  26268. visitBoundText(text) { }
  26269. visitIcu(icu) { }
  26270. }
  26271. /**
  26272. * Processes a template and extract metadata about expressions and symbols within.
  26273. *
  26274. * This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
  26275. * within the template in order to operate.
  26276. *
  26277. * Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
  26278. * by overridden methods from that visitor.
  26279. */
  26280. class TemplateBinder extends RecursiveAstVisitor$1 {
  26281. constructor(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
  26282. super();
  26283. this.bindings = bindings;
  26284. this.symbols = symbols;
  26285. this.usedPipes = usedPipes;
  26286. this.nestingLevel = nestingLevel;
  26287. this.scope = scope;
  26288. this.template = template;
  26289. this.level = level;
  26290. this.pipesUsed = [];
  26291. // Save a bit of processing time by constructing this closure in advance.
  26292. this.visitNode = (node) => node.visit(this);
  26293. }
  26294. /**
  26295. * Process a template and extract metadata about expressions and symbols within.
  26296. *
  26297. * @param template the nodes of the template to process
  26298. * @param scope the `Scope` of the template being processed.
  26299. * @returns three maps which contain metadata about the template: `expressions` which interprets
  26300. * special `AST` nodes in expressions as pointing to references or variables declared within the
  26301. * template, `symbols` which maps those variables and references to the nested `Template` which
  26302. * declares them, if any, and `nestingLevel` which associates each `Template` with a integer
  26303. * nesting level (how many levels deep within the template structure the `Template` is), starting
  26304. * at 1.
  26305. */
  26306. static apply(template, scope) {
  26307. const expressions = new Map();
  26308. const symbols = new Map();
  26309. const nestingLevel = new Map();
  26310. const usedPipes = new Set();
  26311. // The top-level template has nesting level 0.
  26312. const binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
  26313. binder.ingest(template);
  26314. return { expressions, symbols, nestingLevel, usedPipes };
  26315. }
  26316. ingest(template) {
  26317. if (template instanceof Template) {
  26318. // For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
  26319. // and references were all processed in the scope of the containing template.
  26320. template.variables.forEach(this.visitNode);
  26321. template.children.forEach(this.visitNode);
  26322. // Set the nesting level.
  26323. this.nestingLevel.set(template, this.level);
  26324. }
  26325. else {
  26326. // Visit each node from the top-level template.
  26327. template.forEach(this.visitNode);
  26328. }
  26329. }
  26330. visitElement(element) {
  26331. // Visit the inputs, outputs, and children of the element.
  26332. element.inputs.forEach(this.visitNode);
  26333. element.outputs.forEach(this.visitNode);
  26334. element.children.forEach(this.visitNode);
  26335. }
  26336. visitTemplate(template) {
  26337. // First, visit inputs, outputs and template attributes of the template node.
  26338. template.inputs.forEach(this.visitNode);
  26339. template.outputs.forEach(this.visitNode);
  26340. template.templateAttrs.forEach(this.visitNode);
  26341. // References are also evaluated in the outer context.
  26342. template.references.forEach(this.visitNode);
  26343. // Next, recurse into the template using its scope, and bumping the nesting level up by one.
  26344. const childScope = this.scope.getChildScope(template);
  26345. const binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
  26346. binder.ingest(template);
  26347. }
  26348. visitVariable(variable) {
  26349. // Register the `Variable` as a symbol in the current `Template`.
  26350. if (this.template !== null) {
  26351. this.symbols.set(variable, this.template);
  26352. }
  26353. }
  26354. visitReference(reference) {
  26355. // Register the `Reference` as a symbol in the current `Template`.
  26356. if (this.template !== null) {
  26357. this.symbols.set(reference, this.template);
  26358. }
  26359. }
  26360. // Unused template visitors
  26361. visitText(text) { }
  26362. visitContent(content) { }
  26363. visitTextAttribute(attribute) { }
  26364. visitIcu(icu) { }
  26365. // The remaining visitors are concerned with processing AST expressions within template bindings
  26366. visitBoundAttribute(attribute) { attribute.value.visit(this); }
  26367. visitBoundEvent(event) { event.handler.visit(this); }
  26368. visitBoundText(text) { text.value.visit(this); }
  26369. visitPipe(ast, context) {
  26370. this.usedPipes.add(ast.name);
  26371. return super.visitPipe(ast, context);
  26372. }
  26373. // These five types of AST expressions can refer to expression roots, which could be variables
  26374. // or references in the current scope.
  26375. visitPropertyRead(ast, context) {
  26376. this.maybeMap(context, ast, ast.name);
  26377. return super.visitPropertyRead(ast, context);
  26378. }
  26379. visitSafePropertyRead(ast, context) {
  26380. this.maybeMap(context, ast, ast.name);
  26381. return super.visitSafePropertyRead(ast, context);
  26382. }
  26383. visitPropertyWrite(ast, context) {
  26384. this.maybeMap(context, ast, ast.name);
  26385. return super.visitPropertyWrite(ast, context);
  26386. }
  26387. visitMethodCall(ast, context) {
  26388. this.maybeMap(context, ast, ast.name);
  26389. return super.visitMethodCall(ast, context);
  26390. }
  26391. visitSafeMethodCall(ast, context) {
  26392. this.maybeMap(context, ast, ast.name);
  26393. return super.visitSafeMethodCall(ast, context);
  26394. }
  26395. maybeMap(scope, ast, name) {
  26396. // If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
  26397. // `AST` expression that maps to a `Variable` or `Reference`.
  26398. if (!(ast.receiver instanceof ImplicitReceiver)) {
  26399. return;
  26400. }
  26401. // Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
  26402. // probably a property on the top-level component context.
  26403. let target = this.scope.lookup(name);
  26404. if (target !== null) {
  26405. this.bindings.set(ast, target);
  26406. }
  26407. }
  26408. }
  26409. /**
  26410. * Metadata container for a `Target` that allows queries for specific bits of metadata.
  26411. *
  26412. * See `BoundTarget` for documentation on the individual methods.
  26413. */
  26414. class R3BoundTarget {
  26415. constructor(target, directives, bindings, references, exprTargets, symbols, nestingLevel, usedPipes) {
  26416. this.target = target;
  26417. this.directives = directives;
  26418. this.bindings = bindings;
  26419. this.references = references;
  26420. this.exprTargets = exprTargets;
  26421. this.symbols = symbols;
  26422. this.nestingLevel = nestingLevel;
  26423. this.usedPipes = usedPipes;
  26424. }
  26425. getDirectivesOfNode(node) {
  26426. return this.directives.get(node) || null;
  26427. }
  26428. getReferenceTarget(ref) {
  26429. return this.references.get(ref) || null;
  26430. }
  26431. getConsumerOfBinding(binding) {
  26432. return this.bindings.get(binding) || null;
  26433. }
  26434. getExpressionTarget(expr) {
  26435. return this.exprTargets.get(expr) || null;
  26436. }
  26437. getTemplateOfSymbol(symbol) {
  26438. return this.symbols.get(symbol) || null;
  26439. }
  26440. getNestingLevel(template) { return this.nestingLevel.get(template) || 0; }
  26441. getUsedDirectives() {
  26442. const set = new Set();
  26443. this.directives.forEach(dirs => dirs.forEach(dir => set.add(dir)));
  26444. return Array.from(set.values());
  26445. }
  26446. getUsedPipes() { return Array.from(this.usedPipes); }
  26447. }
  26448. /**
  26449. * @license
  26450. * Copyright Google Inc. All Rights Reserved.
  26451. *
  26452. * Use of this source code is governed by an MIT-style license that can be
  26453. * found in the LICENSE file at https://angular.io/license
  26454. */
  26455. // This file only reexports content of the `src` folder. Keep it that way.
  26456. // This function call has a global side effects and publishes the compiler into global namespace for
  26457. // the late binding of the Compiler to the @angular/core for jit compilation.
  26458. publishFacade(_global);
  26459. /**
  26460. * @license
  26461. * Copyright Google Inc. All Rights Reserved.
  26462. *
  26463. * Use of this source code is governed by an MIT-style license that can be
  26464. * found in the LICENSE file at https://angular.io/license
  26465. */
  26466. // This file only reexports content of the `src` folder. Keep it that way.
  26467. /**
  26468. * @license
  26469. * Copyright Google Inc. All Rights Reserved.
  26470. *
  26471. * Use of this source code is governed by an MIT-style license that can be
  26472. * found in the LICENSE file at https://angular.io/license
  26473. */
  26474. /**
  26475. * @license
  26476. * Copyright Google Inc. All Rights Reserved.
  26477. *
  26478. * Use of this source code is governed by an MIT-style license that can be
  26479. * found in the LICENSE file at https://angular.io/license
  26480. */
  26481. export { core, CompilerConfig, preserveWhitespacesDefault, isLoweredSymbol, createLoweredSymbol, Identifiers, JitCompiler, ConstantPool, DirectiveResolver, PipeResolver, NgModuleResolver, DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig, NgModuleCompiler, ArrayType, AssertNotNull, DYNAMIC_TYPE, BinaryOperator, BinaryOperatorExpr, BuiltinMethod, BuiltinType, BuiltinTypeName, BuiltinVar, CastExpr, ClassField, ClassMethod, ClassStmt, CommaExpr, CommentStmt, ConditionalExpr, DeclareFunctionStmt, DeclareVarStmt, Expression, ExpressionStatement, ExpressionType, ExternalExpr, ExternalReference, literalMap, FunctionExpr, IfStmt, InstantiateExpr, InvokeFunctionExpr, InvokeMethodExpr, JSDocCommentStmt, LiteralArrayExpr, LiteralExpr, LiteralMapExpr, MapType, NotExpr, ReadKeyExpr, ReadPropExpr, ReadVarExpr, ReturnStatement, ThrowStmt, TryCatchStmt, Type$1 as Type, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr, StmtModifier, Statement, TypeofExpr, collectExternalReferences, EmitterVisitorContext, JitEvaluator, ViewCompiler, findStaticQueryIds, staticViewQueryIds, getParseErrors, isSyntaxError, syntaxError, Version, BoundAttribute as TmplAstBoundAttribute, BoundEvent as TmplAstBoundEvent, BoundText as TmplAstBoundText, Content as TmplAstContent, Element as TmplAstElement, Reference as TmplAstReference, Template as TmplAstTemplate, Text as TmplAstText, TextAttribute as TmplAstTextAttribute, Variable as TmplAstVariable, Identifiers$1 as R3Identifiers, R3ResolvedDependencyType, compileInjector, compileNgModule, compilePipeFromMetadata, makeBindingParser, parseTemplate, compileBaseDefFromMetadata, compileComponentFromMetadata, compileDirectiveFromMetadata, parseHostBindings, verifyHostBindings, publishFacade, VERSION$1 as VERSION, TextAst, BoundTextAst, AttrAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, VariableAst, ElementAst, EmbeddedTemplateAst, BoundDirectivePropertyAst, DirectiveAst, ProviderAst, ProviderAstType, NgContentAst, NullTemplateVisitor, RecursiveTemplateAstVisitor, templateVisitAll, sanitizeIdentifier, identifierName, identifierModuleUrl, viewClassName, rendererTypeName, hostViewClassName, componentFactoryName, CompileSummaryKind, tokenName, tokenReference, CompileStylesheetMetadata, CompileTemplateMetadata, CompileDirectiveMetadata, CompilePipeMetadata, CompileShallowModuleMetadata, CompileNgModuleMetadata, TransitiveCompileNgModuleMetadata, ProviderMeta, flatten, templateSourceUrl, sharedStylesheetJitUrl, ngModuleJitUrl, templateJitUrl, createAotUrlResolver, createAotCompiler, AotCompiler, analyzeNgModules, analyzeAndValidateNgModules, analyzeFile, analyzeFileForInjectables, mergeAnalyzedFiles, GeneratedFile, toTypeScript, formattedError, isFormattedError, StaticReflector, StaticSymbol, StaticSymbolCache, ResolvedStaticSymbol, StaticSymbolResolver, unescapeIdentifier, unwrapResolvedMetadata, AotSummaryResolver, AstPath, SummaryResolver, JitSummaryResolver, CompileReflector, createUrlResolverWithoutPackagePrefix, createOfflineCompileUrlResolver, UrlResolver, getUrlScheme, ResourceLoader, ElementSchemaRegistry, Extractor, I18NHtmlParser, MessageBundle, Serializer, Xliff, Xliff2, Xmb, Xtb, DirectiveNormalizer, ParserError, ParseSpan, AST, Quote, EmptyExpr, ImplicitReceiver, Chain, Conditional, PropertyRead, PropertyWrite, SafePropertyRead, KeyedRead, KeyedWrite, BindingPipe, LiteralPrimitive, LiteralArray, LiteralMap, Interpolation, Binary, PrefixNot, NonNullAssert, MethodCall, SafeMethodCall, FunctionCall, ASTWithSource, TemplateBinding, NullAstVisitor, RecursiveAstVisitor$1 as RecursiveAstVisitor, AstTransformer$1 as AstTransformer, AstMemoryEfficientTransformer, visitAstChildren, ParsedProperty, ParsedPropertyType, ParsedEvent, ParsedVariable, BoundElementProperty, TokenType$1 as TokenType, Lexer, Token$1 as Token, EOF, isIdentifier, isQuote, SplitInterpolation, TemplateBindingParseResult, Parser$1 as Parser, _ParseAST, ERROR_COMPONENT_TYPE, CompileMetadataResolver, Text$3 as Text, Expansion, ExpansionCase, Attribute, Element$1 as Element, Comment, visitAll$1 as visitAll, RecursiveVisitor, findNode, HtmlParser, ParseTreeResult, TreeError, HtmlTagDefinition, getHtmlTagDefinition, TagContentType, splitNsName, isNgContainer, isNgContent, isNgTemplate, getNsPrefix, mergeNsAndName, NAMED_ENTITIES, NGSP_UNICODE, debugOutputAstAsTypeScript, TypeScriptEmitter, ParseLocation, ParseSourceFile, ParseSourceSpan, ParseErrorLevel, ParseError, typeSourceSpan, r3JitTypeSourceSpan, DomElementSchemaRegistry, CssSelector, SelectorMatcher, SelectorListContext, SelectorContext, HOST_ATTR, CONTENT_ATTR, StylesCompileDependency, CompiledStylesheet, StyleCompiler, TemplateParseError, TemplateParseResult, TemplateParser, splitClasses, createElementCssSelector, removeSummaryDuplicates, isEmptyExpression, compileInjectable, R3TargetBinder, R3BoundTarget };
  26482. //# sourceMappingURL=compiler.js.map