compiler.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { __assign, __spread, __extends, __values, __read } from 'tslib';
  7. /**
  8. * @license
  9. * Copyright Google Inc. All Rights Reserved.
  10. *
  11. * Use of this source code is governed by an MIT-style license that can be
  12. * found in the LICENSE file at https://angular.io/license
  13. */
  14. var TagContentType;
  15. (function (TagContentType) {
  16. TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
  17. TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
  18. TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
  19. })(TagContentType || (TagContentType = {}));
  20. function splitNsName(elementName) {
  21. if (elementName[0] != ':') {
  22. return [null, elementName];
  23. }
  24. var colonIndex = elementName.indexOf(':', 1);
  25. if (colonIndex == -1) {
  26. throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\"");
  27. }
  28. return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
  29. }
  30. // `<ng-container>` tags work the same regardless the namespace
  31. function isNgContainer(tagName) {
  32. return splitNsName(tagName)[1] === 'ng-container';
  33. }
  34. // `<ng-content>` tags work the same regardless the namespace
  35. function isNgContent(tagName) {
  36. return splitNsName(tagName)[1] === 'ng-content';
  37. }
  38. // `<ng-template>` tags work the same regardless the namespace
  39. function isNgTemplate(tagName) {
  40. return splitNsName(tagName)[1] === 'ng-template';
  41. }
  42. function getNsPrefix(fullName) {
  43. return fullName === null ? null : splitNsName(fullName)[0];
  44. }
  45. function mergeNsAndName(prefix, localName) {
  46. return prefix ? ":" + prefix + ":" + localName : localName;
  47. }
  48. // see http://www.w3.org/TR/html51/syntax.html#named-character-references
  49. // see https://html.spec.whatwg.org/multipage/entities.json
  50. // This list is not exhaustive to keep the compiler footprint low.
  51. // The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
  52. // exist.
  53. var NAMED_ENTITIES = {
  54. 'Aacute': '\u00C1',
  55. 'aacute': '\u00E1',
  56. 'Acirc': '\u00C2',
  57. 'acirc': '\u00E2',
  58. 'acute': '\u00B4',
  59. 'AElig': '\u00C6',
  60. 'aelig': '\u00E6',
  61. 'Agrave': '\u00C0',
  62. 'agrave': '\u00E0',
  63. 'alefsym': '\u2135',
  64. 'Alpha': '\u0391',
  65. 'alpha': '\u03B1',
  66. 'amp': '&',
  67. 'and': '\u2227',
  68. 'ang': '\u2220',
  69. 'apos': '\u0027',
  70. 'Aring': '\u00C5',
  71. 'aring': '\u00E5',
  72. 'asymp': '\u2248',
  73. 'Atilde': '\u00C3',
  74. 'atilde': '\u00E3',
  75. 'Auml': '\u00C4',
  76. 'auml': '\u00E4',
  77. 'bdquo': '\u201E',
  78. 'Beta': '\u0392',
  79. 'beta': '\u03B2',
  80. 'brvbar': '\u00A6',
  81. 'bull': '\u2022',
  82. 'cap': '\u2229',
  83. 'Ccedil': '\u00C7',
  84. 'ccedil': '\u00E7',
  85. 'cedil': '\u00B8',
  86. 'cent': '\u00A2',
  87. 'Chi': '\u03A7',
  88. 'chi': '\u03C7',
  89. 'circ': '\u02C6',
  90. 'clubs': '\u2663',
  91. 'cong': '\u2245',
  92. 'copy': '\u00A9',
  93. 'crarr': '\u21B5',
  94. 'cup': '\u222A',
  95. 'curren': '\u00A4',
  96. 'dagger': '\u2020',
  97. 'Dagger': '\u2021',
  98. 'darr': '\u2193',
  99. 'dArr': '\u21D3',
  100. 'deg': '\u00B0',
  101. 'Delta': '\u0394',
  102. 'delta': '\u03B4',
  103. 'diams': '\u2666',
  104. 'divide': '\u00F7',
  105. 'Eacute': '\u00C9',
  106. 'eacute': '\u00E9',
  107. 'Ecirc': '\u00CA',
  108. 'ecirc': '\u00EA',
  109. 'Egrave': '\u00C8',
  110. 'egrave': '\u00E8',
  111. 'empty': '\u2205',
  112. 'emsp': '\u2003',
  113. 'ensp': '\u2002',
  114. 'Epsilon': '\u0395',
  115. 'epsilon': '\u03B5',
  116. 'equiv': '\u2261',
  117. 'Eta': '\u0397',
  118. 'eta': '\u03B7',
  119. 'ETH': '\u00D0',
  120. 'eth': '\u00F0',
  121. 'Euml': '\u00CB',
  122. 'euml': '\u00EB',
  123. 'euro': '\u20AC',
  124. 'exist': '\u2203',
  125. 'fnof': '\u0192',
  126. 'forall': '\u2200',
  127. 'frac12': '\u00BD',
  128. 'frac14': '\u00BC',
  129. 'frac34': '\u00BE',
  130. 'frasl': '\u2044',
  131. 'Gamma': '\u0393',
  132. 'gamma': '\u03B3',
  133. 'ge': '\u2265',
  134. 'gt': '>',
  135. 'harr': '\u2194',
  136. 'hArr': '\u21D4',
  137. 'hearts': '\u2665',
  138. 'hellip': '\u2026',
  139. 'Iacute': '\u00CD',
  140. 'iacute': '\u00ED',
  141. 'Icirc': '\u00CE',
  142. 'icirc': '\u00EE',
  143. 'iexcl': '\u00A1',
  144. 'Igrave': '\u00CC',
  145. 'igrave': '\u00EC',
  146. 'image': '\u2111',
  147. 'infin': '\u221E',
  148. 'int': '\u222B',
  149. 'Iota': '\u0399',
  150. 'iota': '\u03B9',
  151. 'iquest': '\u00BF',
  152. 'isin': '\u2208',
  153. 'Iuml': '\u00CF',
  154. 'iuml': '\u00EF',
  155. 'Kappa': '\u039A',
  156. 'kappa': '\u03BA',
  157. 'Lambda': '\u039B',
  158. 'lambda': '\u03BB',
  159. 'lang': '\u27E8',
  160. 'laquo': '\u00AB',
  161. 'larr': '\u2190',
  162. 'lArr': '\u21D0',
  163. 'lceil': '\u2308',
  164. 'ldquo': '\u201C',
  165. 'le': '\u2264',
  166. 'lfloor': '\u230A',
  167. 'lowast': '\u2217',
  168. 'loz': '\u25CA',
  169. 'lrm': '\u200E',
  170. 'lsaquo': '\u2039',
  171. 'lsquo': '\u2018',
  172. 'lt': '<',
  173. 'macr': '\u00AF',
  174. 'mdash': '\u2014',
  175. 'micro': '\u00B5',
  176. 'middot': '\u00B7',
  177. 'minus': '\u2212',
  178. 'Mu': '\u039C',
  179. 'mu': '\u03BC',
  180. 'nabla': '\u2207',
  181. 'nbsp': '\u00A0',
  182. 'ndash': '\u2013',
  183. 'ne': '\u2260',
  184. 'ni': '\u220B',
  185. 'not': '\u00AC',
  186. 'notin': '\u2209',
  187. 'nsub': '\u2284',
  188. 'Ntilde': '\u00D1',
  189. 'ntilde': '\u00F1',
  190. 'Nu': '\u039D',
  191. 'nu': '\u03BD',
  192. 'Oacute': '\u00D3',
  193. 'oacute': '\u00F3',
  194. 'Ocirc': '\u00D4',
  195. 'ocirc': '\u00F4',
  196. 'OElig': '\u0152',
  197. 'oelig': '\u0153',
  198. 'Ograve': '\u00D2',
  199. 'ograve': '\u00F2',
  200. 'oline': '\u203E',
  201. 'Omega': '\u03A9',
  202. 'omega': '\u03C9',
  203. 'Omicron': '\u039F',
  204. 'omicron': '\u03BF',
  205. 'oplus': '\u2295',
  206. 'or': '\u2228',
  207. 'ordf': '\u00AA',
  208. 'ordm': '\u00BA',
  209. 'Oslash': '\u00D8',
  210. 'oslash': '\u00F8',
  211. 'Otilde': '\u00D5',
  212. 'otilde': '\u00F5',
  213. 'otimes': '\u2297',
  214. 'Ouml': '\u00D6',
  215. 'ouml': '\u00F6',
  216. 'para': '\u00B6',
  217. 'permil': '\u2030',
  218. 'perp': '\u22A5',
  219. 'Phi': '\u03A6',
  220. 'phi': '\u03C6',
  221. 'Pi': '\u03A0',
  222. 'pi': '\u03C0',
  223. 'piv': '\u03D6',
  224. 'plusmn': '\u00B1',
  225. 'pound': '\u00A3',
  226. 'prime': '\u2032',
  227. 'Prime': '\u2033',
  228. 'prod': '\u220F',
  229. 'prop': '\u221D',
  230. 'Psi': '\u03A8',
  231. 'psi': '\u03C8',
  232. 'quot': '\u0022',
  233. 'radic': '\u221A',
  234. 'rang': '\u27E9',
  235. 'raquo': '\u00BB',
  236. 'rarr': '\u2192',
  237. 'rArr': '\u21D2',
  238. 'rceil': '\u2309',
  239. 'rdquo': '\u201D',
  240. 'real': '\u211C',
  241. 'reg': '\u00AE',
  242. 'rfloor': '\u230B',
  243. 'Rho': '\u03A1',
  244. 'rho': '\u03C1',
  245. 'rlm': '\u200F',
  246. 'rsaquo': '\u203A',
  247. 'rsquo': '\u2019',
  248. 'sbquo': '\u201A',
  249. 'Scaron': '\u0160',
  250. 'scaron': '\u0161',
  251. 'sdot': '\u22C5',
  252. 'sect': '\u00A7',
  253. 'shy': '\u00AD',
  254. 'Sigma': '\u03A3',
  255. 'sigma': '\u03C3',
  256. 'sigmaf': '\u03C2',
  257. 'sim': '\u223C',
  258. 'spades': '\u2660',
  259. 'sub': '\u2282',
  260. 'sube': '\u2286',
  261. 'sum': '\u2211',
  262. 'sup': '\u2283',
  263. 'sup1': '\u00B9',
  264. 'sup2': '\u00B2',
  265. 'sup3': '\u00B3',
  266. 'supe': '\u2287',
  267. 'szlig': '\u00DF',
  268. 'Tau': '\u03A4',
  269. 'tau': '\u03C4',
  270. 'there4': '\u2234',
  271. 'Theta': '\u0398',
  272. 'theta': '\u03B8',
  273. 'thetasym': '\u03D1',
  274. 'thinsp': '\u2009',
  275. 'THORN': '\u00DE',
  276. 'thorn': '\u00FE',
  277. 'tilde': '\u02DC',
  278. 'times': '\u00D7',
  279. 'trade': '\u2122',
  280. 'Uacute': '\u00DA',
  281. 'uacute': '\u00FA',
  282. 'uarr': '\u2191',
  283. 'uArr': '\u21D1',
  284. 'Ucirc': '\u00DB',
  285. 'ucirc': '\u00FB',
  286. 'Ugrave': '\u00D9',
  287. 'ugrave': '\u00F9',
  288. 'uml': '\u00A8',
  289. 'upsih': '\u03D2',
  290. 'Upsilon': '\u03A5',
  291. 'upsilon': '\u03C5',
  292. 'Uuml': '\u00DC',
  293. 'uuml': '\u00FC',
  294. 'weierp': '\u2118',
  295. 'Xi': '\u039E',
  296. 'xi': '\u03BE',
  297. 'Yacute': '\u00DD',
  298. 'yacute': '\u00FD',
  299. 'yen': '\u00A5',
  300. 'yuml': '\u00FF',
  301. 'Yuml': '\u0178',
  302. 'Zeta': '\u0396',
  303. 'zeta': '\u03B6',
  304. 'zwj': '\u200D',
  305. 'zwnj': '\u200C',
  306. };
  307. // The &ngsp; pseudo-entity is denoting a space. see:
  308. // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
  309. var NGSP_UNICODE = '\uE500';
  310. NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
  311. /**
  312. * @license
  313. * Copyright Google Inc. All Rights Reserved.
  314. *
  315. * Use of this source code is governed by an MIT-style license that can be
  316. * found in the LICENSE file at https://angular.io/license
  317. */
  318. var HtmlTagDefinition = /** @class */ (function () {
  319. function HtmlTagDefinition(_a) {
  320. var _this = this;
  321. var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? TagContentType.PARSABLE_DATA : _c, _d = _b.closedByParent, closedByParent = _d === void 0 ? false : _d, _e = _b.isVoid, isVoid = _e === void 0 ? false : _e, _f = _b.ignoreFirstLf, ignoreFirstLf = _f === void 0 ? false : _f;
  322. this.closedByChildren = {};
  323. this.closedByParent = false;
  324. this.canSelfClose = false;
  325. if (closedByChildren && closedByChildren.length > 0) {
  326. closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
  327. }
  328. this.isVoid = isVoid;
  329. this.closedByParent = closedByParent || isVoid;
  330. this.implicitNamespacePrefix = implicitNamespacePrefix || null;
  331. this.contentType = contentType;
  332. this.ignoreFirstLf = ignoreFirstLf;
  333. }
  334. HtmlTagDefinition.prototype.isClosedByChild = function (name) {
  335. return this.isVoid || name.toLowerCase() in this.closedByChildren;
  336. };
  337. return HtmlTagDefinition;
  338. }());
  339. var _DEFAULT_TAG_DEFINITION;
  340. // see http://www.w3.org/TR/html51/syntax.html#optional-tags
  341. // This implementation does not fully conform to the HTML5 spec.
  342. var TAG_DEFINITIONS;
  343. function getHtmlTagDefinition(tagName) {
  344. if (!TAG_DEFINITIONS) {
  345. _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
  346. TAG_DEFINITIONS = {
  347. 'base': new HtmlTagDefinition({ isVoid: true }),
  348. 'meta': new HtmlTagDefinition({ isVoid: true }),
  349. 'area': new HtmlTagDefinition({ isVoid: true }),
  350. 'embed': new HtmlTagDefinition({ isVoid: true }),
  351. 'link': new HtmlTagDefinition({ isVoid: true }),
  352. 'img': new HtmlTagDefinition({ isVoid: true }),
  353. 'input': new HtmlTagDefinition({ isVoid: true }),
  354. 'param': new HtmlTagDefinition({ isVoid: true }),
  355. 'hr': new HtmlTagDefinition({ isVoid: true }),
  356. 'br': new HtmlTagDefinition({ isVoid: true }),
  357. 'source': new HtmlTagDefinition({ isVoid: true }),
  358. 'track': new HtmlTagDefinition({ isVoid: true }),
  359. 'wbr': new HtmlTagDefinition({ isVoid: true }),
  360. 'p': new HtmlTagDefinition({
  361. closedByChildren: [
  362. 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
  363. 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
  364. 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
  365. 'p', 'pre', 'section', 'table', 'ul'
  366. ],
  367. closedByParent: true
  368. }),
  369. 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
  370. 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
  371. 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
  372. 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
  373. 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  374. 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  375. 'col': new HtmlTagDefinition({ isVoid: true }),
  376. 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
  377. 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
  378. 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
  379. 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
  380. 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
  381. 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  382. 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  383. 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
  384. 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  385. 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
  386. 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
  387. 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
  388. 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
  389. 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
  390. 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
  391. 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }),
  392. 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
  393. };
  394. }
  395. return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION;
  396. }
  397. /**
  398. * @license
  399. * Copyright Google Inc. All Rights Reserved.
  400. *
  401. * Use of this source code is governed by an MIT-style license that can be
  402. * found in the LICENSE file at https://angular.io/license
  403. */
  404. var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + //":not("
  405. '([-\\w]+)|' + // "tag"
  406. '(?:\\.([-\\w]+))|' + // ".class"
  407. // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
  408. '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
  409. // "[name="value"]",
  410. // "[name='value']"
  411. '(\\))|' + // ")"
  412. '(\\s*,\\s*)', // ","
  413. 'g');
  414. /**
  415. * A css selector contains an element name,
  416. * css classes and attribute/value pairs with the purpose
  417. * of selecting subsets out of them.
  418. */
  419. var CssSelector = /** @class */ (function () {
  420. function CssSelector() {
  421. this.element = null;
  422. this.classNames = [];
  423. /**
  424. * The selectors are encoded in pairs where:
  425. * - even locations are attribute names
  426. * - odd locations are attribute values.
  427. *
  428. * Example:
  429. * Selector: `[key1=value1][key2]` would parse to:
  430. * ```
  431. * ['key1', 'value1', 'key2', '']
  432. * ```
  433. */
  434. this.attrs = [];
  435. this.notSelectors = [];
  436. }
  437. CssSelector.parse = function (selector) {
  438. var results = [];
  439. var _addResult = function (res, cssSel) {
  440. if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
  441. cssSel.attrs.length == 0) {
  442. cssSel.element = '*';
  443. }
  444. res.push(cssSel);
  445. };
  446. var cssSelector = new CssSelector();
  447. var match;
  448. var current = cssSelector;
  449. var inNot = false;
  450. _SELECTOR_REGEXP.lastIndex = 0;
  451. while (match = _SELECTOR_REGEXP.exec(selector)) {
  452. if (match[1]) {
  453. if (inNot) {
  454. throw new Error('Nesting :not is not allowed in a selector');
  455. }
  456. inNot = true;
  457. current = new CssSelector();
  458. cssSelector.notSelectors.push(current);
  459. }
  460. if (match[2]) {
  461. current.setElement(match[2]);
  462. }
  463. if (match[3]) {
  464. current.addClassName(match[3]);
  465. }
  466. if (match[4]) {
  467. current.addAttribute(match[4], match[6]);
  468. }
  469. if (match[7]) {
  470. inNot = false;
  471. current = cssSelector;
  472. }
  473. if (match[8]) {
  474. if (inNot) {
  475. throw new Error('Multiple selectors in :not are not supported');
  476. }
  477. _addResult(results, cssSelector);
  478. cssSelector = current = new CssSelector();
  479. }
  480. }
  481. _addResult(results, cssSelector);
  482. return results;
  483. };
  484. CssSelector.prototype.isElementSelector = function () {
  485. return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
  486. this.notSelectors.length === 0;
  487. };
  488. CssSelector.prototype.hasElementSelector = function () { return !!this.element; };
  489. CssSelector.prototype.setElement = function (element) {
  490. if (element === void 0) { element = null; }
  491. this.element = element;
  492. };
  493. /** Gets a template string for an element that matches the selector. */
  494. CssSelector.prototype.getMatchingElementTemplate = function () {
  495. var tagName = this.element || 'div';
  496. var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
  497. var attrs = '';
  498. for (var i = 0; i < this.attrs.length; i += 2) {
  499. var attrName = this.attrs[i];
  500. var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
  501. attrs += " " + attrName + attrValue;
  502. }
  503. return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
  504. "<" + tagName + classAttr + attrs + "></" + tagName + ">";
  505. };
  506. CssSelector.prototype.getAttrs = function () {
  507. var result = [];
  508. if (this.classNames.length > 0) {
  509. result.push('class', this.classNames.join(' '));
  510. }
  511. return result.concat(this.attrs);
  512. };
  513. CssSelector.prototype.addAttribute = function (name, value) {
  514. if (value === void 0) { value = ''; }
  515. this.attrs.push(name, value && value.toLowerCase() || '');
  516. };
  517. CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
  518. CssSelector.prototype.toString = function () {
  519. var res = this.element || '';
  520. if (this.classNames) {
  521. this.classNames.forEach(function (klass) { return res += "." + klass; });
  522. }
  523. if (this.attrs) {
  524. for (var i = 0; i < this.attrs.length; i += 2) {
  525. var name_1 = this.attrs[i];
  526. var value = this.attrs[i + 1];
  527. res += "[" + name_1 + (value ? '=' + value : '') + "]";
  528. }
  529. }
  530. this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
  531. return res;
  532. };
  533. return CssSelector;
  534. }());
  535. /**
  536. * Reads a list of CssSelectors and allows to calculate which ones
  537. * are contained in a given CssSelector.
  538. */
  539. var SelectorMatcher = /** @class */ (function () {
  540. function SelectorMatcher() {
  541. this._elementMap = new Map();
  542. this._elementPartialMap = new Map();
  543. this._classMap = new Map();
  544. this._classPartialMap = new Map();
  545. this._attrValueMap = new Map();
  546. this._attrValuePartialMap = new Map();
  547. this._listContexts = [];
  548. }
  549. SelectorMatcher.createNotMatcher = function (notSelectors) {
  550. var notMatcher = new SelectorMatcher();
  551. notMatcher.addSelectables(notSelectors, null);
  552. return notMatcher;
  553. };
  554. SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
  555. var listContext = null;
  556. if (cssSelectors.length > 1) {
  557. listContext = new SelectorListContext(cssSelectors);
  558. this._listContexts.push(listContext);
  559. }
  560. for (var i = 0; i < cssSelectors.length; i++) {
  561. this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
  562. }
  563. };
  564. /**
  565. * Add an object that can be found later on by calling `match`.
  566. * @param cssSelector A css selector
  567. * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
  568. */
  569. SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
  570. var matcher = this;
  571. var element = cssSelector.element;
  572. var classNames = cssSelector.classNames;
  573. var attrs = cssSelector.attrs;
  574. var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
  575. if (element) {
  576. var isTerminal = attrs.length === 0 && classNames.length === 0;
  577. if (isTerminal) {
  578. this._addTerminal(matcher._elementMap, element, selectable);
  579. }
  580. else {
  581. matcher = this._addPartial(matcher._elementPartialMap, element);
  582. }
  583. }
  584. if (classNames) {
  585. for (var i = 0; i < classNames.length; i++) {
  586. var isTerminal = attrs.length === 0 && i === classNames.length - 1;
  587. var className = classNames[i];
  588. if (isTerminal) {
  589. this._addTerminal(matcher._classMap, className, selectable);
  590. }
  591. else {
  592. matcher = this._addPartial(matcher._classPartialMap, className);
  593. }
  594. }
  595. }
  596. if (attrs) {
  597. for (var i = 0; i < attrs.length; i += 2) {
  598. var isTerminal = i === attrs.length - 2;
  599. var name_2 = attrs[i];
  600. var value = attrs[i + 1];
  601. if (isTerminal) {
  602. var terminalMap = matcher._attrValueMap;
  603. var terminalValuesMap = terminalMap.get(name_2);
  604. if (!terminalValuesMap) {
  605. terminalValuesMap = new Map();
  606. terminalMap.set(name_2, terminalValuesMap);
  607. }
  608. this._addTerminal(terminalValuesMap, value, selectable);
  609. }
  610. else {
  611. var partialMap = matcher._attrValuePartialMap;
  612. var partialValuesMap = partialMap.get(name_2);
  613. if (!partialValuesMap) {
  614. partialValuesMap = new Map();
  615. partialMap.set(name_2, partialValuesMap);
  616. }
  617. matcher = this._addPartial(partialValuesMap, value);
  618. }
  619. }
  620. }
  621. };
  622. SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
  623. var terminalList = map.get(name);
  624. if (!terminalList) {
  625. terminalList = [];
  626. map.set(name, terminalList);
  627. }
  628. terminalList.push(selectable);
  629. };
  630. SelectorMatcher.prototype._addPartial = function (map, name) {
  631. var matcher = map.get(name);
  632. if (!matcher) {
  633. matcher = new SelectorMatcher();
  634. map.set(name, matcher);
  635. }
  636. return matcher;
  637. };
  638. /**
  639. * Find the objects that have been added via `addSelectable`
  640. * whose css selector is contained in the given css selector.
  641. * @param cssSelector A css selector
  642. * @param matchedCallback This callback will be called with the object handed into `addSelectable`
  643. * @return boolean true if a match was found
  644. */
  645. SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
  646. var result = false;
  647. var element = cssSelector.element;
  648. var classNames = cssSelector.classNames;
  649. var attrs = cssSelector.attrs;
  650. for (var i = 0; i < this._listContexts.length; i++) {
  651. this._listContexts[i].alreadyMatched = false;
  652. }
  653. result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
  654. result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
  655. result;
  656. if (classNames) {
  657. for (var i = 0; i < classNames.length; i++) {
  658. var className = classNames[i];
  659. result =
  660. this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
  661. result =
  662. this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
  663. result;
  664. }
  665. }
  666. if (attrs) {
  667. for (var i = 0; i < attrs.length; i += 2) {
  668. var name_3 = attrs[i];
  669. var value = attrs[i + 1];
  670. var terminalValuesMap = this._attrValueMap.get(name_3);
  671. if (value) {
  672. result =
  673. this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
  674. }
  675. result =
  676. this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
  677. var partialValuesMap = this._attrValuePartialMap.get(name_3);
  678. if (value) {
  679. result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
  680. }
  681. result =
  682. this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
  683. }
  684. }
  685. return result;
  686. };
  687. /** @internal */
  688. SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
  689. if (!map || typeof name !== 'string') {
  690. return false;
  691. }
  692. var selectables = map.get(name) || [];
  693. var starSelectables = map.get('*');
  694. if (starSelectables) {
  695. selectables = selectables.concat(starSelectables);
  696. }
  697. if (selectables.length === 0) {
  698. return false;
  699. }
  700. var selectable;
  701. var result = false;
  702. for (var i = 0; i < selectables.length; i++) {
  703. selectable = selectables[i];
  704. result = selectable.finalize(cssSelector, matchedCallback) || result;
  705. }
  706. return result;
  707. };
  708. /** @internal */
  709. SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
  710. if (!map || typeof name !== 'string') {
  711. return false;
  712. }
  713. var nestedSelector = map.get(name);
  714. if (!nestedSelector) {
  715. return false;
  716. }
  717. // TODO(perf): get rid of recursion and measure again
  718. // TODO(perf): don't pass the whole selector into the recursion,
  719. // but only the not processed parts
  720. return nestedSelector.match(cssSelector, matchedCallback);
  721. };
  722. return SelectorMatcher;
  723. }());
  724. var SelectorListContext = /** @class */ (function () {
  725. function SelectorListContext(selectors) {
  726. this.selectors = selectors;
  727. this.alreadyMatched = false;
  728. }
  729. return SelectorListContext;
  730. }());
  731. // Store context to pass back selector and context when a selector is matched
  732. var SelectorContext = /** @class */ (function () {
  733. function SelectorContext(selector, cbContext, listContext) {
  734. this.selector = selector;
  735. this.cbContext = cbContext;
  736. this.listContext = listContext;
  737. this.notSelectors = selector.notSelectors;
  738. }
  739. SelectorContext.prototype.finalize = function (cssSelector, callback) {
  740. var result = true;
  741. if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
  742. var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
  743. result = !notMatcher.match(cssSelector, null);
  744. }
  745. if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
  746. if (this.listContext) {
  747. this.listContext.alreadyMatched = true;
  748. }
  749. callback(this.selector, this.cbContext);
  750. }
  751. return result;
  752. };
  753. return SelectorContext;
  754. }());
  755. /**
  756. * @license
  757. * Copyright Google Inc. All Rights Reserved.
  758. *
  759. * Use of this source code is governed by an MIT-style license that can be
  760. * found in the LICENSE file at https://angular.io/license
  761. */
  762. var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); });
  763. var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ngInjectableDef: undefined }); });
  764. var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); });
  765. var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) {
  766. if (data === void 0) { data = {}; }
  767. return (__assign({ selector: selector, first: false, isViewQuery: false, descendants: false }, data));
  768. });
  769. var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) {
  770. if (data === void 0) { data = {}; }
  771. return (__assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data));
  772. });
  773. var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) {
  774. if (data === void 0) { data = {}; }
  775. return (__assign({ selector: selector, first: false, isViewQuery: true, descendants: true }, data));
  776. });
  777. var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) {
  778. return (__assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data));
  779. });
  780. var createDirective = makeMetadataFactory('Directive', function (dir) {
  781. if (dir === void 0) { dir = {}; }
  782. return dir;
  783. });
  784. var ViewEncapsulation;
  785. (function (ViewEncapsulation) {
  786. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  787. ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
  788. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  789. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  790. })(ViewEncapsulation || (ViewEncapsulation = {}));
  791. var ChangeDetectionStrategy;
  792. (function (ChangeDetectionStrategy) {
  793. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  794. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  795. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  796. var createComponent = makeMetadataFactory('Component', function (c) {
  797. if (c === void 0) { c = {}; }
  798. return (__assign({ changeDetection: ChangeDetectionStrategy.Default }, c));
  799. });
  800. var createPipe = makeMetadataFactory('Pipe', function (p) { return (__assign({ pure: true }, p)); });
  801. var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  802. var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  803. var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); });
  804. var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); });
  805. var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; });
  806. var createInjectable = makeMetadataFactory('Injectable', function (injectable) {
  807. if (injectable === void 0) { injectable = {}; }
  808. return injectable;
  809. });
  810. var CUSTOM_ELEMENTS_SCHEMA = {
  811. name: 'custom-elements'
  812. };
  813. var NO_ERRORS_SCHEMA = {
  814. name: 'no-errors-schema'
  815. };
  816. var createOptional = makeMetadataFactory('Optional');
  817. var createSelf = makeMetadataFactory('Self');
  818. var createSkipSelf = makeMetadataFactory('SkipSelf');
  819. var createHost = makeMetadataFactory('Host');
  820. var Type = Function;
  821. var SecurityContext;
  822. (function (SecurityContext) {
  823. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  824. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  825. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  826. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  827. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  828. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  829. })(SecurityContext || (SecurityContext = {}));
  830. var MissingTranslationStrategy;
  831. (function (MissingTranslationStrategy) {
  832. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  833. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  834. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  835. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  836. function makeMetadataFactory(name, props) {
  837. // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
  838. // that works with the static_reflector.ts in the ViewEngine compiler.
  839. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
  840. // new'ed.
  841. function factory() {
  842. var args = [];
  843. for (var _i = 0; _i < arguments.length; _i++) {
  844. args[_i] = arguments[_i];
  845. }
  846. var values = props ? props.apply(void 0, __spread(args)) : {};
  847. return __assign({ ngMetadataName: name }, values);
  848. }
  849. factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; };
  850. factory.ngMetadataName = name;
  851. return factory;
  852. }
  853. function parserSelectorToSimpleSelector(selector) {
  854. var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
  855. [];
  856. var elementName = selector.element && selector.element !== '*' ? selector.element : '';
  857. return __spread([elementName], selector.attrs, classes);
  858. }
  859. function parserSelectorToNegativeSelector(selector) {
  860. var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
  861. [];
  862. if (selector.element) {
  863. return __spread([
  864. 1 /* NOT */ | 4 /* ELEMENT */, selector.element
  865. ], selector.attrs, classes);
  866. }
  867. else if (selector.attrs.length) {
  868. return __spread([1 /* NOT */ | 2 /* ATTRIBUTE */], selector.attrs, classes);
  869. }
  870. else {
  871. return selector.classNames && selector.classNames.length ? __spread([1 /* NOT */ | 8 /* CLASS */], selector.classNames) :
  872. [];
  873. }
  874. }
  875. function parserSelectorToR3Selector(selector) {
  876. var positive = parserSelectorToSimpleSelector(selector);
  877. var negative = selector.notSelectors && selector.notSelectors.length ?
  878. selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) :
  879. [];
  880. return positive.concat.apply(positive, __spread(negative));
  881. }
  882. function parseSelectorToR3Selector(selector) {
  883. return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
  884. }
  885. var core = /*#__PURE__*/Object.freeze({
  886. createInject: createInject,
  887. createInjectionToken: createInjectionToken,
  888. createAttribute: createAttribute,
  889. createContentChildren: createContentChildren,
  890. createContentChild: createContentChild,
  891. createViewChildren: createViewChildren,
  892. createViewChild: createViewChild,
  893. createDirective: createDirective,
  894. get ViewEncapsulation () { return ViewEncapsulation; },
  895. get ChangeDetectionStrategy () { return ChangeDetectionStrategy; },
  896. createComponent: createComponent,
  897. createPipe: createPipe,
  898. createInput: createInput,
  899. createOutput: createOutput,
  900. createHostBinding: createHostBinding,
  901. createHostListener: createHostListener,
  902. createNgModule: createNgModule,
  903. createInjectable: createInjectable,
  904. CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA,
  905. NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA,
  906. createOptional: createOptional,
  907. createSelf: createSelf,
  908. createSkipSelf: createSkipSelf,
  909. createHost: createHost,
  910. Type: Type,
  911. get SecurityContext () { return SecurityContext; },
  912. get MissingTranslationStrategy () { return MissingTranslationStrategy; },
  913. parseSelectorToR3Selector: parseSelectorToR3Selector
  914. });
  915. /**
  916. * @license
  917. * Copyright Google Inc. All Rights Reserved.
  918. *
  919. * Use of this source code is governed by an MIT-style license that can be
  920. * found in the LICENSE file at https://angular.io/license
  921. */
  922. //// Types
  923. var TypeModifier;
  924. (function (TypeModifier) {
  925. TypeModifier[TypeModifier["Const"] = 0] = "Const";
  926. })(TypeModifier || (TypeModifier = {}));
  927. var Type$1 = /** @class */ (function () {
  928. function Type(modifiers) {
  929. if (modifiers === void 0) { modifiers = null; }
  930. this.modifiers = modifiers;
  931. if (!modifiers) {
  932. this.modifiers = [];
  933. }
  934. }
  935. Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  936. return Type;
  937. }());
  938. var BuiltinTypeName;
  939. (function (BuiltinTypeName) {
  940. BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
  941. BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
  942. BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
  943. BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
  944. BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
  945. BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
  946. BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
  947. BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None";
  948. })(BuiltinTypeName || (BuiltinTypeName = {}));
  949. var BuiltinType = /** @class */ (function (_super) {
  950. __extends(BuiltinType, _super);
  951. function BuiltinType(name, modifiers) {
  952. if (modifiers === void 0) { modifiers = null; }
  953. var _this = _super.call(this, modifiers) || this;
  954. _this.name = name;
  955. return _this;
  956. }
  957. BuiltinType.prototype.visitType = function (visitor, context) {
  958. return visitor.visitBuiltinType(this, context);
  959. };
  960. return BuiltinType;
  961. }(Type$1));
  962. var ExpressionType = /** @class */ (function (_super) {
  963. __extends(ExpressionType, _super);
  964. function ExpressionType(value, modifiers, typeParams) {
  965. if (modifiers === void 0) { modifiers = null; }
  966. if (typeParams === void 0) { typeParams = null; }
  967. var _this = _super.call(this, modifiers) || this;
  968. _this.value = value;
  969. _this.typeParams = typeParams;
  970. return _this;
  971. }
  972. ExpressionType.prototype.visitType = function (visitor, context) {
  973. return visitor.visitExpressionType(this, context);
  974. };
  975. return ExpressionType;
  976. }(Type$1));
  977. var ArrayType = /** @class */ (function (_super) {
  978. __extends(ArrayType, _super);
  979. function ArrayType(of, modifiers) {
  980. if (modifiers === void 0) { modifiers = null; }
  981. var _this = _super.call(this, modifiers) || this;
  982. _this.of = of;
  983. return _this;
  984. }
  985. ArrayType.prototype.visitType = function (visitor, context) {
  986. return visitor.visitArrayType(this, context);
  987. };
  988. return ArrayType;
  989. }(Type$1));
  990. var MapType = /** @class */ (function (_super) {
  991. __extends(MapType, _super);
  992. function MapType(valueType, modifiers) {
  993. if (modifiers === void 0) { modifiers = null; }
  994. var _this = _super.call(this, modifiers) || this;
  995. _this.valueType = valueType || null;
  996. return _this;
  997. }
  998. MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); };
  999. return MapType;
  1000. }(Type$1));
  1001. var DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
  1002. var INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
  1003. var BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
  1004. var INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
  1005. var NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
  1006. var STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
  1007. var FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
  1008. var NONE_TYPE = new BuiltinType(BuiltinTypeName.None);
  1009. ///// Expressions
  1010. var BinaryOperator;
  1011. (function (BinaryOperator) {
  1012. BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
  1013. BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
  1014. BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
  1015. BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
  1016. BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
  1017. BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
  1018. BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
  1019. BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
  1020. BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
  1021. BinaryOperator[BinaryOperator["And"] = 9] = "And";
  1022. BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
  1023. BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
  1024. BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
  1025. BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
  1026. BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
  1027. BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
  1028. })(BinaryOperator || (BinaryOperator = {}));
  1029. function nullSafeIsEquivalent(base, other) {
  1030. if (base == null || other == null) {
  1031. return base == other;
  1032. }
  1033. return base.isEquivalent(other);
  1034. }
  1035. function areAllEquivalent(base, other) {
  1036. var len = base.length;
  1037. if (len !== other.length) {
  1038. return false;
  1039. }
  1040. for (var i = 0; i < len; i++) {
  1041. if (!base[i].isEquivalent(other[i])) {
  1042. return false;
  1043. }
  1044. }
  1045. return true;
  1046. }
  1047. var Expression = /** @class */ (function () {
  1048. function Expression(type, sourceSpan) {
  1049. this.type = type || null;
  1050. this.sourceSpan = sourceSpan || null;
  1051. }
  1052. Expression.prototype.prop = function (name, sourceSpan) {
  1053. return new ReadPropExpr(this, name, null, sourceSpan);
  1054. };
  1055. Expression.prototype.key = function (index, type, sourceSpan) {
  1056. return new ReadKeyExpr(this, index, type, sourceSpan);
  1057. };
  1058. Expression.prototype.callMethod = function (name, params, sourceSpan) {
  1059. return new InvokeMethodExpr(this, name, params, null, sourceSpan);
  1060. };
  1061. Expression.prototype.callFn = function (params, sourceSpan) {
  1062. return new InvokeFunctionExpr(this, params, null, sourceSpan);
  1063. };
  1064. Expression.prototype.instantiate = function (params, type, sourceSpan) {
  1065. return new InstantiateExpr(this, params, type, sourceSpan);
  1066. };
  1067. Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
  1068. if (falseCase === void 0) { falseCase = null; }
  1069. return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
  1070. };
  1071. Expression.prototype.equals = function (rhs, sourceSpan) {
  1072. return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
  1073. };
  1074. Expression.prototype.notEquals = function (rhs, sourceSpan) {
  1075. return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
  1076. };
  1077. Expression.prototype.identical = function (rhs, sourceSpan) {
  1078. return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
  1079. };
  1080. Expression.prototype.notIdentical = function (rhs, sourceSpan) {
  1081. return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
  1082. };
  1083. Expression.prototype.minus = function (rhs, sourceSpan) {
  1084. return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
  1085. };
  1086. Expression.prototype.plus = function (rhs, sourceSpan) {
  1087. return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
  1088. };
  1089. Expression.prototype.divide = function (rhs, sourceSpan) {
  1090. return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
  1091. };
  1092. Expression.prototype.multiply = function (rhs, sourceSpan) {
  1093. return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
  1094. };
  1095. Expression.prototype.modulo = function (rhs, sourceSpan) {
  1096. return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
  1097. };
  1098. Expression.prototype.and = function (rhs, sourceSpan) {
  1099. return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
  1100. };
  1101. Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) {
  1102. if (parens === void 0) { parens = true; }
  1103. return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
  1104. };
  1105. Expression.prototype.or = function (rhs, sourceSpan) {
  1106. return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
  1107. };
  1108. Expression.prototype.lower = function (rhs, sourceSpan) {
  1109. return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
  1110. };
  1111. Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
  1112. return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
  1113. };
  1114. Expression.prototype.bigger = function (rhs, sourceSpan) {
  1115. return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
  1116. };
  1117. Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
  1118. return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
  1119. };
  1120. Expression.prototype.isBlank = function (sourceSpan) {
  1121. // Note: We use equals by purpose here to compare to null and undefined in JS.
  1122. // We use the typed null to allow strictNullChecks to narrow types.
  1123. return this.equals(TYPED_NULL_EXPR, sourceSpan);
  1124. };
  1125. Expression.prototype.cast = function (type, sourceSpan) {
  1126. return new CastExpr(this, type, sourceSpan);
  1127. };
  1128. Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); };
  1129. return Expression;
  1130. }());
  1131. var BuiltinVar;
  1132. (function (BuiltinVar) {
  1133. BuiltinVar[BuiltinVar["This"] = 0] = "This";
  1134. BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
  1135. BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
  1136. BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
  1137. })(BuiltinVar || (BuiltinVar = {}));
  1138. var ReadVarExpr = /** @class */ (function (_super) {
  1139. __extends(ReadVarExpr, _super);
  1140. function ReadVarExpr(name, type, sourceSpan) {
  1141. var _this = _super.call(this, type, sourceSpan) || this;
  1142. if (typeof name === 'string') {
  1143. _this.name = name;
  1144. _this.builtin = null;
  1145. }
  1146. else {
  1147. _this.name = null;
  1148. _this.builtin = name;
  1149. }
  1150. return _this;
  1151. }
  1152. ReadVarExpr.prototype.isEquivalent = function (e) {
  1153. return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
  1154. };
  1155. ReadVarExpr.prototype.isConstant = function () { return false; };
  1156. ReadVarExpr.prototype.visitExpression = function (visitor, context) {
  1157. return visitor.visitReadVarExpr(this, context);
  1158. };
  1159. ReadVarExpr.prototype.set = function (value) {
  1160. if (!this.name) {
  1161. throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
  1162. }
  1163. return new WriteVarExpr(this.name, value, null, this.sourceSpan);
  1164. };
  1165. return ReadVarExpr;
  1166. }(Expression));
  1167. var TypeofExpr = /** @class */ (function (_super) {
  1168. __extends(TypeofExpr, _super);
  1169. function TypeofExpr(expr, type, sourceSpan) {
  1170. var _this = _super.call(this, type, sourceSpan) || this;
  1171. _this.expr = expr;
  1172. return _this;
  1173. }
  1174. TypeofExpr.prototype.visitExpression = function (visitor, context) {
  1175. return visitor.visitTypeofExpr(this, context);
  1176. };
  1177. TypeofExpr.prototype.isEquivalent = function (e) {
  1178. return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
  1179. };
  1180. TypeofExpr.prototype.isConstant = function () { return this.expr.isConstant(); };
  1181. return TypeofExpr;
  1182. }(Expression));
  1183. var WrappedNodeExpr = /** @class */ (function (_super) {
  1184. __extends(WrappedNodeExpr, _super);
  1185. function WrappedNodeExpr(node, type, sourceSpan) {
  1186. var _this = _super.call(this, type, sourceSpan) || this;
  1187. _this.node = node;
  1188. return _this;
  1189. }
  1190. WrappedNodeExpr.prototype.isEquivalent = function (e) {
  1191. return e instanceof WrappedNodeExpr && this.node === e.node;
  1192. };
  1193. WrappedNodeExpr.prototype.isConstant = function () { return false; };
  1194. WrappedNodeExpr.prototype.visitExpression = function (visitor, context) {
  1195. return visitor.visitWrappedNodeExpr(this, context);
  1196. };
  1197. return WrappedNodeExpr;
  1198. }(Expression));
  1199. var WriteVarExpr = /** @class */ (function (_super) {
  1200. __extends(WriteVarExpr, _super);
  1201. function WriteVarExpr(name, value, type, sourceSpan) {
  1202. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1203. _this.name = name;
  1204. _this.value = value;
  1205. return _this;
  1206. }
  1207. WriteVarExpr.prototype.isEquivalent = function (e) {
  1208. return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
  1209. };
  1210. WriteVarExpr.prototype.isConstant = function () { return false; };
  1211. WriteVarExpr.prototype.visitExpression = function (visitor, context) {
  1212. return visitor.visitWriteVarExpr(this, context);
  1213. };
  1214. WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
  1215. return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
  1216. };
  1217. WriteVarExpr.prototype.toConstDecl = function () { return this.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]); };
  1218. return WriteVarExpr;
  1219. }(Expression));
  1220. var WriteKeyExpr = /** @class */ (function (_super) {
  1221. __extends(WriteKeyExpr, _super);
  1222. function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
  1223. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1224. _this.receiver = receiver;
  1225. _this.index = index;
  1226. _this.value = value;
  1227. return _this;
  1228. }
  1229. WriteKeyExpr.prototype.isEquivalent = function (e) {
  1230. return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1231. this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
  1232. };
  1233. WriteKeyExpr.prototype.isConstant = function () { return false; };
  1234. WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
  1235. return visitor.visitWriteKeyExpr(this, context);
  1236. };
  1237. return WriteKeyExpr;
  1238. }(Expression));
  1239. var WritePropExpr = /** @class */ (function (_super) {
  1240. __extends(WritePropExpr, _super);
  1241. function WritePropExpr(receiver, name, value, type, sourceSpan) {
  1242. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1243. _this.receiver = receiver;
  1244. _this.name = name;
  1245. _this.value = value;
  1246. return _this;
  1247. }
  1248. WritePropExpr.prototype.isEquivalent = function (e) {
  1249. return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
  1250. this.name === e.name && this.value.isEquivalent(e.value);
  1251. };
  1252. WritePropExpr.prototype.isConstant = function () { return false; };
  1253. WritePropExpr.prototype.visitExpression = function (visitor, context) {
  1254. return visitor.visitWritePropExpr(this, context);
  1255. };
  1256. return WritePropExpr;
  1257. }(Expression));
  1258. var BuiltinMethod;
  1259. (function (BuiltinMethod) {
  1260. BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
  1261. BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
  1262. BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
  1263. })(BuiltinMethod || (BuiltinMethod = {}));
  1264. var InvokeMethodExpr = /** @class */ (function (_super) {
  1265. __extends(InvokeMethodExpr, _super);
  1266. function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
  1267. var _this = _super.call(this, type, sourceSpan) || this;
  1268. _this.receiver = receiver;
  1269. _this.args = args;
  1270. if (typeof method === 'string') {
  1271. _this.name = method;
  1272. _this.builtin = null;
  1273. }
  1274. else {
  1275. _this.name = null;
  1276. _this.builtin = method;
  1277. }
  1278. return _this;
  1279. }
  1280. InvokeMethodExpr.prototype.isEquivalent = function (e) {
  1281. return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
  1282. this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
  1283. };
  1284. InvokeMethodExpr.prototype.isConstant = function () { return false; };
  1285. InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
  1286. return visitor.visitInvokeMethodExpr(this, context);
  1287. };
  1288. return InvokeMethodExpr;
  1289. }(Expression));
  1290. var InvokeFunctionExpr = /** @class */ (function (_super) {
  1291. __extends(InvokeFunctionExpr, _super);
  1292. function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) {
  1293. if (pure === void 0) { pure = false; }
  1294. var _this = _super.call(this, type, sourceSpan) || this;
  1295. _this.fn = fn;
  1296. _this.args = args;
  1297. _this.pure = pure;
  1298. return _this;
  1299. }
  1300. InvokeFunctionExpr.prototype.isEquivalent = function (e) {
  1301. return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
  1302. areAllEquivalent(this.args, e.args) && this.pure === e.pure;
  1303. };
  1304. InvokeFunctionExpr.prototype.isConstant = function () { return false; };
  1305. InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
  1306. return visitor.visitInvokeFunctionExpr(this, context);
  1307. };
  1308. return InvokeFunctionExpr;
  1309. }(Expression));
  1310. var InstantiateExpr = /** @class */ (function (_super) {
  1311. __extends(InstantiateExpr, _super);
  1312. function InstantiateExpr(classExpr, args, type, sourceSpan) {
  1313. var _this = _super.call(this, type, sourceSpan) || this;
  1314. _this.classExpr = classExpr;
  1315. _this.args = args;
  1316. return _this;
  1317. }
  1318. InstantiateExpr.prototype.isEquivalent = function (e) {
  1319. return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
  1320. areAllEquivalent(this.args, e.args);
  1321. };
  1322. InstantiateExpr.prototype.isConstant = function () { return false; };
  1323. InstantiateExpr.prototype.visitExpression = function (visitor, context) {
  1324. return visitor.visitInstantiateExpr(this, context);
  1325. };
  1326. return InstantiateExpr;
  1327. }(Expression));
  1328. var LiteralExpr = /** @class */ (function (_super) {
  1329. __extends(LiteralExpr, _super);
  1330. function LiteralExpr(value, type, sourceSpan) {
  1331. var _this = _super.call(this, type, sourceSpan) || this;
  1332. _this.value = value;
  1333. return _this;
  1334. }
  1335. LiteralExpr.prototype.isEquivalent = function (e) {
  1336. return e instanceof LiteralExpr && this.value === e.value;
  1337. };
  1338. LiteralExpr.prototype.isConstant = function () { return true; };
  1339. LiteralExpr.prototype.visitExpression = function (visitor, context) {
  1340. return visitor.visitLiteralExpr(this, context);
  1341. };
  1342. return LiteralExpr;
  1343. }(Expression));
  1344. var ExternalExpr = /** @class */ (function (_super) {
  1345. __extends(ExternalExpr, _super);
  1346. function ExternalExpr(value, type, typeParams, sourceSpan) {
  1347. if (typeParams === void 0) { typeParams = null; }
  1348. var _this = _super.call(this, type, sourceSpan) || this;
  1349. _this.value = value;
  1350. _this.typeParams = typeParams;
  1351. return _this;
  1352. }
  1353. ExternalExpr.prototype.isEquivalent = function (e) {
  1354. return e instanceof ExternalExpr && this.value.name === e.value.name &&
  1355. this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
  1356. };
  1357. ExternalExpr.prototype.isConstant = function () { return false; };
  1358. ExternalExpr.prototype.visitExpression = function (visitor, context) {
  1359. return visitor.visitExternalExpr(this, context);
  1360. };
  1361. return ExternalExpr;
  1362. }(Expression));
  1363. var ExternalReference = /** @class */ (function () {
  1364. function ExternalReference(moduleName, name, runtime) {
  1365. this.moduleName = moduleName;
  1366. this.name = name;
  1367. this.runtime = runtime;
  1368. }
  1369. return ExternalReference;
  1370. }());
  1371. var ConditionalExpr = /** @class */ (function (_super) {
  1372. __extends(ConditionalExpr, _super);
  1373. function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
  1374. if (falseCase === void 0) { falseCase = null; }
  1375. var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
  1376. _this.condition = condition;
  1377. _this.falseCase = falseCase;
  1378. _this.trueCase = trueCase;
  1379. return _this;
  1380. }
  1381. ConditionalExpr.prototype.isEquivalent = function (e) {
  1382. return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
  1383. this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
  1384. };
  1385. ConditionalExpr.prototype.isConstant = function () { return false; };
  1386. ConditionalExpr.prototype.visitExpression = function (visitor, context) {
  1387. return visitor.visitConditionalExpr(this, context);
  1388. };
  1389. return ConditionalExpr;
  1390. }(Expression));
  1391. var NotExpr = /** @class */ (function (_super) {
  1392. __extends(NotExpr, _super);
  1393. function NotExpr(condition, sourceSpan) {
  1394. var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
  1395. _this.condition = condition;
  1396. return _this;
  1397. }
  1398. NotExpr.prototype.isEquivalent = function (e) {
  1399. return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
  1400. };
  1401. NotExpr.prototype.isConstant = function () { return false; };
  1402. NotExpr.prototype.visitExpression = function (visitor, context) {
  1403. return visitor.visitNotExpr(this, context);
  1404. };
  1405. return NotExpr;
  1406. }(Expression));
  1407. var AssertNotNull = /** @class */ (function (_super) {
  1408. __extends(AssertNotNull, _super);
  1409. function AssertNotNull(condition, sourceSpan) {
  1410. var _this = _super.call(this, condition.type, sourceSpan) || this;
  1411. _this.condition = condition;
  1412. return _this;
  1413. }
  1414. AssertNotNull.prototype.isEquivalent = function (e) {
  1415. return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
  1416. };
  1417. AssertNotNull.prototype.isConstant = function () { return false; };
  1418. AssertNotNull.prototype.visitExpression = function (visitor, context) {
  1419. return visitor.visitAssertNotNullExpr(this, context);
  1420. };
  1421. return AssertNotNull;
  1422. }(Expression));
  1423. var CastExpr = /** @class */ (function (_super) {
  1424. __extends(CastExpr, _super);
  1425. function CastExpr(value, type, sourceSpan) {
  1426. var _this = _super.call(this, type, sourceSpan) || this;
  1427. _this.value = value;
  1428. return _this;
  1429. }
  1430. CastExpr.prototype.isEquivalent = function (e) {
  1431. return e instanceof CastExpr && this.value.isEquivalent(e.value);
  1432. };
  1433. CastExpr.prototype.isConstant = function () { return false; };
  1434. CastExpr.prototype.visitExpression = function (visitor, context) {
  1435. return visitor.visitCastExpr(this, context);
  1436. };
  1437. return CastExpr;
  1438. }(Expression));
  1439. var FnParam = /** @class */ (function () {
  1440. function FnParam(name, type) {
  1441. if (type === void 0) { type = null; }
  1442. this.name = name;
  1443. this.type = type;
  1444. }
  1445. FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; };
  1446. return FnParam;
  1447. }());
  1448. var FunctionExpr = /** @class */ (function (_super) {
  1449. __extends(FunctionExpr, _super);
  1450. function FunctionExpr(params, statements, type, sourceSpan, name) {
  1451. var _this = _super.call(this, type, sourceSpan) || this;
  1452. _this.params = params;
  1453. _this.statements = statements;
  1454. _this.name = name;
  1455. return _this;
  1456. }
  1457. FunctionExpr.prototype.isEquivalent = function (e) {
  1458. return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
  1459. areAllEquivalent(this.statements, e.statements);
  1460. };
  1461. FunctionExpr.prototype.isConstant = function () { return false; };
  1462. FunctionExpr.prototype.visitExpression = function (visitor, context) {
  1463. return visitor.visitFunctionExpr(this, context);
  1464. };
  1465. FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
  1466. if (modifiers === void 0) { modifiers = null; }
  1467. return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
  1468. };
  1469. return FunctionExpr;
  1470. }(Expression));
  1471. var BinaryOperatorExpr = /** @class */ (function (_super) {
  1472. __extends(BinaryOperatorExpr, _super);
  1473. function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) {
  1474. if (parens === void 0) { parens = true; }
  1475. var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
  1476. _this.operator = operator;
  1477. _this.rhs = rhs;
  1478. _this.parens = parens;
  1479. _this.lhs = lhs;
  1480. return _this;
  1481. }
  1482. BinaryOperatorExpr.prototype.isEquivalent = function (e) {
  1483. return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
  1484. this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
  1485. };
  1486. BinaryOperatorExpr.prototype.isConstant = function () { return false; };
  1487. BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
  1488. return visitor.visitBinaryOperatorExpr(this, context);
  1489. };
  1490. return BinaryOperatorExpr;
  1491. }(Expression));
  1492. var ReadPropExpr = /** @class */ (function (_super) {
  1493. __extends(ReadPropExpr, _super);
  1494. function ReadPropExpr(receiver, name, type, sourceSpan) {
  1495. var _this = _super.call(this, type, sourceSpan) || this;
  1496. _this.receiver = receiver;
  1497. _this.name = name;
  1498. return _this;
  1499. }
  1500. ReadPropExpr.prototype.isEquivalent = function (e) {
  1501. return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
  1502. this.name === e.name;
  1503. };
  1504. ReadPropExpr.prototype.isConstant = function () { return false; };
  1505. ReadPropExpr.prototype.visitExpression = function (visitor, context) {
  1506. return visitor.visitReadPropExpr(this, context);
  1507. };
  1508. ReadPropExpr.prototype.set = function (value) {
  1509. return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
  1510. };
  1511. return ReadPropExpr;
  1512. }(Expression));
  1513. var ReadKeyExpr = /** @class */ (function (_super) {
  1514. __extends(ReadKeyExpr, _super);
  1515. function ReadKeyExpr(receiver, index, type, sourceSpan) {
  1516. var _this = _super.call(this, type, sourceSpan) || this;
  1517. _this.receiver = receiver;
  1518. _this.index = index;
  1519. return _this;
  1520. }
  1521. ReadKeyExpr.prototype.isEquivalent = function (e) {
  1522. return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1523. this.index.isEquivalent(e.index);
  1524. };
  1525. ReadKeyExpr.prototype.isConstant = function () { return false; };
  1526. ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
  1527. return visitor.visitReadKeyExpr(this, context);
  1528. };
  1529. ReadKeyExpr.prototype.set = function (value) {
  1530. return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
  1531. };
  1532. return ReadKeyExpr;
  1533. }(Expression));
  1534. var LiteralArrayExpr = /** @class */ (function (_super) {
  1535. __extends(LiteralArrayExpr, _super);
  1536. function LiteralArrayExpr(entries, type, sourceSpan) {
  1537. var _this = _super.call(this, type, sourceSpan) || this;
  1538. _this.entries = entries;
  1539. return _this;
  1540. }
  1541. LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); };
  1542. LiteralArrayExpr.prototype.isEquivalent = function (e) {
  1543. return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
  1544. };
  1545. LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
  1546. return visitor.visitLiteralArrayExpr(this, context);
  1547. };
  1548. return LiteralArrayExpr;
  1549. }(Expression));
  1550. var LiteralMapEntry = /** @class */ (function () {
  1551. function LiteralMapEntry(key, value, quoted) {
  1552. this.key = key;
  1553. this.value = value;
  1554. this.quoted = quoted;
  1555. }
  1556. LiteralMapEntry.prototype.isEquivalent = function (e) {
  1557. return this.key === e.key && this.value.isEquivalent(e.value);
  1558. };
  1559. return LiteralMapEntry;
  1560. }());
  1561. var LiteralMapExpr = /** @class */ (function (_super) {
  1562. __extends(LiteralMapExpr, _super);
  1563. function LiteralMapExpr(entries, type, sourceSpan) {
  1564. var _this = _super.call(this, type, sourceSpan) || this;
  1565. _this.entries = entries;
  1566. _this.valueType = null;
  1567. if (type) {
  1568. _this.valueType = type.valueType;
  1569. }
  1570. return _this;
  1571. }
  1572. LiteralMapExpr.prototype.isEquivalent = function (e) {
  1573. return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
  1574. };
  1575. LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); };
  1576. LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
  1577. return visitor.visitLiteralMapExpr(this, context);
  1578. };
  1579. return LiteralMapExpr;
  1580. }(Expression));
  1581. var CommaExpr = /** @class */ (function (_super) {
  1582. __extends(CommaExpr, _super);
  1583. function CommaExpr(parts, sourceSpan) {
  1584. var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
  1585. _this.parts = parts;
  1586. return _this;
  1587. }
  1588. CommaExpr.prototype.isEquivalent = function (e) {
  1589. return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
  1590. };
  1591. CommaExpr.prototype.isConstant = function () { return false; };
  1592. CommaExpr.prototype.visitExpression = function (visitor, context) {
  1593. return visitor.visitCommaExpr(this, context);
  1594. };
  1595. return CommaExpr;
  1596. }(Expression));
  1597. var THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
  1598. var SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
  1599. var CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
  1600. var CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
  1601. var NULL_EXPR = new LiteralExpr(null, null, null);
  1602. var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
  1603. //// Statements
  1604. var StmtModifier;
  1605. (function (StmtModifier) {
  1606. StmtModifier[StmtModifier["Final"] = 0] = "Final";
  1607. StmtModifier[StmtModifier["Private"] = 1] = "Private";
  1608. StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
  1609. StmtModifier[StmtModifier["Static"] = 3] = "Static";
  1610. })(StmtModifier || (StmtModifier = {}));
  1611. var Statement = /** @class */ (function () {
  1612. function Statement(modifiers, sourceSpan) {
  1613. this.modifiers = modifiers || [];
  1614. this.sourceSpan = sourceSpan || null;
  1615. }
  1616. Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1617. return Statement;
  1618. }());
  1619. var DeclareVarStmt = /** @class */ (function (_super) {
  1620. __extends(DeclareVarStmt, _super);
  1621. function DeclareVarStmt(name, value, type, modifiers, sourceSpan) {
  1622. if (modifiers === void 0) { modifiers = null; }
  1623. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1624. _this.name = name;
  1625. _this.value = value;
  1626. _this.type = type || (value && value.type) || null;
  1627. return _this;
  1628. }
  1629. DeclareVarStmt.prototype.isEquivalent = function (stmt) {
  1630. return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
  1631. (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
  1632. };
  1633. DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
  1634. return visitor.visitDeclareVarStmt(this, context);
  1635. };
  1636. return DeclareVarStmt;
  1637. }(Statement));
  1638. var DeclareFunctionStmt = /** @class */ (function (_super) {
  1639. __extends(DeclareFunctionStmt, _super);
  1640. function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) {
  1641. if (modifiers === void 0) { modifiers = null; }
  1642. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1643. _this.name = name;
  1644. _this.params = params;
  1645. _this.statements = statements;
  1646. _this.type = type || null;
  1647. return _this;
  1648. }
  1649. DeclareFunctionStmt.prototype.isEquivalent = function (stmt) {
  1650. return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
  1651. areAllEquivalent(this.statements, stmt.statements);
  1652. };
  1653. DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
  1654. return visitor.visitDeclareFunctionStmt(this, context);
  1655. };
  1656. return DeclareFunctionStmt;
  1657. }(Statement));
  1658. var ExpressionStatement = /** @class */ (function (_super) {
  1659. __extends(ExpressionStatement, _super);
  1660. function ExpressionStatement(expr, sourceSpan) {
  1661. var _this = _super.call(this, null, sourceSpan) || this;
  1662. _this.expr = expr;
  1663. return _this;
  1664. }
  1665. ExpressionStatement.prototype.isEquivalent = function (stmt) {
  1666. return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
  1667. };
  1668. ExpressionStatement.prototype.visitStatement = function (visitor, context) {
  1669. return visitor.visitExpressionStmt(this, context);
  1670. };
  1671. return ExpressionStatement;
  1672. }(Statement));
  1673. var ReturnStatement = /** @class */ (function (_super) {
  1674. __extends(ReturnStatement, _super);
  1675. function ReturnStatement(value, sourceSpan) {
  1676. var _this = _super.call(this, null, sourceSpan) || this;
  1677. _this.value = value;
  1678. return _this;
  1679. }
  1680. ReturnStatement.prototype.isEquivalent = function (stmt) {
  1681. return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
  1682. };
  1683. ReturnStatement.prototype.visitStatement = function (visitor, context) {
  1684. return visitor.visitReturnStmt(this, context);
  1685. };
  1686. return ReturnStatement;
  1687. }(Statement));
  1688. var AbstractClassPart = /** @class */ (function () {
  1689. function AbstractClassPart(type, modifiers) {
  1690. this.modifiers = modifiers;
  1691. if (!modifiers) {
  1692. this.modifiers = [];
  1693. }
  1694. this.type = type || null;
  1695. }
  1696. AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1697. return AbstractClassPart;
  1698. }());
  1699. var ClassField = /** @class */ (function (_super) {
  1700. __extends(ClassField, _super);
  1701. function ClassField(name, type, modifiers, initializer) {
  1702. if (modifiers === void 0) { modifiers = null; }
  1703. var _this = _super.call(this, type, modifiers) || this;
  1704. _this.name = name;
  1705. _this.initializer = initializer;
  1706. return _this;
  1707. }
  1708. ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; };
  1709. return ClassField;
  1710. }(AbstractClassPart));
  1711. var ClassMethod = /** @class */ (function (_super) {
  1712. __extends(ClassMethod, _super);
  1713. function ClassMethod(name, params, body, type, modifiers) {
  1714. if (modifiers === void 0) { modifiers = null; }
  1715. var _this = _super.call(this, type, modifiers) || this;
  1716. _this.name = name;
  1717. _this.params = params;
  1718. _this.body = body;
  1719. return _this;
  1720. }
  1721. ClassMethod.prototype.isEquivalent = function (m) {
  1722. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1723. };
  1724. return ClassMethod;
  1725. }(AbstractClassPart));
  1726. var ClassGetter = /** @class */ (function (_super) {
  1727. __extends(ClassGetter, _super);
  1728. function ClassGetter(name, body, type, modifiers) {
  1729. if (modifiers === void 0) { modifiers = null; }
  1730. var _this = _super.call(this, type, modifiers) || this;
  1731. _this.name = name;
  1732. _this.body = body;
  1733. return _this;
  1734. }
  1735. ClassGetter.prototype.isEquivalent = function (m) {
  1736. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1737. };
  1738. return ClassGetter;
  1739. }(AbstractClassPart));
  1740. var ClassStmt = /** @class */ (function (_super) {
  1741. __extends(ClassStmt, _super);
  1742. function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) {
  1743. if (modifiers === void 0) { modifiers = null; }
  1744. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1745. _this.name = name;
  1746. _this.parent = parent;
  1747. _this.fields = fields;
  1748. _this.getters = getters;
  1749. _this.constructorMethod = constructorMethod;
  1750. _this.methods = methods;
  1751. return _this;
  1752. }
  1753. ClassStmt.prototype.isEquivalent = function (stmt) {
  1754. return stmt instanceof ClassStmt && this.name === stmt.name &&
  1755. nullSafeIsEquivalent(this.parent, stmt.parent) &&
  1756. areAllEquivalent(this.fields, stmt.fields) &&
  1757. areAllEquivalent(this.getters, stmt.getters) &&
  1758. this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
  1759. areAllEquivalent(this.methods, stmt.methods);
  1760. };
  1761. ClassStmt.prototype.visitStatement = function (visitor, context) {
  1762. return visitor.visitDeclareClassStmt(this, context);
  1763. };
  1764. return ClassStmt;
  1765. }(Statement));
  1766. var IfStmt = /** @class */ (function (_super) {
  1767. __extends(IfStmt, _super);
  1768. function IfStmt(condition, trueCase, falseCase, sourceSpan) {
  1769. if (falseCase === void 0) { falseCase = []; }
  1770. var _this = _super.call(this, null, sourceSpan) || this;
  1771. _this.condition = condition;
  1772. _this.trueCase = trueCase;
  1773. _this.falseCase = falseCase;
  1774. return _this;
  1775. }
  1776. IfStmt.prototype.isEquivalent = function (stmt) {
  1777. return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
  1778. areAllEquivalent(this.trueCase, stmt.trueCase) &&
  1779. areAllEquivalent(this.falseCase, stmt.falseCase);
  1780. };
  1781. IfStmt.prototype.visitStatement = function (visitor, context) {
  1782. return visitor.visitIfStmt(this, context);
  1783. };
  1784. return IfStmt;
  1785. }(Statement));
  1786. var CommentStmt = /** @class */ (function (_super) {
  1787. __extends(CommentStmt, _super);
  1788. function CommentStmt(comment, multiline, sourceSpan) {
  1789. if (multiline === void 0) { multiline = false; }
  1790. var _this = _super.call(this, null, sourceSpan) || this;
  1791. _this.comment = comment;
  1792. _this.multiline = multiline;
  1793. return _this;
  1794. }
  1795. CommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof CommentStmt; };
  1796. CommentStmt.prototype.visitStatement = function (visitor, context) {
  1797. return visitor.visitCommentStmt(this, context);
  1798. };
  1799. return CommentStmt;
  1800. }(Statement));
  1801. var JSDocCommentStmt = /** @class */ (function (_super) {
  1802. __extends(JSDocCommentStmt, _super);
  1803. function JSDocCommentStmt(tags, sourceSpan) {
  1804. if (tags === void 0) { tags = []; }
  1805. var _this = _super.call(this, null, sourceSpan) || this;
  1806. _this.tags = tags;
  1807. return _this;
  1808. }
  1809. JSDocCommentStmt.prototype.isEquivalent = function (stmt) {
  1810. return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString();
  1811. };
  1812. JSDocCommentStmt.prototype.visitStatement = function (visitor, context) {
  1813. return visitor.visitJSDocCommentStmt(this, context);
  1814. };
  1815. JSDocCommentStmt.prototype.toString = function () { return serializeTags(this.tags); };
  1816. return JSDocCommentStmt;
  1817. }(Statement));
  1818. var TryCatchStmt = /** @class */ (function (_super) {
  1819. __extends(TryCatchStmt, _super);
  1820. function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) {
  1821. var _this = _super.call(this, null, sourceSpan) || this;
  1822. _this.bodyStmts = bodyStmts;
  1823. _this.catchStmts = catchStmts;
  1824. return _this;
  1825. }
  1826. TryCatchStmt.prototype.isEquivalent = function (stmt) {
  1827. return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
  1828. areAllEquivalent(this.catchStmts, stmt.catchStmts);
  1829. };
  1830. TryCatchStmt.prototype.visitStatement = function (visitor, context) {
  1831. return visitor.visitTryCatchStmt(this, context);
  1832. };
  1833. return TryCatchStmt;
  1834. }(Statement));
  1835. var ThrowStmt = /** @class */ (function (_super) {
  1836. __extends(ThrowStmt, _super);
  1837. function ThrowStmt(error, sourceSpan) {
  1838. var _this = _super.call(this, null, sourceSpan) || this;
  1839. _this.error = error;
  1840. return _this;
  1841. }
  1842. ThrowStmt.prototype.isEquivalent = function (stmt) {
  1843. return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
  1844. };
  1845. ThrowStmt.prototype.visitStatement = function (visitor, context) {
  1846. return visitor.visitThrowStmt(this, context);
  1847. };
  1848. return ThrowStmt;
  1849. }(Statement));
  1850. var AstTransformer = /** @class */ (function () {
  1851. function AstTransformer() {
  1852. }
  1853. AstTransformer.prototype.transformExpr = function (expr, context) { return expr; };
  1854. AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; };
  1855. AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); };
  1856. AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) {
  1857. return this.transformExpr(ast, context);
  1858. };
  1859. AstTransformer.prototype.visitTypeofExpr = function (expr, context) {
  1860. return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1861. };
  1862. AstTransformer.prototype.visitWriteVarExpr = function (expr, context) {
  1863. return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1864. };
  1865. AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) {
  1866. 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);
  1867. };
  1868. AstTransformer.prototype.visitWritePropExpr = function (expr, context) {
  1869. return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1870. };
  1871. AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) {
  1872. var method = ast.builtin || ast.name;
  1873. return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1874. };
  1875. AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) {
  1876. return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1877. };
  1878. AstTransformer.prototype.visitInstantiateExpr = function (ast, context) {
  1879. return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1880. };
  1881. AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); };
  1882. AstTransformer.prototype.visitExternalExpr = function (ast, context) {
  1883. return this.transformExpr(ast, context);
  1884. };
  1885. AstTransformer.prototype.visitConditionalExpr = function (ast, context) {
  1886. 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);
  1887. };
  1888. AstTransformer.prototype.visitNotExpr = function (ast, context) {
  1889. return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1890. };
  1891. AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) {
  1892. return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1893. };
  1894. AstTransformer.prototype.visitCastExpr = function (ast, context) {
  1895. return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1896. };
  1897. AstTransformer.prototype.visitFunctionExpr = function (ast, context) {
  1898. return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
  1899. };
  1900. AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) {
  1901. return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1902. };
  1903. AstTransformer.prototype.visitReadPropExpr = function (ast, context) {
  1904. return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
  1905. };
  1906. AstTransformer.prototype.visitReadKeyExpr = function (ast, context) {
  1907. return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1908. };
  1909. AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) {
  1910. return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
  1911. };
  1912. AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) {
  1913. var _this = this;
  1914. var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
  1915. var mapType = new MapType(ast.valueType, null);
  1916. return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
  1917. };
  1918. AstTransformer.prototype.visitCommaExpr = function (ast, context) {
  1919. return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
  1920. };
  1921. AstTransformer.prototype.visitAllExpressions = function (exprs, context) {
  1922. var _this = this;
  1923. return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
  1924. };
  1925. AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) {
  1926. var value = stmt.value && stmt.value.visitExpression(this, context);
  1927. return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1928. };
  1929. AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  1930. return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1931. };
  1932. AstTransformer.prototype.visitExpressionStmt = function (stmt, context) {
  1933. return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
  1934. };
  1935. AstTransformer.prototype.visitReturnStmt = function (stmt, context) {
  1936. return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
  1937. };
  1938. AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) {
  1939. var _this = this;
  1940. var parent = stmt.parent.visitExpression(this, context);
  1941. var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
  1942. var ctorMethod = stmt.constructorMethod &&
  1943. new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
  1944. var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
  1945. return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
  1946. };
  1947. AstTransformer.prototype.visitIfStmt = function (stmt, context) {
  1948. return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
  1949. };
  1950. AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) {
  1951. return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
  1952. };
  1953. AstTransformer.prototype.visitThrowStmt = function (stmt, context) {
  1954. return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
  1955. };
  1956. AstTransformer.prototype.visitCommentStmt = function (stmt, context) {
  1957. return this.transformStmt(stmt, context);
  1958. };
  1959. AstTransformer.prototype.visitJSDocCommentStmt = function (stmt, context) {
  1960. return this.transformStmt(stmt, context);
  1961. };
  1962. AstTransformer.prototype.visitAllStatements = function (stmts, context) {
  1963. var _this = this;
  1964. return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
  1965. };
  1966. return AstTransformer;
  1967. }());
  1968. var RecursiveAstVisitor = /** @class */ (function () {
  1969. function RecursiveAstVisitor() {
  1970. }
  1971. RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; };
  1972. RecursiveAstVisitor.prototype.visitExpression = function (ast, context) {
  1973. if (ast.type) {
  1974. ast.type.visitType(this, context);
  1975. }
  1976. return ast;
  1977. };
  1978. RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); };
  1979. RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) {
  1980. var _this = this;
  1981. type.value.visitExpression(this, context);
  1982. if (type.typeParams !== null) {
  1983. type.typeParams.forEach(function (param) { return _this.visitType(param, context); });
  1984. }
  1985. return this.visitType(type, context);
  1986. };
  1987. RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); };
  1988. RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); };
  1989. RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) { return ast; };
  1990. RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) { return this.visitExpression(ast, context); };
  1991. RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) {
  1992. return this.visitExpression(ast, context);
  1993. };
  1994. RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) {
  1995. ast.value.visitExpression(this, context);
  1996. return this.visitExpression(ast, context);
  1997. };
  1998. RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) {
  1999. ast.receiver.visitExpression(this, context);
  2000. ast.index.visitExpression(this, context);
  2001. ast.value.visitExpression(this, context);
  2002. return this.visitExpression(ast, context);
  2003. };
  2004. RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) {
  2005. ast.receiver.visitExpression(this, context);
  2006. ast.value.visitExpression(this, context);
  2007. return this.visitExpression(ast, context);
  2008. };
  2009. RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) {
  2010. ast.receiver.visitExpression(this, context);
  2011. this.visitAllExpressions(ast.args, context);
  2012. return this.visitExpression(ast, context);
  2013. };
  2014. RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) {
  2015. ast.fn.visitExpression(this, context);
  2016. this.visitAllExpressions(ast.args, context);
  2017. return this.visitExpression(ast, context);
  2018. };
  2019. RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) {
  2020. ast.classExpr.visitExpression(this, context);
  2021. this.visitAllExpressions(ast.args, context);
  2022. return this.visitExpression(ast, context);
  2023. };
  2024. RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) {
  2025. return this.visitExpression(ast, context);
  2026. };
  2027. RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) {
  2028. var _this = this;
  2029. if (ast.typeParams) {
  2030. ast.typeParams.forEach(function (type) { return type.visitType(_this, context); });
  2031. }
  2032. return this.visitExpression(ast, context);
  2033. };
  2034. RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) {
  2035. ast.condition.visitExpression(this, context);
  2036. ast.trueCase.visitExpression(this, context);
  2037. ast.falseCase.visitExpression(this, context);
  2038. return this.visitExpression(ast, context);
  2039. };
  2040. RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) {
  2041. ast.condition.visitExpression(this, context);
  2042. return this.visitExpression(ast, context);
  2043. };
  2044. RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) {
  2045. ast.condition.visitExpression(this, context);
  2046. return this.visitExpression(ast, context);
  2047. };
  2048. RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) {
  2049. ast.value.visitExpression(this, context);
  2050. return this.visitExpression(ast, context);
  2051. };
  2052. RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) {
  2053. this.visitAllStatements(ast.statements, context);
  2054. return this.visitExpression(ast, context);
  2055. };
  2056. RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) {
  2057. ast.lhs.visitExpression(this, context);
  2058. ast.rhs.visitExpression(this, context);
  2059. return this.visitExpression(ast, context);
  2060. };
  2061. RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) {
  2062. ast.receiver.visitExpression(this, context);
  2063. return this.visitExpression(ast, context);
  2064. };
  2065. RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) {
  2066. ast.receiver.visitExpression(this, context);
  2067. ast.index.visitExpression(this, context);
  2068. return this.visitExpression(ast, context);
  2069. };
  2070. RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2071. this.visitAllExpressions(ast.entries, context);
  2072. return this.visitExpression(ast, context);
  2073. };
  2074. RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2075. var _this = this;
  2076. ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
  2077. return this.visitExpression(ast, context);
  2078. };
  2079. RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) {
  2080. this.visitAllExpressions(ast.parts, context);
  2081. return this.visitExpression(ast, context);
  2082. };
  2083. RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) {
  2084. var _this = this;
  2085. exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
  2086. };
  2087. RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) {
  2088. if (stmt.value) {
  2089. stmt.value.visitExpression(this, context);
  2090. }
  2091. if (stmt.type) {
  2092. stmt.type.visitType(this, context);
  2093. }
  2094. return stmt;
  2095. };
  2096. RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2097. this.visitAllStatements(stmt.statements, context);
  2098. if (stmt.type) {
  2099. stmt.type.visitType(this, context);
  2100. }
  2101. return stmt;
  2102. };
  2103. RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) {
  2104. stmt.expr.visitExpression(this, context);
  2105. return stmt;
  2106. };
  2107. RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) {
  2108. stmt.value.visitExpression(this, context);
  2109. return stmt;
  2110. };
  2111. RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2112. var _this = this;
  2113. stmt.parent.visitExpression(this, context);
  2114. stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
  2115. if (stmt.constructorMethod) {
  2116. this.visitAllStatements(stmt.constructorMethod.body, context);
  2117. }
  2118. stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
  2119. return stmt;
  2120. };
  2121. RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) {
  2122. stmt.condition.visitExpression(this, context);
  2123. this.visitAllStatements(stmt.trueCase, context);
  2124. this.visitAllStatements(stmt.falseCase, context);
  2125. return stmt;
  2126. };
  2127. RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) {
  2128. this.visitAllStatements(stmt.bodyStmts, context);
  2129. this.visitAllStatements(stmt.catchStmts, context);
  2130. return stmt;
  2131. };
  2132. RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) {
  2133. stmt.error.visitExpression(this, context);
  2134. return stmt;
  2135. };
  2136. RecursiveAstVisitor.prototype.visitCommentStmt = function (stmt, context) { return stmt; };
  2137. RecursiveAstVisitor.prototype.visitJSDocCommentStmt = function (stmt, context) { return stmt; };
  2138. RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) {
  2139. var _this = this;
  2140. stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
  2141. };
  2142. return RecursiveAstVisitor;
  2143. }());
  2144. function findReadVarNames(stmts) {
  2145. var visitor = new _ReadVarVisitor();
  2146. visitor.visitAllStatements(stmts, null);
  2147. return visitor.varNames;
  2148. }
  2149. var _ReadVarVisitor = /** @class */ (function (_super) {
  2150. __extends(_ReadVarVisitor, _super);
  2151. function _ReadVarVisitor() {
  2152. var _this = _super !== null && _super.apply(this, arguments) || this;
  2153. _this.varNames = new Set();
  2154. return _this;
  2155. }
  2156. _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2157. // Don't descend into nested functions
  2158. return stmt;
  2159. };
  2160. _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2161. // Don't descend into nested classes
  2162. return stmt;
  2163. };
  2164. _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2165. if (ast.name) {
  2166. this.varNames.add(ast.name);
  2167. }
  2168. return null;
  2169. };
  2170. return _ReadVarVisitor;
  2171. }(RecursiveAstVisitor));
  2172. function collectExternalReferences(stmts) {
  2173. var visitor = new _FindExternalReferencesVisitor();
  2174. visitor.visitAllStatements(stmts, null);
  2175. return visitor.externalReferences;
  2176. }
  2177. var _FindExternalReferencesVisitor = /** @class */ (function (_super) {
  2178. __extends(_FindExternalReferencesVisitor, _super);
  2179. function _FindExternalReferencesVisitor() {
  2180. var _this = _super !== null && _super.apply(this, arguments) || this;
  2181. _this.externalReferences = [];
  2182. return _this;
  2183. }
  2184. _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) {
  2185. this.externalReferences.push(e.value);
  2186. return _super.prototype.visitExternalExpr.call(this, e, context);
  2187. };
  2188. return _FindExternalReferencesVisitor;
  2189. }(RecursiveAstVisitor));
  2190. function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
  2191. if (!sourceSpan) {
  2192. return stmt;
  2193. }
  2194. var transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2195. return stmt.visitStatement(transformer, null);
  2196. }
  2197. function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
  2198. if (!sourceSpan) {
  2199. return expr;
  2200. }
  2201. var transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2202. return expr.visitExpression(transformer, null);
  2203. }
  2204. var _ApplySourceSpanTransformer = /** @class */ (function (_super) {
  2205. __extends(_ApplySourceSpanTransformer, _super);
  2206. function _ApplySourceSpanTransformer(sourceSpan) {
  2207. var _this = _super.call(this) || this;
  2208. _this.sourceSpan = sourceSpan;
  2209. return _this;
  2210. }
  2211. _ApplySourceSpanTransformer.prototype._clone = function (obj) {
  2212. var clone = Object.create(obj.constructor.prototype);
  2213. for (var prop in obj) {
  2214. clone[prop] = obj[prop];
  2215. }
  2216. return clone;
  2217. };
  2218. _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
  2219. if (!expr.sourceSpan) {
  2220. expr = this._clone(expr);
  2221. expr.sourceSpan = this.sourceSpan;
  2222. }
  2223. return expr;
  2224. };
  2225. _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
  2226. if (!stmt.sourceSpan) {
  2227. stmt = this._clone(stmt);
  2228. stmt.sourceSpan = this.sourceSpan;
  2229. }
  2230. return stmt;
  2231. };
  2232. return _ApplySourceSpanTransformer;
  2233. }(AstTransformer));
  2234. function variable(name, type, sourceSpan) {
  2235. return new ReadVarExpr(name, type, sourceSpan);
  2236. }
  2237. function importExpr(id, typeParams, sourceSpan) {
  2238. if (typeParams === void 0) { typeParams = null; }
  2239. return new ExternalExpr(id, null, typeParams, sourceSpan);
  2240. }
  2241. function importType(id, typeParams, typeModifiers) {
  2242. if (typeParams === void 0) { typeParams = null; }
  2243. if (typeModifiers === void 0) { typeModifiers = null; }
  2244. return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
  2245. }
  2246. function expressionType(expr, typeModifiers, typeParams) {
  2247. if (typeModifiers === void 0) { typeModifiers = null; }
  2248. if (typeParams === void 0) { typeParams = null; }
  2249. return new ExpressionType(expr, typeModifiers, typeParams);
  2250. }
  2251. function typeofExpr(expr) {
  2252. return new TypeofExpr(expr);
  2253. }
  2254. function literalArr(values, type, sourceSpan) {
  2255. return new LiteralArrayExpr(values, type, sourceSpan);
  2256. }
  2257. function literalMap(values, type) {
  2258. if (type === void 0) { type = null; }
  2259. return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null);
  2260. }
  2261. function not(expr, sourceSpan) {
  2262. return new NotExpr(expr, sourceSpan);
  2263. }
  2264. function assertNotNull(expr, sourceSpan) {
  2265. return new AssertNotNull(expr, sourceSpan);
  2266. }
  2267. function fn(params, body, type, sourceSpan, name) {
  2268. return new FunctionExpr(params, body, type, sourceSpan, name);
  2269. }
  2270. function ifStmt(condition, thenClause, elseClause) {
  2271. return new IfStmt(condition, thenClause, elseClause);
  2272. }
  2273. function literal(value, type, sourceSpan) {
  2274. return new LiteralExpr(value, type, sourceSpan);
  2275. }
  2276. function isNull(exp) {
  2277. return exp instanceof LiteralExpr && exp.value === null;
  2278. }
  2279. /*
  2280. * Serializes a `Tag` into a string.
  2281. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
  2282. */
  2283. function tagToString(tag) {
  2284. var out = '';
  2285. if (tag.tagName) {
  2286. out += " @" + tag.tagName;
  2287. }
  2288. if (tag.text) {
  2289. if (tag.text.match(/\/\*|\*\//)) {
  2290. throw new Error('JSDoc text cannot contain "/*" and "*/"');
  2291. }
  2292. out += ' ' + tag.text.replace(/@/g, '\\@');
  2293. }
  2294. return out;
  2295. }
  2296. function serializeTags(tags) {
  2297. var e_1, _a;
  2298. if (tags.length === 0)
  2299. return '';
  2300. var out = '*\n';
  2301. try {
  2302. for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) {
  2303. var tag = tags_1_1.value;
  2304. out += ' *';
  2305. // If the tagToString is multi-line, insert " * " prefixes on subsequent lines.
  2306. out += tagToString(tag).replace(/\n/g, '\n * ');
  2307. out += '\n';
  2308. }
  2309. }
  2310. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2311. finally {
  2312. try {
  2313. if (tags_1_1 && !tags_1_1.done && (_a = tags_1.return)) _a.call(tags_1);
  2314. }
  2315. finally { if (e_1) throw e_1.error; }
  2316. }
  2317. out += ' ';
  2318. return out;
  2319. }
  2320. /**
  2321. * @license
  2322. * Copyright Google Inc. All Rights Reserved.
  2323. *
  2324. * Use of this source code is governed by an MIT-style license that can be
  2325. * found in the LICENSE file at https://angular.io/license
  2326. */
  2327. var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
  2328. function dashCaseToCamelCase(input) {
  2329. return input.replace(DASH_CASE_REGEXP, function () {
  2330. var m = [];
  2331. for (var _i = 0; _i < arguments.length; _i++) {
  2332. m[_i] = arguments[_i];
  2333. }
  2334. return m[1].toUpperCase();
  2335. });
  2336. }
  2337. function splitAtColon(input, defaultValues) {
  2338. return _splitAt(input, ':', defaultValues);
  2339. }
  2340. function splitAtPeriod(input, defaultValues) {
  2341. return _splitAt(input, '.', defaultValues);
  2342. }
  2343. function _splitAt(input, character, defaultValues) {
  2344. var characterIndex = input.indexOf(character);
  2345. if (characterIndex == -1)
  2346. return defaultValues;
  2347. return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
  2348. }
  2349. function visitValue(value, visitor, context) {
  2350. if (Array.isArray(value)) {
  2351. return visitor.visitArray(value, context);
  2352. }
  2353. if (isStrictStringMap(value)) {
  2354. return visitor.visitStringMap(value, context);
  2355. }
  2356. if (value == null || typeof value == 'string' || typeof value == 'number' ||
  2357. typeof value == 'boolean') {
  2358. return visitor.visitPrimitive(value, context);
  2359. }
  2360. return visitor.visitOther(value, context);
  2361. }
  2362. function isDefined(val) {
  2363. return val !== null && val !== undefined;
  2364. }
  2365. function noUndefined(val) {
  2366. return val === undefined ? null : val;
  2367. }
  2368. var ValueTransformer = /** @class */ (function () {
  2369. function ValueTransformer() {
  2370. }
  2371. ValueTransformer.prototype.visitArray = function (arr, context) {
  2372. var _this = this;
  2373. return arr.map(function (value) { return visitValue(value, _this, context); });
  2374. };
  2375. ValueTransformer.prototype.visitStringMap = function (map, context) {
  2376. var _this = this;
  2377. var result = {};
  2378. Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
  2379. return result;
  2380. };
  2381. ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
  2382. ValueTransformer.prototype.visitOther = function (value, context) { return value; };
  2383. return ValueTransformer;
  2384. }());
  2385. var SyncAsync = {
  2386. assertSync: function (value) {
  2387. if (isPromise(value)) {
  2388. throw new Error("Illegal state: value cannot be a promise");
  2389. }
  2390. return value;
  2391. },
  2392. then: function (value, cb) { return isPromise(value) ? value.then(cb) : cb(value); },
  2393. all: function (syncAsyncValues) {
  2394. return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
  2395. }
  2396. };
  2397. function error(msg) {
  2398. throw new Error("Internal Error: " + msg);
  2399. }
  2400. function syntaxError(msg, parseErrors) {
  2401. var error = Error(msg);
  2402. error[ERROR_SYNTAX_ERROR] = true;
  2403. if (parseErrors)
  2404. error[ERROR_PARSE_ERRORS] = parseErrors;
  2405. return error;
  2406. }
  2407. var ERROR_SYNTAX_ERROR = 'ngSyntaxError';
  2408. var ERROR_PARSE_ERRORS = 'ngParseErrors';
  2409. function isSyntaxError(error) {
  2410. return error[ERROR_SYNTAX_ERROR];
  2411. }
  2412. function getParseErrors(error) {
  2413. return error[ERROR_PARSE_ERRORS] || [];
  2414. }
  2415. // Escape characters that have a special meaning in Regular Expressions
  2416. function escapeRegExp(s) {
  2417. return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  2418. }
  2419. var STRING_MAP_PROTO = Object.getPrototypeOf({});
  2420. function isStrictStringMap(obj) {
  2421. return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
  2422. }
  2423. function utf8Encode(str) {
  2424. var encoded = '';
  2425. for (var index = 0; index < str.length; index++) {
  2426. var codePoint = str.charCodeAt(index);
  2427. // decode surrogate
  2428. // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  2429. if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
  2430. var low = str.charCodeAt(index + 1);
  2431. if (low >= 0xdc00 && low <= 0xdfff) {
  2432. index++;
  2433. codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
  2434. }
  2435. }
  2436. if (codePoint <= 0x7f) {
  2437. encoded += String.fromCharCode(codePoint);
  2438. }
  2439. else if (codePoint <= 0x7ff) {
  2440. encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
  2441. }
  2442. else if (codePoint <= 0xffff) {
  2443. encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2444. }
  2445. else if (codePoint <= 0x1fffff) {
  2446. encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2447. }
  2448. }
  2449. return encoded;
  2450. }
  2451. function stringify(token) {
  2452. if (typeof token === 'string') {
  2453. return token;
  2454. }
  2455. if (token instanceof Array) {
  2456. return '[' + token.map(stringify).join(', ') + ']';
  2457. }
  2458. if (token == null) {
  2459. return '' + token;
  2460. }
  2461. if (token.overriddenName) {
  2462. return "" + token.overriddenName;
  2463. }
  2464. if (token.name) {
  2465. return "" + token.name;
  2466. }
  2467. if (!token.toString) {
  2468. return 'object';
  2469. }
  2470. // WARNING: do not try to `JSON.stringify(token)` here
  2471. // see https://github.com/angular/angular/issues/23440
  2472. var res = token.toString();
  2473. if (res == null) {
  2474. return '' + res;
  2475. }
  2476. var newLineIndex = res.indexOf('\n');
  2477. return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
  2478. }
  2479. /**
  2480. * Lazily retrieves the reference value from a forwardRef.
  2481. */
  2482. function resolveForwardRef(type) {
  2483. if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
  2484. return type();
  2485. }
  2486. else {
  2487. return type;
  2488. }
  2489. }
  2490. /**
  2491. * Determine if the argument is shaped like a Promise
  2492. */
  2493. function isPromise(obj) {
  2494. // allow any Promise/A+ compliant thenable.
  2495. // It's up to the caller to ensure that obj.then conforms to the spec
  2496. return !!obj && typeof obj.then === 'function';
  2497. }
  2498. var Version = /** @class */ (function () {
  2499. function Version(full) {
  2500. this.full = full;
  2501. var splits = full.split('.');
  2502. this.major = splits[0];
  2503. this.minor = splits[1];
  2504. this.patch = splits.slice(2).join('.');
  2505. }
  2506. return Version;
  2507. }());
  2508. var __window = typeof window !== 'undefined' && window;
  2509. var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  2510. self instanceof WorkerGlobalScope && self;
  2511. var __global = typeof global !== 'undefined' && global;
  2512. // Check __global first, because in Node tests both __global and __window may be defined and _global
  2513. // should be __global in that case.
  2514. var _global = __global || __window || __self;
  2515. /**
  2516. * @license
  2517. * Copyright Google Inc. All Rights Reserved.
  2518. *
  2519. * Use of this source code is governed by an MIT-style license that can be
  2520. * found in the LICENSE file at https://angular.io/license
  2521. */
  2522. var CONSTANT_PREFIX = '_c';
  2523. /**
  2524. * Context to use when producing a key.
  2525. *
  2526. * This ensures we see the constant not the reference variable when producing
  2527. * a key.
  2528. */
  2529. var KEY_CONTEXT = {};
  2530. /**
  2531. * A node that is a place-holder that allows the node to be replaced when the actual
  2532. * node is known.
  2533. *
  2534. * This allows the constant pool to change an expression from a direct reference to
  2535. * a constant to a shared constant. It returns a fix-up node that is later allowed to
  2536. * change the referenced expression.
  2537. */
  2538. var FixupExpression = /** @class */ (function (_super) {
  2539. __extends(FixupExpression, _super);
  2540. function FixupExpression(resolved) {
  2541. var _this = _super.call(this, resolved.type) || this;
  2542. _this.resolved = resolved;
  2543. _this.original = resolved;
  2544. return _this;
  2545. }
  2546. FixupExpression.prototype.visitExpression = function (visitor, context) {
  2547. if (context === KEY_CONTEXT) {
  2548. // When producing a key we want to traverse the constant not the
  2549. // variable used to refer to it.
  2550. return this.original.visitExpression(visitor, context);
  2551. }
  2552. else {
  2553. return this.resolved.visitExpression(visitor, context);
  2554. }
  2555. };
  2556. FixupExpression.prototype.isEquivalent = function (e) {
  2557. return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
  2558. };
  2559. FixupExpression.prototype.isConstant = function () { return true; };
  2560. FixupExpression.prototype.fixup = function (expression) {
  2561. this.resolved = expression;
  2562. this.shared = true;
  2563. };
  2564. return FixupExpression;
  2565. }(Expression));
  2566. /**
  2567. * A constant pool allows a code emitter to share constant in an output context.
  2568. *
  2569. * The constant pool also supports sharing access to ivy definitions references.
  2570. */
  2571. var ConstantPool = /** @class */ (function () {
  2572. function ConstantPool() {
  2573. this.statements = [];
  2574. this.literals = new Map();
  2575. this.literalFactories = new Map();
  2576. this.injectorDefinitions = new Map();
  2577. this.directiveDefinitions = new Map();
  2578. this.componentDefinitions = new Map();
  2579. this.pipeDefinitions = new Map();
  2580. this.nextNameIndex = 0;
  2581. }
  2582. ConstantPool.prototype.getConstLiteral = function (literal, forceShared) {
  2583. if (literal instanceof LiteralExpr || literal instanceof FixupExpression) {
  2584. // Do no put simple literals into the constant pool or try to produce a constant for a
  2585. // reference to a constant.
  2586. return literal;
  2587. }
  2588. var key = this.keyOf(literal);
  2589. var fixup = this.literals.get(key);
  2590. var newValue = false;
  2591. if (!fixup) {
  2592. fixup = new FixupExpression(literal);
  2593. this.literals.set(key, fixup);
  2594. newValue = true;
  2595. }
  2596. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2597. // Replace the expression with a variable
  2598. var name_1 = this.freshName();
  2599. this.statements.push(variable(name_1).set(literal).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
  2600. fixup.fixup(variable(name_1));
  2601. }
  2602. return fixup;
  2603. };
  2604. ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) {
  2605. if (forceShared === void 0) { forceShared = false; }
  2606. var definitions = this.definitionsOf(kind);
  2607. var fixup = definitions.get(type);
  2608. var newValue = false;
  2609. if (!fixup) {
  2610. var property = this.propertyNameOf(kind);
  2611. fixup = new FixupExpression(ctx.importExpr(type).prop(property));
  2612. definitions.set(type, fixup);
  2613. newValue = true;
  2614. }
  2615. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2616. var name_2 = this.freshName();
  2617. this.statements.push(variable(name_2).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
  2618. fixup.fixup(variable(name_2));
  2619. }
  2620. return fixup;
  2621. };
  2622. ConstantPool.prototype.getLiteralFactory = function (literal$1) {
  2623. // Create a pure function that builds an array of a mix of constant and variable expressions
  2624. if (literal$1 instanceof LiteralArrayExpr) {
  2625. var argumentsForKey = literal$1.entries.map(function (e) { return e.isConstant() ? e : literal(null); });
  2626. var key = this.keyOf(literalArr(argumentsForKey));
  2627. return this._getLiteralFactory(key, literal$1.entries, function (entries) { return literalArr(entries); });
  2628. }
  2629. else {
  2630. var expressionForKey = literalMap(literal$1.entries.map(function (e) { return ({
  2631. key: e.key,
  2632. value: e.value.isConstant() ? e.value : literal(null),
  2633. quoted: e.quoted
  2634. }); }));
  2635. var key = this.keyOf(expressionForKey);
  2636. return this._getLiteralFactory(key, literal$1.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({
  2637. key: literal$1.entries[index].key,
  2638. value: value,
  2639. quoted: literal$1.entries[index].quoted
  2640. }); })); });
  2641. }
  2642. };
  2643. ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) {
  2644. var _this = this;
  2645. var literalFactory = this.literalFactories.get(key);
  2646. var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); }));
  2647. if (!literalFactory) {
  2648. var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); });
  2649. var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); });
  2650. var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
  2651. var name_3 = this.freshName();
  2652. this.statements.push(variable(name_3).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
  2653. StmtModifier.Final
  2654. ]));
  2655. literalFactory = variable(name_3);
  2656. this.literalFactories.set(key, literalFactory);
  2657. }
  2658. return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments };
  2659. };
  2660. /**
  2661. * Produce a unique name.
  2662. *
  2663. * The name might be unique among different prefixes if any of the prefixes end in
  2664. * a digit so the prefix should be a constant string (not based on user input) and
  2665. * must not end in a digit.
  2666. */
  2667. ConstantPool.prototype.uniqueName = function (prefix) { return "" + prefix + this.nextNameIndex++; };
  2668. ConstantPool.prototype.definitionsOf = function (kind) {
  2669. switch (kind) {
  2670. case 2 /* Component */:
  2671. return this.componentDefinitions;
  2672. case 1 /* Directive */:
  2673. return this.directiveDefinitions;
  2674. case 0 /* Injector */:
  2675. return this.injectorDefinitions;
  2676. case 3 /* Pipe */:
  2677. return this.pipeDefinitions;
  2678. }
  2679. error("Unknown definition kind " + kind);
  2680. return this.componentDefinitions;
  2681. };
  2682. ConstantPool.prototype.propertyNameOf = function (kind) {
  2683. switch (kind) {
  2684. case 2 /* Component */:
  2685. return 'ngComponentDef';
  2686. case 1 /* Directive */:
  2687. return 'ngDirectiveDef';
  2688. case 0 /* Injector */:
  2689. return 'ngInjectorDef';
  2690. case 3 /* Pipe */:
  2691. return 'ngPipeDef';
  2692. }
  2693. error("Unknown definition kind " + kind);
  2694. return '<unknown>';
  2695. };
  2696. ConstantPool.prototype.freshName = function () { return this.uniqueName(CONSTANT_PREFIX); };
  2697. ConstantPool.prototype.keyOf = function (expression) {
  2698. return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
  2699. };
  2700. return ConstantPool;
  2701. }());
  2702. /**
  2703. * Visitor used to determine if 2 expressions are equivalent and can be shared in the
  2704. * `ConstantPool`.
  2705. *
  2706. * When the id (string) generated by the visitor is equal, expressions are considered equivalent.
  2707. */
  2708. var KeyVisitor = /** @class */ (function () {
  2709. function KeyVisitor() {
  2710. this.visitWrappedNodeExpr = invalid;
  2711. this.visitWriteVarExpr = invalid;
  2712. this.visitWriteKeyExpr = invalid;
  2713. this.visitWritePropExpr = invalid;
  2714. this.visitInvokeMethodExpr = invalid;
  2715. this.visitInvokeFunctionExpr = invalid;
  2716. this.visitInstantiateExpr = invalid;
  2717. this.visitConditionalExpr = invalid;
  2718. this.visitNotExpr = invalid;
  2719. this.visitAssertNotNullExpr = invalid;
  2720. this.visitCastExpr = invalid;
  2721. this.visitFunctionExpr = invalid;
  2722. this.visitBinaryOperatorExpr = invalid;
  2723. this.visitReadPropExpr = invalid;
  2724. this.visitReadKeyExpr = invalid;
  2725. this.visitCommaExpr = invalid;
  2726. }
  2727. KeyVisitor.prototype.visitLiteralExpr = function (ast) {
  2728. return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value);
  2729. };
  2730. KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2731. var _this = this;
  2732. return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]";
  2733. };
  2734. KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2735. var _this = this;
  2736. var mapKey = function (entry) {
  2737. var quote = entry.quoted ? '"' : '';
  2738. return "" + quote + entry.key + quote;
  2739. };
  2740. var mapEntry = function (entry) {
  2741. return mapKey(entry) + ":" + entry.value.visitExpression(_this, context);
  2742. };
  2743. return "{" + ast.entries.map(mapEntry).join(',');
  2744. };
  2745. KeyVisitor.prototype.visitExternalExpr = function (ast) {
  2746. return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name :
  2747. "EX:" + ast.value.runtime.name;
  2748. };
  2749. KeyVisitor.prototype.visitReadVarExpr = function (node) { return "VAR:" + node.name; };
  2750. KeyVisitor.prototype.visitTypeofExpr = function (node, context) {
  2751. return "TYPEOF:" + node.expr.visitExpression(this, context);
  2752. };
  2753. return KeyVisitor;
  2754. }());
  2755. function invalid(arg) {
  2756. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  2757. }
  2758. function isVariable(e) {
  2759. return e instanceof ReadVarExpr;
  2760. }
  2761. /**
  2762. * @license
  2763. * Copyright Google Inc. All Rights Reserved.
  2764. *
  2765. * Use of this source code is governed by an MIT-style license that can be
  2766. * found in the LICENSE file at https://angular.io/license
  2767. */
  2768. var CORE = '@angular/core';
  2769. var Identifiers = /** @class */ (function () {
  2770. function Identifiers() {
  2771. }
  2772. Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
  2773. name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
  2774. moduleName: CORE,
  2775. };
  2776. Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE };
  2777. Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE };
  2778. Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE };
  2779. Identifiers.ChangeDetectorRef = {
  2780. name: 'ChangeDetectorRef',
  2781. moduleName: CORE,
  2782. };
  2783. Identifiers.QueryList = { name: 'QueryList', moduleName: CORE };
  2784. Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE };
  2785. Identifiers.Renderer2 = { name: 'Renderer2', moduleName: CORE };
  2786. Identifiers.CodegenComponentFactoryResolver = {
  2787. name: 'ɵCodegenComponentFactoryResolver',
  2788. moduleName: CORE,
  2789. };
  2790. Identifiers.ComponentFactoryResolver = {
  2791. name: 'ComponentFactoryResolver',
  2792. moduleName: CORE,
  2793. };
  2794. Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE };
  2795. Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE };
  2796. Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE };
  2797. Identifiers.createModuleFactory = {
  2798. name: 'ɵcmf',
  2799. moduleName: CORE,
  2800. };
  2801. Identifiers.moduleDef = {
  2802. name: 'ɵmod',
  2803. moduleName: CORE,
  2804. };
  2805. Identifiers.moduleProviderDef = {
  2806. name: 'ɵmpd',
  2807. moduleName: CORE,
  2808. };
  2809. Identifiers.RegisterModuleFactoryFn = {
  2810. name: 'ɵregisterModuleFactory',
  2811. moduleName: CORE,
  2812. };
  2813. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE };
  2814. Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
  2815. Identifiers.Injector = { name: 'Injector', moduleName: CORE };
  2816. Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
  2817. Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', moduleName: CORE };
  2818. Identifiers.ViewEncapsulation = {
  2819. name: 'ViewEncapsulation',
  2820. moduleName: CORE,
  2821. };
  2822. Identifiers.ChangeDetectionStrategy = {
  2823. name: 'ChangeDetectionStrategy',
  2824. moduleName: CORE,
  2825. };
  2826. Identifiers.SecurityContext = {
  2827. name: 'SecurityContext',
  2828. moduleName: CORE,
  2829. };
  2830. Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE };
  2831. Identifiers.TRANSLATIONS_FORMAT = {
  2832. name: 'TRANSLATIONS_FORMAT',
  2833. moduleName: CORE,
  2834. };
  2835. Identifiers.inlineInterpolate = {
  2836. name: 'ɵinlineInterpolate',
  2837. moduleName: CORE,
  2838. };
  2839. Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE };
  2840. Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE };
  2841. Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE };
  2842. Identifiers.Renderer = { name: 'Renderer', moduleName: CORE };
  2843. Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE };
  2844. Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE };
  2845. Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE };
  2846. Identifiers.textDef = { name: 'ɵted', moduleName: CORE };
  2847. Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE };
  2848. Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE };
  2849. Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE };
  2850. Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE };
  2851. Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE };
  2852. Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE };
  2853. Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE };
  2854. Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE };
  2855. Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE };
  2856. Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE };
  2857. Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE };
  2858. // type only
  2859. Identifiers.RendererType2 = {
  2860. name: 'RendererType2',
  2861. moduleName: CORE,
  2862. };
  2863. // type only
  2864. Identifiers.ViewDefinition = {
  2865. name: 'ɵViewDefinition',
  2866. moduleName: CORE,
  2867. };
  2868. Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE };
  2869. Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
  2870. return Identifiers;
  2871. }());
  2872. function createTokenForReference(reference) {
  2873. return { identifier: { reference: reference } };
  2874. }
  2875. function createTokenForExternalReference(reflector, reference) {
  2876. return createTokenForReference(reflector.resolveExternalReference(reference));
  2877. }
  2878. /**
  2879. * @license
  2880. * Copyright Google Inc. All Rights Reserved.
  2881. *
  2882. * Use of this source code is governed by an MIT-style license that can be
  2883. * found in the LICENSE file at https://angular.io/license
  2884. */
  2885. /**
  2886. * A token representing the a reference to a static type.
  2887. *
  2888. * This token is unique for a filePath and name and can be used as a hash table key.
  2889. */
  2890. var StaticSymbol = /** @class */ (function () {
  2891. function StaticSymbol(filePath, name, members) {
  2892. this.filePath = filePath;
  2893. this.name = name;
  2894. this.members = members;
  2895. }
  2896. StaticSymbol.prototype.assertNoMembers = function () {
  2897. if (this.members.length) {
  2898. throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + ".");
  2899. }
  2900. };
  2901. return StaticSymbol;
  2902. }());
  2903. /**
  2904. * A cache of static symbol used by the StaticReflector to return the same symbol for the
  2905. * same symbol values.
  2906. */
  2907. var StaticSymbolCache = /** @class */ (function () {
  2908. function StaticSymbolCache() {
  2909. this.cache = new Map();
  2910. }
  2911. StaticSymbolCache.prototype.get = function (declarationFile, name, members) {
  2912. members = members || [];
  2913. var memberSuffix = members.length ? "." + members.join('.') : '';
  2914. var key = "\"" + declarationFile + "\"." + name + memberSuffix;
  2915. var result = this.cache.get(key);
  2916. if (!result) {
  2917. result = new StaticSymbol(declarationFile, name, members);
  2918. this.cache.set(key, result);
  2919. }
  2920. return result;
  2921. };
  2922. return StaticSymbolCache;
  2923. }());
  2924. /**
  2925. * @license
  2926. * Copyright Google Inc. All Rights Reserved.
  2927. *
  2928. * Use of this source code is governed by an MIT-style license that can be
  2929. * found in the LICENSE file at https://angular.io/license
  2930. */
  2931. // group 0: "[prop] or (event) or @trigger"
  2932. // group 1: "prop" from "[prop]"
  2933. // group 2: "event" from "(event)"
  2934. // group 3: "@trigger" from "@trigger"
  2935. var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
  2936. function sanitizeIdentifier(name) {
  2937. return name.replace(/\W/g, '_');
  2938. }
  2939. var _anonymousTypeIndex = 0;
  2940. function identifierName(compileIdentifier) {
  2941. if (!compileIdentifier || !compileIdentifier.reference) {
  2942. return null;
  2943. }
  2944. var ref = compileIdentifier.reference;
  2945. if (ref instanceof StaticSymbol) {
  2946. return ref.name;
  2947. }
  2948. if (ref['__anonymousType']) {
  2949. return ref['__anonymousType'];
  2950. }
  2951. var identifier = stringify(ref);
  2952. if (identifier.indexOf('(') >= 0) {
  2953. // case: anonymous functions!
  2954. identifier = "anonymous_" + _anonymousTypeIndex++;
  2955. ref['__anonymousType'] = identifier;
  2956. }
  2957. else {
  2958. identifier = sanitizeIdentifier(identifier);
  2959. }
  2960. return identifier;
  2961. }
  2962. function identifierModuleUrl(compileIdentifier) {
  2963. var ref = compileIdentifier.reference;
  2964. if (ref instanceof StaticSymbol) {
  2965. return ref.filePath;
  2966. }
  2967. // Runtime type
  2968. return "./" + stringify(ref);
  2969. }
  2970. function viewClassName(compType, embeddedTemplateIndex) {
  2971. return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex;
  2972. }
  2973. function rendererTypeName(compType) {
  2974. return "RenderType_" + identifierName({ reference: compType });
  2975. }
  2976. function hostViewClassName(compType) {
  2977. return "HostView_" + identifierName({ reference: compType });
  2978. }
  2979. function componentFactoryName(compType) {
  2980. return identifierName({ reference: compType }) + "NgFactory";
  2981. }
  2982. var CompileSummaryKind;
  2983. (function (CompileSummaryKind) {
  2984. CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
  2985. CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
  2986. CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
  2987. CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
  2988. })(CompileSummaryKind || (CompileSummaryKind = {}));
  2989. function tokenName(token) {
  2990. return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
  2991. }
  2992. function tokenReference(token) {
  2993. if (token.identifier != null) {
  2994. return token.identifier.reference;
  2995. }
  2996. else {
  2997. return token.value;
  2998. }
  2999. }
  3000. /**
  3001. * Metadata about a stylesheet
  3002. */
  3003. var CompileStylesheetMetadata = /** @class */ (function () {
  3004. function CompileStylesheetMetadata(_a) {
  3005. var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls;
  3006. this.moduleUrl = moduleUrl || null;
  3007. this.styles = _normalizeArray(styles);
  3008. this.styleUrls = _normalizeArray(styleUrls);
  3009. }
  3010. return CompileStylesheetMetadata;
  3011. }());
  3012. /**
  3013. * Metadata regarding compilation of a template.
  3014. */
  3015. var CompileTemplateMetadata = /** @class */ (function () {
  3016. function CompileTemplateMetadata(_a) {
  3017. var encapsulation = _a.encapsulation, template = _a.template, templateUrl = _a.templateUrl, htmlAst = _a.htmlAst, styles = _a.styles, styleUrls = _a.styleUrls, externalStylesheets = _a.externalStylesheets, animations = _a.animations, ngContentSelectors = _a.ngContentSelectors, interpolation = _a.interpolation, isInline = _a.isInline, preserveWhitespaces = _a.preserveWhitespaces;
  3018. this.encapsulation = encapsulation;
  3019. this.template = template;
  3020. this.templateUrl = templateUrl;
  3021. this.htmlAst = htmlAst;
  3022. this.styles = _normalizeArray(styles);
  3023. this.styleUrls = _normalizeArray(styleUrls);
  3024. this.externalStylesheets = _normalizeArray(externalStylesheets);
  3025. this.animations = animations ? flatten(animations) : [];
  3026. this.ngContentSelectors = ngContentSelectors || [];
  3027. if (interpolation && interpolation.length != 2) {
  3028. throw new Error("'interpolation' should have a start and an end symbol.");
  3029. }
  3030. this.interpolation = interpolation;
  3031. this.isInline = isInline;
  3032. this.preserveWhitespaces = preserveWhitespaces;
  3033. }
  3034. CompileTemplateMetadata.prototype.toSummary = function () {
  3035. return {
  3036. ngContentSelectors: this.ngContentSelectors,
  3037. encapsulation: this.encapsulation,
  3038. styles: this.styles,
  3039. animations: this.animations
  3040. };
  3041. };
  3042. return CompileTemplateMetadata;
  3043. }());
  3044. /**
  3045. * Metadata regarding compilation of a directive.
  3046. */
  3047. var CompileDirectiveMetadata = /** @class */ (function () {
  3048. function CompileDirectiveMetadata(_a) {
  3049. var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, hostListeners = _a.hostListeners, hostProperties = _a.hostProperties, hostAttributes = _a.hostAttributes, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
  3050. this.isHost = !!isHost;
  3051. this.type = type;
  3052. this.isComponent = isComponent;
  3053. this.selector = selector;
  3054. this.exportAs = exportAs;
  3055. this.changeDetection = changeDetection;
  3056. this.inputs = inputs;
  3057. this.outputs = outputs;
  3058. this.hostListeners = hostListeners;
  3059. this.hostProperties = hostProperties;
  3060. this.hostAttributes = hostAttributes;
  3061. this.providers = _normalizeArray(providers);
  3062. this.viewProviders = _normalizeArray(viewProviders);
  3063. this.queries = _normalizeArray(queries);
  3064. this.guards = guards;
  3065. this.viewQueries = _normalizeArray(viewQueries);
  3066. this.entryComponents = _normalizeArray(entryComponents);
  3067. this.template = template;
  3068. this.componentViewType = componentViewType;
  3069. this.rendererType = rendererType;
  3070. this.componentFactory = componentFactory;
  3071. }
  3072. CompileDirectiveMetadata.create = function (_a) {
  3073. var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, host = _a.host, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
  3074. var hostListeners = {};
  3075. var hostProperties = {};
  3076. var hostAttributes = {};
  3077. if (host != null) {
  3078. Object.keys(host).forEach(function (key) {
  3079. var value = host[key];
  3080. var matches = key.match(HOST_REG_EXP);
  3081. if (matches === null) {
  3082. hostAttributes[key] = value;
  3083. }
  3084. else if (matches[1] != null) {
  3085. hostProperties[matches[1]] = value;
  3086. }
  3087. else if (matches[2] != null) {
  3088. hostListeners[matches[2]] = value;
  3089. }
  3090. });
  3091. }
  3092. var inputsMap = {};
  3093. if (inputs != null) {
  3094. inputs.forEach(function (bindConfig) {
  3095. // canonical syntax: `dirProp: elProp`
  3096. // if there is no `:`, use dirProp = elProp
  3097. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  3098. inputsMap[parts[0]] = parts[1];
  3099. });
  3100. }
  3101. var outputsMap = {};
  3102. if (outputs != null) {
  3103. outputs.forEach(function (bindConfig) {
  3104. // canonical syntax: `dirProp: elProp`
  3105. // if there is no `:`, use dirProp = elProp
  3106. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  3107. outputsMap[parts[0]] = parts[1];
  3108. });
  3109. }
  3110. return new CompileDirectiveMetadata({
  3111. isHost: isHost,
  3112. type: type,
  3113. isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection,
  3114. inputs: inputsMap,
  3115. outputs: outputsMap,
  3116. hostListeners: hostListeners,
  3117. hostProperties: hostProperties,
  3118. hostAttributes: hostAttributes,
  3119. providers: providers,
  3120. viewProviders: viewProviders,
  3121. queries: queries,
  3122. guards: guards,
  3123. viewQueries: viewQueries,
  3124. entryComponents: entryComponents,
  3125. template: template,
  3126. componentViewType: componentViewType,
  3127. rendererType: rendererType,
  3128. componentFactory: componentFactory,
  3129. });
  3130. };
  3131. CompileDirectiveMetadata.prototype.toSummary = function () {
  3132. return {
  3133. summaryKind: CompileSummaryKind.Directive,
  3134. type: this.type,
  3135. isComponent: this.isComponent,
  3136. selector: this.selector,
  3137. exportAs: this.exportAs,
  3138. inputs: this.inputs,
  3139. outputs: this.outputs,
  3140. hostListeners: this.hostListeners,
  3141. hostProperties: this.hostProperties,
  3142. hostAttributes: this.hostAttributes,
  3143. providers: this.providers,
  3144. viewProviders: this.viewProviders,
  3145. queries: this.queries,
  3146. guards: this.guards,
  3147. viewQueries: this.viewQueries,
  3148. entryComponents: this.entryComponents,
  3149. changeDetection: this.changeDetection,
  3150. template: this.template && this.template.toSummary(),
  3151. componentViewType: this.componentViewType,
  3152. rendererType: this.rendererType,
  3153. componentFactory: this.componentFactory
  3154. };
  3155. };
  3156. return CompileDirectiveMetadata;
  3157. }());
  3158. var CompilePipeMetadata = /** @class */ (function () {
  3159. function CompilePipeMetadata(_a) {
  3160. var type = _a.type, name = _a.name, pure = _a.pure;
  3161. this.type = type;
  3162. this.name = name;
  3163. this.pure = !!pure;
  3164. }
  3165. CompilePipeMetadata.prototype.toSummary = function () {
  3166. return {
  3167. summaryKind: CompileSummaryKind.Pipe,
  3168. type: this.type,
  3169. name: this.name,
  3170. pure: this.pure
  3171. };
  3172. };
  3173. return CompilePipeMetadata;
  3174. }());
  3175. var CompileShallowModuleMetadata = /** @class */ (function () {
  3176. function CompileShallowModuleMetadata() {
  3177. }
  3178. return CompileShallowModuleMetadata;
  3179. }());
  3180. /**
  3181. * Metadata regarding compilation of a module.
  3182. */
  3183. var CompileNgModuleMetadata = /** @class */ (function () {
  3184. function CompileNgModuleMetadata(_a) {
  3185. var type = _a.type, providers = _a.providers, declaredDirectives = _a.declaredDirectives, exportedDirectives = _a.exportedDirectives, declaredPipes = _a.declaredPipes, exportedPipes = _a.exportedPipes, entryComponents = _a.entryComponents, bootstrapComponents = _a.bootstrapComponents, importedModules = _a.importedModules, exportedModules = _a.exportedModules, schemas = _a.schemas, transitiveModule = _a.transitiveModule, id = _a.id;
  3186. this.type = type || null;
  3187. this.declaredDirectives = _normalizeArray(declaredDirectives);
  3188. this.exportedDirectives = _normalizeArray(exportedDirectives);
  3189. this.declaredPipes = _normalizeArray(declaredPipes);
  3190. this.exportedPipes = _normalizeArray(exportedPipes);
  3191. this.providers = _normalizeArray(providers);
  3192. this.entryComponents = _normalizeArray(entryComponents);
  3193. this.bootstrapComponents = _normalizeArray(bootstrapComponents);
  3194. this.importedModules = _normalizeArray(importedModules);
  3195. this.exportedModules = _normalizeArray(exportedModules);
  3196. this.schemas = _normalizeArray(schemas);
  3197. this.id = id || null;
  3198. this.transitiveModule = transitiveModule || null;
  3199. }
  3200. CompileNgModuleMetadata.prototype.toSummary = function () {
  3201. var module = this.transitiveModule;
  3202. return {
  3203. summaryKind: CompileSummaryKind.NgModule,
  3204. type: this.type,
  3205. entryComponents: module.entryComponents,
  3206. providers: module.providers,
  3207. modules: module.modules,
  3208. exportedDirectives: module.exportedDirectives,
  3209. exportedPipes: module.exportedPipes
  3210. };
  3211. };
  3212. return CompileNgModuleMetadata;
  3213. }());
  3214. var TransitiveCompileNgModuleMetadata = /** @class */ (function () {
  3215. function TransitiveCompileNgModuleMetadata() {
  3216. this.directivesSet = new Set();
  3217. this.directives = [];
  3218. this.exportedDirectivesSet = new Set();
  3219. this.exportedDirectives = [];
  3220. this.pipesSet = new Set();
  3221. this.pipes = [];
  3222. this.exportedPipesSet = new Set();
  3223. this.exportedPipes = [];
  3224. this.modulesSet = new Set();
  3225. this.modules = [];
  3226. this.entryComponentsSet = new Set();
  3227. this.entryComponents = [];
  3228. this.providers = [];
  3229. }
  3230. TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) {
  3231. this.providers.push({ provider: provider, module: module });
  3232. };
  3233. TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) {
  3234. if (!this.directivesSet.has(id.reference)) {
  3235. this.directivesSet.add(id.reference);
  3236. this.directives.push(id);
  3237. }
  3238. };
  3239. TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) {
  3240. if (!this.exportedDirectivesSet.has(id.reference)) {
  3241. this.exportedDirectivesSet.add(id.reference);
  3242. this.exportedDirectives.push(id);
  3243. }
  3244. };
  3245. TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) {
  3246. if (!this.pipesSet.has(id.reference)) {
  3247. this.pipesSet.add(id.reference);
  3248. this.pipes.push(id);
  3249. }
  3250. };
  3251. TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) {
  3252. if (!this.exportedPipesSet.has(id.reference)) {
  3253. this.exportedPipesSet.add(id.reference);
  3254. this.exportedPipes.push(id);
  3255. }
  3256. };
  3257. TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) {
  3258. if (!this.modulesSet.has(id.reference)) {
  3259. this.modulesSet.add(id.reference);
  3260. this.modules.push(id);
  3261. }
  3262. };
  3263. TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) {
  3264. if (!this.entryComponentsSet.has(ec.componentType)) {
  3265. this.entryComponentsSet.add(ec.componentType);
  3266. this.entryComponents.push(ec);
  3267. }
  3268. };
  3269. return TransitiveCompileNgModuleMetadata;
  3270. }());
  3271. function _normalizeArray(obj) {
  3272. return obj || [];
  3273. }
  3274. var ProviderMeta = /** @class */ (function () {
  3275. function ProviderMeta(token, _a) {
  3276. var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
  3277. this.token = token;
  3278. this.useClass = useClass || null;
  3279. this.useValue = useValue;
  3280. this.useExisting = useExisting;
  3281. this.useFactory = useFactory || null;
  3282. this.dependencies = deps || null;
  3283. this.multi = !!multi;
  3284. }
  3285. return ProviderMeta;
  3286. }());
  3287. function flatten(list) {
  3288. return list.reduce(function (flat, item) {
  3289. var flatItem = Array.isArray(item) ? flatten(item) : item;
  3290. return flat.concat(flatItem);
  3291. }, []);
  3292. }
  3293. function jitSourceUrl(url) {
  3294. // Note: We need 3 "/" so that ng shows up as a separate domain
  3295. // in the chrome dev tools.
  3296. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
  3297. }
  3298. function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
  3299. var url;
  3300. if (templateMeta.isInline) {
  3301. if (compMeta.type.reference instanceof StaticSymbol) {
  3302. // Note: a .ts file might contain multiple components with inline templates,
  3303. // so we need to give them unique urls, as these will be used for sourcemaps.
  3304. url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html";
  3305. }
  3306. else {
  3307. url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html";
  3308. }
  3309. }
  3310. else {
  3311. url = templateMeta.templateUrl;
  3312. }
  3313. return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
  3314. }
  3315. function sharedStylesheetJitUrl(meta, id) {
  3316. var pathParts = meta.moduleUrl.split(/\/\\/g);
  3317. var baseName = pathParts[pathParts.length - 1];
  3318. return jitSourceUrl("css/" + id + baseName + ".ngstyle.js");
  3319. }
  3320. function ngModuleJitUrl(moduleMeta) {
  3321. return jitSourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js");
  3322. }
  3323. function templateJitUrl(ngModuleType, compMeta) {
  3324. return jitSourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js");
  3325. }
  3326. /**
  3327. * @license
  3328. * Copyright Google Inc. All Rights Reserved.
  3329. *
  3330. * Use of this source code is governed by an MIT-style license that can be
  3331. * found in the LICENSE file at https://angular.io/license
  3332. */
  3333. var CORE$1 = '@angular/core';
  3334. var Identifiers$1 = /** @class */ (function () {
  3335. function Identifiers() {
  3336. }
  3337. /* Methods */
  3338. Identifiers.NEW_METHOD = 'factory';
  3339. Identifiers.TRANSFORM_METHOD = 'transform';
  3340. Identifiers.PATCH_DEPS = 'patchedDeps';
  3341. /* Instructions */
  3342. Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 };
  3343. Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 };
  3344. Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 };
  3345. Identifiers.element = { name: 'ɵɵelement', moduleName: CORE$1 };
  3346. Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 };
  3347. Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 };
  3348. Identifiers.select = { name: 'ɵɵselect', moduleName: CORE$1 };
  3349. Identifiers.updateSyntheticHostBinding = { name: 'ɵɵupdateSyntheticHostBinding', moduleName: CORE$1 };
  3350. Identifiers.componentHostSyntheticListener = { name: 'ɵɵcomponentHostSyntheticListener', moduleName: CORE$1 };
  3351. Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 };
  3352. Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 };
  3353. Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 };
  3354. Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 };
  3355. Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 };
  3356. Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 };
  3357. Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 };
  3358. Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 };
  3359. Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 };
  3360. Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 };
  3361. Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 };
  3362. Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 };
  3363. Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 };
  3364. Identifiers.styling = { name: 'ɵɵstyling', moduleName: CORE$1 };
  3365. Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 };
  3366. Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 };
  3367. Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 };
  3368. Identifiers.stylingApply = { name: 'ɵɵstylingApply', moduleName: CORE$1 };
  3369. Identifiers.styleSanitizer = { name: 'ɵɵstyleSanitizer', moduleName: CORE$1 };
  3370. Identifiers.elementHostAttrs = { name: 'ɵɵelementHostAttrs', moduleName: CORE$1 };
  3371. Identifiers.containerCreate = { name: 'ɵɵcontainer', moduleName: CORE$1 };
  3372. Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 };
  3373. Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 };
  3374. Identifiers.text = { name: 'ɵɵtext', moduleName: CORE$1 };
  3375. Identifiers.textBinding = { name: 'ɵɵtextBinding', moduleName: CORE$1 };
  3376. Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 };
  3377. Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 };
  3378. Identifiers.allocHostVars = { name: 'ɵɵallocHostVars', moduleName: CORE$1 };
  3379. Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 };
  3380. Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 };
  3381. Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 };
  3382. Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 };
  3383. Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 };
  3384. Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 };
  3385. Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 };
  3386. Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 };
  3387. Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 };
  3388. Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 };
  3389. Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 };
  3390. Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 };
  3391. Identifiers.interpolation1 = { name: 'ɵɵinterpolation1', moduleName: CORE$1 };
  3392. Identifiers.interpolation2 = { name: 'ɵɵinterpolation2', moduleName: CORE$1 };
  3393. Identifiers.interpolation3 = { name: 'ɵɵinterpolation3', moduleName: CORE$1 };
  3394. Identifiers.interpolation4 = { name: 'ɵɵinterpolation4', moduleName: CORE$1 };
  3395. Identifiers.interpolation5 = { name: 'ɵɵinterpolation5', moduleName: CORE$1 };
  3396. Identifiers.interpolation6 = { name: 'ɵɵinterpolation6', moduleName: CORE$1 };
  3397. Identifiers.interpolation7 = { name: 'ɵɵinterpolation7', moduleName: CORE$1 };
  3398. Identifiers.interpolation8 = { name: 'ɵɵinterpolation8', moduleName: CORE$1 };
  3399. Identifiers.interpolationV = { name: 'ɵɵinterpolationV', moduleName: CORE$1 };
  3400. Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 };
  3401. Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 };
  3402. Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 };
  3403. Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 };
  3404. Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 };
  3405. Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 };
  3406. Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 };
  3407. Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 };
  3408. Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 };
  3409. Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 };
  3410. Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 };
  3411. Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 };
  3412. Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 };
  3413. Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 };
  3414. Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 };
  3415. Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE$1 };
  3416. Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 };
  3417. Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 };
  3418. Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 };
  3419. Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 };
  3420. Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 };
  3421. Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 };
  3422. Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 };
  3423. Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 };
  3424. Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 };
  3425. Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 };
  3426. Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 };
  3427. Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 };
  3428. Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 };
  3429. Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 };
  3430. Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 };
  3431. Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 };
  3432. Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 };
  3433. Identifiers.i18nLocalize = { name: 'ɵɵi18nLocalize', moduleName: CORE$1 };
  3434. Identifiers.load = { name: 'ɵɵload', moduleName: CORE$1 };
  3435. Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 };
  3436. Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE$1 };
  3437. Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 };
  3438. Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE$1 };
  3439. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
  3440. Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 };
  3441. Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
  3442. Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 };
  3443. Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 };
  3444. Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 };
  3445. Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 };
  3446. Identifiers.defineBase = { name: 'ɵɵdefineBase', moduleName: CORE$1 };
  3447. Identifiers.BaseDef = {
  3448. name: 'ɵɵBaseDef',
  3449. moduleName: CORE$1,
  3450. };
  3451. Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 };
  3452. Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 };
  3453. Identifiers.ComponentDefWithMeta = {
  3454. name: 'ɵɵComponentDefWithMeta',
  3455. moduleName: CORE$1,
  3456. };
  3457. Identifiers.defineDirective = {
  3458. name: 'ɵɵdefineDirective',
  3459. moduleName: CORE$1,
  3460. };
  3461. Identifiers.DirectiveDefWithMeta = {
  3462. name: 'ɵɵDirectiveDefWithMeta',
  3463. moduleName: CORE$1,
  3464. };
  3465. Identifiers.InjectorDef = {
  3466. name: 'ɵɵInjectorDef',
  3467. moduleName: CORE$1,
  3468. };
  3469. Identifiers.defineInjector = {
  3470. name: 'ɵɵdefineInjector',
  3471. moduleName: CORE$1,
  3472. };
  3473. Identifiers.NgModuleDefWithMeta = {
  3474. name: 'ɵɵNgModuleDefWithMeta',
  3475. moduleName: CORE$1,
  3476. };
  3477. Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 };
  3478. Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 };
  3479. Identifiers.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 };
  3480. Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 };
  3481. Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 };
  3482. Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 };
  3483. Identifiers.staticViewQuery = { name: 'ɵɵstaticViewQuery', moduleName: CORE$1 };
  3484. Identifiers.staticContentQuery = { name: 'ɵɵstaticContentQuery', moduleName: CORE$1 };
  3485. Identifiers.loadViewQuery = { name: 'ɵɵloadViewQuery', moduleName: CORE$1 };
  3486. Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 };
  3487. Identifiers.loadContentQuery = { name: 'ɵɵloadContentQuery', moduleName: CORE$1 };
  3488. Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 };
  3489. Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 };
  3490. Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 };
  3491. Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE$1 };
  3492. Identifiers.getFactoryOf = {
  3493. name: 'ɵɵgetFactoryOf',
  3494. moduleName: CORE$1,
  3495. };
  3496. Identifiers.getInheritedFactory = {
  3497. name: 'ɵɵgetInheritedFactory',
  3498. moduleName: CORE$1,
  3499. };
  3500. // sanitization-related functions
  3501. Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 };
  3502. Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 };
  3503. Identifiers.defaultStyleSanitizer = { name: 'ɵɵdefaultStyleSanitizer', moduleName: CORE$1 };
  3504. Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 };
  3505. Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 };
  3506. Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 };
  3507. Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 };
  3508. return Identifiers;
  3509. }());
  3510. /**
  3511. * @license
  3512. * Copyright Google Inc. All Rights Reserved.
  3513. *
  3514. * Use of this source code is governed by an MIT-style license that can be
  3515. * found in the LICENSE file at https://angular.io/license
  3516. */
  3517. var $EOF = 0;
  3518. var $BSPACE = 8;
  3519. var $TAB = 9;
  3520. var $LF = 10;
  3521. var $VTAB = 11;
  3522. var $FF = 12;
  3523. var $CR = 13;
  3524. var $SPACE = 32;
  3525. var $BANG = 33;
  3526. var $DQ = 34;
  3527. var $HASH = 35;
  3528. var $$ = 36;
  3529. var $PERCENT = 37;
  3530. var $AMPERSAND = 38;
  3531. var $SQ = 39;
  3532. var $LPAREN = 40;
  3533. var $RPAREN = 41;
  3534. var $STAR = 42;
  3535. var $PLUS = 43;
  3536. var $COMMA = 44;
  3537. var $MINUS = 45;
  3538. var $PERIOD = 46;
  3539. var $SLASH = 47;
  3540. var $COLON = 58;
  3541. var $SEMICOLON = 59;
  3542. var $LT = 60;
  3543. var $EQ = 61;
  3544. var $GT = 62;
  3545. var $QUESTION = 63;
  3546. var $0 = 48;
  3547. var $7 = 55;
  3548. var $9 = 57;
  3549. var $A = 65;
  3550. var $E = 69;
  3551. var $F = 70;
  3552. var $X = 88;
  3553. var $Z = 90;
  3554. var $LBRACKET = 91;
  3555. var $BACKSLASH = 92;
  3556. var $RBRACKET = 93;
  3557. var $CARET = 94;
  3558. var $_ = 95;
  3559. var $a = 97;
  3560. var $b = 98;
  3561. var $e = 101;
  3562. var $f = 102;
  3563. var $n = 110;
  3564. var $r = 114;
  3565. var $t = 116;
  3566. var $u = 117;
  3567. var $v = 118;
  3568. var $x = 120;
  3569. var $z = 122;
  3570. var $LBRACE = 123;
  3571. var $BAR = 124;
  3572. var $RBRACE = 125;
  3573. var $NBSP = 160;
  3574. var $BT = 96;
  3575. function isWhitespace(code) {
  3576. return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
  3577. }
  3578. function isDigit(code) {
  3579. return $0 <= code && code <= $9;
  3580. }
  3581. function isAsciiLetter(code) {
  3582. return code >= $a && code <= $z || code >= $A && code <= $Z;
  3583. }
  3584. function isAsciiHexDigit(code) {
  3585. return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
  3586. }
  3587. function isNewLine(code) {
  3588. return code === $LF || code === $CR;
  3589. }
  3590. function isOctalDigit(code) {
  3591. return $0 <= code && code <= $7;
  3592. }
  3593. /**
  3594. * @license
  3595. * Copyright Google Inc. All Rights Reserved.
  3596. *
  3597. * Use of this source code is governed by an MIT-style license that can be
  3598. * found in the LICENSE file at https://angular.io/license
  3599. */
  3600. var ParseLocation = /** @class */ (function () {
  3601. function ParseLocation(file, offset, line, col) {
  3602. this.file = file;
  3603. this.offset = offset;
  3604. this.line = line;
  3605. this.col = col;
  3606. }
  3607. ParseLocation.prototype.toString = function () {
  3608. return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url;
  3609. };
  3610. ParseLocation.prototype.moveBy = function (delta) {
  3611. var source = this.file.content;
  3612. var len = source.length;
  3613. var offset = this.offset;
  3614. var line = this.line;
  3615. var col = this.col;
  3616. while (offset > 0 && delta < 0) {
  3617. offset--;
  3618. delta++;
  3619. var ch = source.charCodeAt(offset);
  3620. if (ch == $LF) {
  3621. line--;
  3622. var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
  3623. col = priorLine > 0 ? offset - priorLine : offset;
  3624. }
  3625. else {
  3626. col--;
  3627. }
  3628. }
  3629. while (offset < len && delta > 0) {
  3630. var ch = source.charCodeAt(offset);
  3631. offset++;
  3632. delta--;
  3633. if (ch == $LF) {
  3634. line++;
  3635. col = 0;
  3636. }
  3637. else {
  3638. col++;
  3639. }
  3640. }
  3641. return new ParseLocation(this.file, offset, line, col);
  3642. };
  3643. // Return the source around the location
  3644. // Up to `maxChars` or `maxLines` on each side of the location
  3645. ParseLocation.prototype.getContext = function (maxChars, maxLines) {
  3646. var content = this.file.content;
  3647. var startOffset = this.offset;
  3648. if (startOffset != null) {
  3649. if (startOffset > content.length - 1) {
  3650. startOffset = content.length - 1;
  3651. }
  3652. var endOffset = startOffset;
  3653. var ctxChars = 0;
  3654. var ctxLines = 0;
  3655. while (ctxChars < maxChars && startOffset > 0) {
  3656. startOffset--;
  3657. ctxChars++;
  3658. if (content[startOffset] == '\n') {
  3659. if (++ctxLines == maxLines) {
  3660. break;
  3661. }
  3662. }
  3663. }
  3664. ctxChars = 0;
  3665. ctxLines = 0;
  3666. while (ctxChars < maxChars && endOffset < content.length - 1) {
  3667. endOffset++;
  3668. ctxChars++;
  3669. if (content[endOffset] == '\n') {
  3670. if (++ctxLines == maxLines) {
  3671. break;
  3672. }
  3673. }
  3674. }
  3675. return {
  3676. before: content.substring(startOffset, this.offset),
  3677. after: content.substring(this.offset, endOffset + 1),
  3678. };
  3679. }
  3680. return null;
  3681. };
  3682. return ParseLocation;
  3683. }());
  3684. var ParseSourceFile = /** @class */ (function () {
  3685. function ParseSourceFile(content, url) {
  3686. this.content = content;
  3687. this.url = url;
  3688. }
  3689. return ParseSourceFile;
  3690. }());
  3691. var ParseSourceSpan = /** @class */ (function () {
  3692. function ParseSourceSpan(start, end, details) {
  3693. if (details === void 0) { details = null; }
  3694. this.start = start;
  3695. this.end = end;
  3696. this.details = details;
  3697. }
  3698. ParseSourceSpan.prototype.toString = function () {
  3699. return this.start.file.content.substring(this.start.offset, this.end.offset);
  3700. };
  3701. return ParseSourceSpan;
  3702. }());
  3703. var ParseErrorLevel;
  3704. (function (ParseErrorLevel) {
  3705. ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
  3706. ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
  3707. })(ParseErrorLevel || (ParseErrorLevel = {}));
  3708. var ParseError = /** @class */ (function () {
  3709. function ParseError(span, msg, level) {
  3710. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  3711. this.span = span;
  3712. this.msg = msg;
  3713. this.level = level;
  3714. }
  3715. ParseError.prototype.contextualMessage = function () {
  3716. var ctx = this.span.start.getContext(100, 3);
  3717. return ctx ? this.msg + " (\"" + ctx.before + "[" + ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" :
  3718. this.msg;
  3719. };
  3720. ParseError.prototype.toString = function () {
  3721. var details = this.span.details ? ", " + this.span.details : '';
  3722. return this.contextualMessage() + ": " + this.span.start + details;
  3723. };
  3724. return ParseError;
  3725. }());
  3726. function typeSourceSpan(kind, type) {
  3727. var moduleUrl = identifierModuleUrl(type);
  3728. var sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl :
  3729. "in " + kind + " " + identifierName(type);
  3730. var sourceFile = new ParseSourceFile('', sourceFileName);
  3731. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3732. }
  3733. /**
  3734. * Generates Source Span object for a given R3 Type for JIT mode.
  3735. *
  3736. * @param kind Component or Directive.
  3737. * @param typeName name of the Component or Directive.
  3738. * @param sourceUrl reference to Component or Directive source.
  3739. * @returns instance of ParseSourceSpan that represent a given Component or Directive.
  3740. */
  3741. function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
  3742. var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl;
  3743. var sourceFile = new ParseSourceFile('', sourceFileName);
  3744. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3745. }
  3746. /**
  3747. * @license
  3748. * Copyright Google Inc. All Rights Reserved.
  3749. *
  3750. * Use of this source code is governed by an MIT-style license that can be
  3751. * found in the LICENSE file at https://angular.io/license
  3752. */
  3753. var Text = /** @class */ (function () {
  3754. function Text(value, sourceSpan) {
  3755. this.value = value;
  3756. this.sourceSpan = sourceSpan;
  3757. }
  3758. Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
  3759. return Text;
  3760. }());
  3761. var BoundText = /** @class */ (function () {
  3762. function BoundText(value, sourceSpan, i18n) {
  3763. this.value = value;
  3764. this.sourceSpan = sourceSpan;
  3765. this.i18n = i18n;
  3766. }
  3767. BoundText.prototype.visit = function (visitor) { return visitor.visitBoundText(this); };
  3768. return BoundText;
  3769. }());
  3770. var TextAttribute = /** @class */ (function () {
  3771. function TextAttribute(name, value, sourceSpan, valueSpan, i18n) {
  3772. this.name = name;
  3773. this.value = value;
  3774. this.sourceSpan = sourceSpan;
  3775. this.valueSpan = valueSpan;
  3776. this.i18n = i18n;
  3777. }
  3778. TextAttribute.prototype.visit = function (visitor) { return visitor.visitTextAttribute(this); };
  3779. return TextAttribute;
  3780. }());
  3781. var BoundAttribute = /** @class */ (function () {
  3782. function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, i18n) {
  3783. this.name = name;
  3784. this.type = type;
  3785. this.securityContext = securityContext;
  3786. this.value = value;
  3787. this.unit = unit;
  3788. this.sourceSpan = sourceSpan;
  3789. this.i18n = i18n;
  3790. }
  3791. BoundAttribute.fromBoundElementProperty = function (prop, i18n) {
  3792. return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, i18n);
  3793. };
  3794. BoundAttribute.prototype.visit = function (visitor) { return visitor.visitBoundAttribute(this); };
  3795. return BoundAttribute;
  3796. }());
  3797. var BoundEvent = /** @class */ (function () {
  3798. function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan) {
  3799. this.name = name;
  3800. this.type = type;
  3801. this.handler = handler;
  3802. this.target = target;
  3803. this.phase = phase;
  3804. this.sourceSpan = sourceSpan;
  3805. this.handlerSpan = handlerSpan;
  3806. }
  3807. BoundEvent.fromParsedEvent = function (event) {
  3808. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  3809. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  3810. return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan);
  3811. };
  3812. BoundEvent.prototype.visit = function (visitor) { return visitor.visitBoundEvent(this); };
  3813. return BoundEvent;
  3814. }());
  3815. var Element = /** @class */ (function () {
  3816. function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3817. this.name = name;
  3818. this.attributes = attributes;
  3819. this.inputs = inputs;
  3820. this.outputs = outputs;
  3821. this.children = children;
  3822. this.references = references;
  3823. this.sourceSpan = sourceSpan;
  3824. this.startSourceSpan = startSourceSpan;
  3825. this.endSourceSpan = endSourceSpan;
  3826. this.i18n = i18n;
  3827. // If the element is empty then the source span should include any closing tag
  3828. if (children.length === 0 && startSourceSpan && endSourceSpan) {
  3829. this.sourceSpan = new ParseSourceSpan(sourceSpan.start, endSourceSpan.end);
  3830. }
  3831. }
  3832. Element.prototype.visit = function (visitor) { return visitor.visitElement(this); };
  3833. return Element;
  3834. }());
  3835. var Template = /** @class */ (function () {
  3836. function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3837. this.tagName = tagName;
  3838. this.attributes = attributes;
  3839. this.inputs = inputs;
  3840. this.outputs = outputs;
  3841. this.templateAttrs = templateAttrs;
  3842. this.children = children;
  3843. this.references = references;
  3844. this.variables = variables;
  3845. this.sourceSpan = sourceSpan;
  3846. this.startSourceSpan = startSourceSpan;
  3847. this.endSourceSpan = endSourceSpan;
  3848. this.i18n = i18n;
  3849. }
  3850. Template.prototype.visit = function (visitor) { return visitor.visitTemplate(this); };
  3851. return Template;
  3852. }());
  3853. var Content = /** @class */ (function () {
  3854. function Content(selector, attributes, sourceSpan, i18n) {
  3855. this.selector = selector;
  3856. this.attributes = attributes;
  3857. this.sourceSpan = sourceSpan;
  3858. this.i18n = i18n;
  3859. }
  3860. Content.prototype.visit = function (visitor) { return visitor.visitContent(this); };
  3861. return Content;
  3862. }());
  3863. var Variable = /** @class */ (function () {
  3864. function Variable(name, value, sourceSpan) {
  3865. this.name = name;
  3866. this.value = value;
  3867. this.sourceSpan = sourceSpan;
  3868. }
  3869. Variable.prototype.visit = function (visitor) { return visitor.visitVariable(this); };
  3870. return Variable;
  3871. }());
  3872. var Reference = /** @class */ (function () {
  3873. function Reference(name, value, sourceSpan) {
  3874. this.name = name;
  3875. this.value = value;
  3876. this.sourceSpan = sourceSpan;
  3877. }
  3878. Reference.prototype.visit = function (visitor) { return visitor.visitReference(this); };
  3879. return Reference;
  3880. }());
  3881. var Icu = /** @class */ (function () {
  3882. function Icu(vars, placeholders, sourceSpan, i18n) {
  3883. this.vars = vars;
  3884. this.placeholders = placeholders;
  3885. this.sourceSpan = sourceSpan;
  3886. this.i18n = i18n;
  3887. }
  3888. Icu.prototype.visit = function (visitor) { return visitor.visitIcu(this); };
  3889. return Icu;
  3890. }());
  3891. function visitAll(visitor, nodes) {
  3892. var e_1, _a, e_2, _b;
  3893. var result = [];
  3894. if (visitor.visit) {
  3895. try {
  3896. for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
  3897. var node = nodes_1_1.value;
  3898. var newNode = visitor.visit(node) || node.visit(visitor);
  3899. }
  3900. }
  3901. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  3902. finally {
  3903. try {
  3904. if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1);
  3905. }
  3906. finally { if (e_1) throw e_1.error; }
  3907. }
  3908. }
  3909. else {
  3910. try {
  3911. for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) {
  3912. var node = nodes_2_1.value;
  3913. var newNode = node.visit(visitor);
  3914. if (newNode) {
  3915. result.push(newNode);
  3916. }
  3917. }
  3918. }
  3919. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  3920. finally {
  3921. try {
  3922. if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2);
  3923. }
  3924. finally { if (e_2) throw e_2.error; }
  3925. }
  3926. }
  3927. return result;
  3928. }
  3929. /**
  3930. * @license
  3931. * Copyright Google Inc. All Rights Reserved.
  3932. *
  3933. * Use of this source code is governed by an MIT-style license that can be
  3934. * found in the LICENSE file at https://angular.io/license
  3935. */
  3936. var Message = /** @class */ (function () {
  3937. /**
  3938. * @param nodes message AST
  3939. * @param placeholders maps placeholder names to static content
  3940. * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
  3941. * @param meaning
  3942. * @param description
  3943. * @param id
  3944. */
  3945. function Message(nodes, placeholders, placeholderToMessage, meaning, description, id) {
  3946. this.nodes = nodes;
  3947. this.placeholders = placeholders;
  3948. this.placeholderToMessage = placeholderToMessage;
  3949. this.meaning = meaning;
  3950. this.description = description;
  3951. this.id = id;
  3952. if (nodes.length) {
  3953. this.sources = [{
  3954. filePath: nodes[0].sourceSpan.start.file.url,
  3955. startLine: nodes[0].sourceSpan.start.line + 1,
  3956. startCol: nodes[0].sourceSpan.start.col + 1,
  3957. endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
  3958. endCol: nodes[0].sourceSpan.start.col + 1
  3959. }];
  3960. }
  3961. else {
  3962. this.sources = [];
  3963. }
  3964. }
  3965. return Message;
  3966. }());
  3967. var Text$1 = /** @class */ (function () {
  3968. function Text(value, sourceSpan) {
  3969. this.value = value;
  3970. this.sourceSpan = sourceSpan;
  3971. }
  3972. Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  3973. return Text;
  3974. }());
  3975. // TODO(vicb): do we really need this node (vs an array) ?
  3976. var Container = /** @class */ (function () {
  3977. function Container(children, sourceSpan) {
  3978. this.children = children;
  3979. this.sourceSpan = sourceSpan;
  3980. }
  3981. Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); };
  3982. return Container;
  3983. }());
  3984. var Icu$1 = /** @class */ (function () {
  3985. function Icu(expression, type, cases, sourceSpan) {
  3986. this.expression = expression;
  3987. this.type = type;
  3988. this.cases = cases;
  3989. this.sourceSpan = sourceSpan;
  3990. }
  3991. Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); };
  3992. return Icu;
  3993. }());
  3994. var TagPlaceholder = /** @class */ (function () {
  3995. function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, sourceSpan) {
  3996. this.tag = tag;
  3997. this.attrs = attrs;
  3998. this.startName = startName;
  3999. this.closeName = closeName;
  4000. this.children = children;
  4001. this.isVoid = isVoid;
  4002. this.sourceSpan = sourceSpan;
  4003. }
  4004. TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); };
  4005. return TagPlaceholder;
  4006. }());
  4007. var Placeholder = /** @class */ (function () {
  4008. function Placeholder(value, name, sourceSpan) {
  4009. this.value = value;
  4010. this.name = name;
  4011. this.sourceSpan = sourceSpan;
  4012. }
  4013. Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); };
  4014. return Placeholder;
  4015. }());
  4016. var IcuPlaceholder = /** @class */ (function () {
  4017. function IcuPlaceholder(value, name, sourceSpan) {
  4018. this.value = value;
  4019. this.name = name;
  4020. this.sourceSpan = sourceSpan;
  4021. }
  4022. IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); };
  4023. return IcuPlaceholder;
  4024. }());
  4025. // Clone the AST
  4026. var CloneVisitor = /** @class */ (function () {
  4027. function CloneVisitor() {
  4028. }
  4029. CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  4030. CloneVisitor.prototype.visitContainer = function (container, context) {
  4031. var _this = this;
  4032. var children = container.children.map(function (n) { return n.visit(_this, context); });
  4033. return new Container(children, container.sourceSpan);
  4034. };
  4035. CloneVisitor.prototype.visitIcu = function (icu, context) {
  4036. var _this = this;
  4037. var cases = {};
  4038. Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); });
  4039. var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
  4040. msg.expressionPlaceholder = icu.expressionPlaceholder;
  4041. return msg;
  4042. };
  4043. CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4044. var _this = this;
  4045. var children = ph.children.map(function (n) { return n.visit(_this, context); });
  4046. return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan);
  4047. };
  4048. CloneVisitor.prototype.visitPlaceholder = function (ph, context) {
  4049. return new Placeholder(ph.value, ph.name, ph.sourceSpan);
  4050. };
  4051. CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4052. return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
  4053. };
  4054. return CloneVisitor;
  4055. }());
  4056. // Visit all the nodes recursively
  4057. var RecurseVisitor = /** @class */ (function () {
  4058. function RecurseVisitor() {
  4059. }
  4060. RecurseVisitor.prototype.visitText = function (text, context) { };
  4061. RecurseVisitor.prototype.visitContainer = function (container, context) {
  4062. var _this = this;
  4063. container.children.forEach(function (child) { return child.visit(_this); });
  4064. };
  4065. RecurseVisitor.prototype.visitIcu = function (icu, context) {
  4066. var _this = this;
  4067. Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); });
  4068. };
  4069. RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4070. var _this = this;
  4071. ph.children.forEach(function (child) { return child.visit(_this); });
  4072. };
  4073. RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { };
  4074. RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { };
  4075. return RecurseVisitor;
  4076. }());
  4077. /**
  4078. * @license
  4079. * Copyright Google Inc. All Rights Reserved.
  4080. *
  4081. * Use of this source code is governed by an MIT-style license that can be
  4082. * found in the LICENSE file at https://angular.io/license
  4083. */
  4084. function digest(message) {
  4085. return message.id || sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
  4086. }
  4087. function decimalDigest(message) {
  4088. if (message.id) {
  4089. return message.id;
  4090. }
  4091. var visitor = new _SerializerIgnoreIcuExpVisitor();
  4092. var parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
  4093. return computeMsgId(parts.join(''), message.meaning);
  4094. }
  4095. /**
  4096. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4097. *
  4098. * The visitor is also used in the i18n parser tests
  4099. *
  4100. * @internal
  4101. */
  4102. var _SerializerVisitor = /** @class */ (function () {
  4103. function _SerializerVisitor() {
  4104. }
  4105. _SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
  4106. _SerializerVisitor.prototype.visitContainer = function (container, context) {
  4107. var _this = this;
  4108. return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]";
  4109. };
  4110. _SerializerVisitor.prototype.visitIcu = function (icu, context) {
  4111. var _this = this;
  4112. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4113. return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}";
  4114. };
  4115. _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4116. var _this = this;
  4117. return ph.isVoid ?
  4118. "<ph tag name=\"" + ph.startName + "\"/>" :
  4119. "<ph tag name=\"" + ph.startName + "\">" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + "</ph name=\"" + ph.closeName + "\">";
  4120. };
  4121. _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
  4122. return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
  4123. };
  4124. _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4125. return "<ph icu name=\"" + ph.name + "\">" + ph.value.visit(this) + "</ph>";
  4126. };
  4127. return _SerializerVisitor;
  4128. }());
  4129. var serializerVisitor = new _SerializerVisitor();
  4130. function serializeNodes(nodes) {
  4131. return nodes.map(function (a) { return a.visit(serializerVisitor, null); });
  4132. }
  4133. /**
  4134. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4135. *
  4136. * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
  4137. *
  4138. * @internal
  4139. */
  4140. var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) {
  4141. __extends(_SerializerIgnoreIcuExpVisitor, _super);
  4142. function _SerializerIgnoreIcuExpVisitor() {
  4143. return _super !== null && _super.apply(this, arguments) || this;
  4144. }
  4145. _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
  4146. var _this = this;
  4147. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4148. // Do not take the expression into account
  4149. return "{" + icu.type + ", " + strCases.join(', ') + "}";
  4150. };
  4151. return _SerializerIgnoreIcuExpVisitor;
  4152. }(_SerializerVisitor));
  4153. /**
  4154. * Compute the SHA1 of the given string
  4155. *
  4156. * see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
  4157. *
  4158. * WARNING: this function has not been designed not tested with security in mind.
  4159. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
  4160. */
  4161. function sha1(str) {
  4162. var _a, _b;
  4163. var utf8 = utf8Encode(str);
  4164. var words32 = stringToWords32(utf8, Endian.Big);
  4165. var len = utf8.length * 8;
  4166. var w = new Array(80);
  4167. var _c = __read([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0], 5), a = _c[0], b = _c[1], c = _c[2], d = _c[3], e = _c[4];
  4168. words32[len >> 5] |= 0x80 << (24 - len % 32);
  4169. words32[((len + 64 >> 9) << 4) + 15] = len;
  4170. for (var i = 0; i < words32.length; i += 16) {
  4171. var _d = __read([a, b, c, d, e], 5), h0 = _d[0], h1 = _d[1], h2 = _d[2], h3 = _d[3], h4 = _d[4];
  4172. for (var j = 0; j < 80; j++) {
  4173. if (j < 16) {
  4174. w[j] = words32[i + j];
  4175. }
  4176. else {
  4177. w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  4178. }
  4179. var _e = __read(fk(j, b, c, d), 2), f = _e[0], k = _e[1];
  4180. var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
  4181. _a = __read([d, c, rol32(b, 30), a, temp], 5), e = _a[0], d = _a[1], c = _a[2], b = _a[3], a = _a[4];
  4182. }
  4183. _b = __read([add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)], 5), a = _b[0], b = _b[1], c = _b[2], d = _b[3], e = _b[4];
  4184. }
  4185. return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
  4186. }
  4187. function fk(index, b, c, d) {
  4188. if (index < 20) {
  4189. return [(b & c) | (~b & d), 0x5a827999];
  4190. }
  4191. if (index < 40) {
  4192. return [b ^ c ^ d, 0x6ed9eba1];
  4193. }
  4194. if (index < 60) {
  4195. return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
  4196. }
  4197. return [b ^ c ^ d, 0xca62c1d6];
  4198. }
  4199. /**
  4200. * Compute the fingerprint of the given string
  4201. *
  4202. * The output is 64 bit number encoded as a decimal string
  4203. *
  4204. * based on:
  4205. * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
  4206. */
  4207. function fingerprint(str) {
  4208. var utf8 = utf8Encode(str);
  4209. var _a = __read([hash32(utf8, 0), hash32(utf8, 102072)], 2), hi = _a[0], lo = _a[1];
  4210. if (hi == 0 && (lo == 0 || lo == 1)) {
  4211. hi = hi ^ 0x130f9bef;
  4212. lo = lo ^ -0x6b5f56d8;
  4213. }
  4214. return [hi, lo];
  4215. }
  4216. function computeMsgId(msg, meaning) {
  4217. var _a;
  4218. var _b = __read(fingerprint(msg), 2), hi = _b[0], lo = _b[1];
  4219. if (meaning) {
  4220. var _c = __read(fingerprint(meaning), 2), him = _c[0], lom = _c[1];
  4221. _a = __read(add64(rol64([hi, lo], 1), [him, lom]), 2), hi = _a[0], lo = _a[1];
  4222. }
  4223. return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
  4224. }
  4225. function hash32(str, c) {
  4226. var _a;
  4227. var _b = __read([0x9e3779b9, 0x9e3779b9], 2), a = _b[0], b = _b[1];
  4228. var i;
  4229. var len = str.length;
  4230. for (i = 0; i + 12 <= len; i += 12) {
  4231. a = add32(a, wordAt(str, i, Endian.Little));
  4232. b = add32(b, wordAt(str, i + 4, Endian.Little));
  4233. c = add32(c, wordAt(str, i + 8, Endian.Little));
  4234. _a = __read(mix([a, b, c]), 3), a = _a[0], b = _a[1], c = _a[2];
  4235. }
  4236. a = add32(a, wordAt(str, i, Endian.Little));
  4237. b = add32(b, wordAt(str, i + 4, Endian.Little));
  4238. // the first byte of c is reserved for the length
  4239. c = add32(c, len);
  4240. c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
  4241. return mix([a, b, c])[2];
  4242. }
  4243. // clang-format off
  4244. function mix(_a) {
  4245. var _b = __read(_a, 3), a = _b[0], b = _b[1], c = _b[2];
  4246. a = sub32(a, b);
  4247. a = sub32(a, c);
  4248. a ^= c >>> 13;
  4249. b = sub32(b, c);
  4250. b = sub32(b, a);
  4251. b ^= a << 8;
  4252. c = sub32(c, a);
  4253. c = sub32(c, b);
  4254. c ^= b >>> 13;
  4255. a = sub32(a, b);
  4256. a = sub32(a, c);
  4257. a ^= c >>> 12;
  4258. b = sub32(b, c);
  4259. b = sub32(b, a);
  4260. b ^= a << 16;
  4261. c = sub32(c, a);
  4262. c = sub32(c, b);
  4263. c ^= b >>> 5;
  4264. a = sub32(a, b);
  4265. a = sub32(a, c);
  4266. a ^= c >>> 3;
  4267. b = sub32(b, c);
  4268. b = sub32(b, a);
  4269. b ^= a << 10;
  4270. c = sub32(c, a);
  4271. c = sub32(c, b);
  4272. c ^= b >>> 15;
  4273. return [a, b, c];
  4274. }
  4275. // clang-format on
  4276. // Utils
  4277. var Endian;
  4278. (function (Endian) {
  4279. Endian[Endian["Little"] = 0] = "Little";
  4280. Endian[Endian["Big"] = 1] = "Big";
  4281. })(Endian || (Endian = {}));
  4282. function add32(a, b) {
  4283. return add32to64(a, b)[1];
  4284. }
  4285. function add32to64(a, b) {
  4286. var low = (a & 0xffff) + (b & 0xffff);
  4287. var high = (a >>> 16) + (b >>> 16) + (low >>> 16);
  4288. return [high >>> 16, (high << 16) | (low & 0xffff)];
  4289. }
  4290. function add64(_a, _b) {
  4291. var _c = __read(_a, 2), ah = _c[0], al = _c[1];
  4292. var _d = __read(_b, 2), bh = _d[0], bl = _d[1];
  4293. var _e = __read(add32to64(al, bl), 2), carry = _e[0], l = _e[1];
  4294. var h = add32(add32(ah, bh), carry);
  4295. return [h, l];
  4296. }
  4297. function sub32(a, b) {
  4298. var low = (a & 0xffff) - (b & 0xffff);
  4299. var high = (a >> 16) - (b >> 16) + (low >> 16);
  4300. return (high << 16) | (low & 0xffff);
  4301. }
  4302. // Rotate a 32b number left `count` position
  4303. function rol32(a, count) {
  4304. return (a << count) | (a >>> (32 - count));
  4305. }
  4306. // Rotate a 64b number left `count` position
  4307. function rol64(_a, count) {
  4308. var _b = __read(_a, 2), hi = _b[0], lo = _b[1];
  4309. var h = (hi << count) | (lo >>> (32 - count));
  4310. var l = (lo << count) | (hi >>> (32 - count));
  4311. return [h, l];
  4312. }
  4313. function stringToWords32(str, endian) {
  4314. var words32 = Array((str.length + 3) >>> 2);
  4315. for (var i = 0; i < words32.length; i++) {
  4316. words32[i] = wordAt(str, i * 4, endian);
  4317. }
  4318. return words32;
  4319. }
  4320. function byteAt(str, index) {
  4321. return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
  4322. }
  4323. function wordAt(str, index, endian) {
  4324. var word = 0;
  4325. if (endian === Endian.Big) {
  4326. for (var i = 0; i < 4; i++) {
  4327. word += byteAt(str, index + i) << (24 - 8 * i);
  4328. }
  4329. }
  4330. else {
  4331. for (var i = 0; i < 4; i++) {
  4332. word += byteAt(str, index + i) << 8 * i;
  4333. }
  4334. }
  4335. return word;
  4336. }
  4337. function words32ToByteString(words32) {
  4338. return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, '');
  4339. }
  4340. function word32ToByteString(word) {
  4341. var str = '';
  4342. for (var i = 0; i < 4; i++) {
  4343. str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
  4344. }
  4345. return str;
  4346. }
  4347. function byteStringToHexString(str) {
  4348. var hex = '';
  4349. for (var i = 0; i < str.length; i++) {
  4350. var b = byteAt(str, i);
  4351. hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
  4352. }
  4353. return hex.toLowerCase();
  4354. }
  4355. // based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b)
  4356. function byteStringToDecString(str) {
  4357. var decimal = '';
  4358. var toThePower = '1';
  4359. for (var i = str.length - 1; i >= 0; i--) {
  4360. decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
  4361. toThePower = numberTimesBigInt(256, toThePower);
  4362. }
  4363. return decimal.split('').reverse().join('');
  4364. }
  4365. // x and y decimal, lowest significant digit first
  4366. function addBigInt(x, y) {
  4367. var sum = '';
  4368. var len = Math.max(x.length, y.length);
  4369. for (var i = 0, carry = 0; i < len || carry; i++) {
  4370. var tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
  4371. if (tmpSum >= 10) {
  4372. carry = 1;
  4373. sum += tmpSum - 10;
  4374. }
  4375. else {
  4376. carry = 0;
  4377. sum += tmpSum;
  4378. }
  4379. }
  4380. return sum;
  4381. }
  4382. function numberTimesBigInt(num, b) {
  4383. var product = '';
  4384. var bToThePower = b;
  4385. for (; num !== 0; num = num >>> 1) {
  4386. if (num & 1)
  4387. product = addBigInt(product, bToThePower);
  4388. bToThePower = addBigInt(bToThePower, bToThePower);
  4389. }
  4390. return product;
  4391. }
  4392. /**
  4393. * @license
  4394. * Copyright Google Inc. All Rights Reserved.
  4395. *
  4396. * Use of this source code is governed by an MIT-style license that can be
  4397. * found in the LICENSE file at https://angular.io/license
  4398. */
  4399. var Serializer = /** @class */ (function () {
  4400. function Serializer() {
  4401. }
  4402. // Creates a name mapper, see `PlaceholderMapper`
  4403. // Returning `null` means that no name mapping is used.
  4404. Serializer.prototype.createNameMapper = function (message) { return null; };
  4405. return Serializer;
  4406. }());
  4407. /**
  4408. * A simple mapper that take a function to transform an internal name to a public name
  4409. */
  4410. var SimplePlaceholderMapper = /** @class */ (function (_super) {
  4411. __extends(SimplePlaceholderMapper, _super);
  4412. // create a mapping from the message
  4413. function SimplePlaceholderMapper(message, mapName) {
  4414. var _this = _super.call(this) || this;
  4415. _this.mapName = mapName;
  4416. _this.internalToPublic = {};
  4417. _this.publicToNextId = {};
  4418. _this.publicToInternal = {};
  4419. message.nodes.forEach(function (node) { return node.visit(_this); });
  4420. return _this;
  4421. }
  4422. SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
  4423. return this.internalToPublic.hasOwnProperty(internalName) ?
  4424. this.internalToPublic[internalName] :
  4425. null;
  4426. };
  4427. SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
  4428. return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
  4429. null;
  4430. };
  4431. SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; };
  4432. SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
  4433. this.visitPlaceholderName(ph.startName);
  4434. _super.prototype.visitTagPlaceholder.call(this, ph, context);
  4435. this.visitPlaceholderName(ph.closeName);
  4436. };
  4437. SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); };
  4438. SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
  4439. this.visitPlaceholderName(ph.name);
  4440. };
  4441. // XMB placeholders could only contains A-Z, 0-9 and _
  4442. SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
  4443. if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
  4444. return;
  4445. }
  4446. var publicName = this.mapName(internalName);
  4447. if (this.publicToInternal.hasOwnProperty(publicName)) {
  4448. // Create a new XMB when it has already been used
  4449. var nextId = this.publicToNextId[publicName];
  4450. this.publicToNextId[publicName] = nextId + 1;
  4451. publicName = publicName + "_" + nextId;
  4452. }
  4453. else {
  4454. this.publicToNextId[publicName] = 1;
  4455. }
  4456. this.internalToPublic[internalName] = publicName;
  4457. this.publicToInternal[publicName] = internalName;
  4458. };
  4459. return SimplePlaceholderMapper;
  4460. }(RecurseVisitor));
  4461. /**
  4462. * @license
  4463. * Copyright Google Inc. All Rights Reserved.
  4464. *
  4465. * Use of this source code is governed by an MIT-style license that can be
  4466. * found in the LICENSE file at https://angular.io/license
  4467. */
  4468. var _Visitor = /** @class */ (function () {
  4469. function _Visitor() {
  4470. }
  4471. _Visitor.prototype.visitTag = function (tag) {
  4472. var _this = this;
  4473. var strAttrs = this._serializeAttributes(tag.attrs);
  4474. if (tag.children.length == 0) {
  4475. return "<" + tag.name + strAttrs + "/>";
  4476. }
  4477. var strChildren = tag.children.map(function (node) { return node.visit(_this); });
  4478. return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "</" + tag.name + ">";
  4479. };
  4480. _Visitor.prototype.visitText = function (text) { return text.value; };
  4481. _Visitor.prototype.visitDeclaration = function (decl) {
  4482. return "<?xml" + this._serializeAttributes(decl.attrs) + " ?>";
  4483. };
  4484. _Visitor.prototype._serializeAttributes = function (attrs) {
  4485. var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
  4486. return strAttrs.length > 0 ? ' ' + strAttrs : '';
  4487. };
  4488. _Visitor.prototype.visitDoctype = function (doctype) {
  4489. return "<!DOCTYPE " + doctype.rootTag + " [\n" + doctype.dtd + "\n]>";
  4490. };
  4491. return _Visitor;
  4492. }());
  4493. var _visitor = new _Visitor();
  4494. function serialize(nodes) {
  4495. return nodes.map(function (node) { return node.visit(_visitor); }).join('');
  4496. }
  4497. var Declaration = /** @class */ (function () {
  4498. function Declaration(unescapedAttrs) {
  4499. var _this = this;
  4500. this.attrs = {};
  4501. Object.keys(unescapedAttrs).forEach(function (k) {
  4502. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4503. });
  4504. }
  4505. Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); };
  4506. return Declaration;
  4507. }());
  4508. var Doctype = /** @class */ (function () {
  4509. function Doctype(rootTag, dtd) {
  4510. this.rootTag = rootTag;
  4511. this.dtd = dtd;
  4512. }
  4513. Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); };
  4514. return Doctype;
  4515. }());
  4516. var Tag = /** @class */ (function () {
  4517. function Tag(name, unescapedAttrs, children) {
  4518. var _this = this;
  4519. if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
  4520. if (children === void 0) { children = []; }
  4521. this.name = name;
  4522. this.children = children;
  4523. this.attrs = {};
  4524. Object.keys(unescapedAttrs).forEach(function (k) {
  4525. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4526. });
  4527. }
  4528. Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); };
  4529. return Tag;
  4530. }());
  4531. var Text$2 = /** @class */ (function () {
  4532. function Text(unescapedValue) {
  4533. this.value = escapeXml(unescapedValue);
  4534. }
  4535. Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
  4536. return Text;
  4537. }());
  4538. var CR = /** @class */ (function (_super) {
  4539. __extends(CR, _super);
  4540. function CR(ws) {
  4541. if (ws === void 0) { ws = 0; }
  4542. return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
  4543. }
  4544. return CR;
  4545. }(Text$2));
  4546. var _ESCAPED_CHARS = [
  4547. [/&/g, '&amp;'],
  4548. [/"/g, '&quot;'],
  4549. [/'/g, '&apos;'],
  4550. [/</g, '&lt;'],
  4551. [/>/g, '&gt;'],
  4552. ];
  4553. // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
  4554. function escapeXml(text) {
  4555. return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
  4556. }
  4557. /**
  4558. * @license
  4559. * Copyright Google Inc. All Rights Reserved.
  4560. *
  4561. * Use of this source code is governed by an MIT-style license that can be
  4562. * found in the LICENSE file at https://angular.io/license
  4563. */
  4564. var _MESSAGES_TAG = 'messagebundle';
  4565. var _MESSAGE_TAG = 'msg';
  4566. var _PLACEHOLDER_TAG = 'ph';
  4567. var _EXAMPLE_TAG = 'ex';
  4568. var _SOURCE_TAG = 'source';
  4569. var _DOCTYPE = "<!ELEMENT messagebundle (msg)*>\n<!ATTLIST messagebundle class CDATA #IMPLIED>\n\n<!ELEMENT msg (#PCDATA|ph|source)*>\n<!ATTLIST msg id CDATA #IMPLIED>\n<!ATTLIST msg seq CDATA #IMPLIED>\n<!ATTLIST msg name CDATA #IMPLIED>\n<!ATTLIST msg desc CDATA #IMPLIED>\n<!ATTLIST msg meaning CDATA #IMPLIED>\n<!ATTLIST msg obsolete (obsolete) #IMPLIED>\n<!ATTLIST msg xml:space (default|preserve) \"default\">\n<!ATTLIST msg is_hidden CDATA #IMPLIED>\n\n<!ELEMENT source (#PCDATA)>\n\n<!ELEMENT ph (#PCDATA|ex)*>\n<!ATTLIST ph name CDATA #REQUIRED>\n\n<!ELEMENT ex (#PCDATA)>";
  4570. var Xmb = /** @class */ (function (_super) {
  4571. __extends(Xmb, _super);
  4572. function Xmb() {
  4573. return _super !== null && _super.apply(this, arguments) || this;
  4574. }
  4575. Xmb.prototype.write = function (messages, locale) {
  4576. var exampleVisitor = new ExampleVisitor();
  4577. var visitor = new _Visitor$1();
  4578. var rootNode = new Tag(_MESSAGES_TAG);
  4579. messages.forEach(function (message) {
  4580. var attrs = { id: message.id };
  4581. if (message.description) {
  4582. attrs['desc'] = message.description;
  4583. }
  4584. if (message.meaning) {
  4585. attrs['meaning'] = message.meaning;
  4586. }
  4587. var sourceTags = [];
  4588. message.sources.forEach(function (source) {
  4589. sourceTags.push(new Tag(_SOURCE_TAG, {}, [
  4590. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  4591. ]));
  4592. });
  4593. rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spread(sourceTags, visitor.serialize(message.nodes))));
  4594. });
  4595. rootNode.children.push(new CR());
  4596. return serialize([
  4597. new Declaration({ version: '1.0', encoding: 'UTF-8' }),
  4598. new CR(),
  4599. new Doctype(_MESSAGES_TAG, _DOCTYPE),
  4600. new CR(),
  4601. exampleVisitor.addDefaultExamples(rootNode),
  4602. new CR(),
  4603. ]);
  4604. };
  4605. Xmb.prototype.load = function (content, url) {
  4606. throw new Error('Unsupported');
  4607. };
  4608. Xmb.prototype.digest = function (message) { return digest$1(message); };
  4609. Xmb.prototype.createNameMapper = function (message) {
  4610. return new SimplePlaceholderMapper(message, toPublicName);
  4611. };
  4612. return Xmb;
  4613. }(Serializer));
  4614. var _Visitor$1 = /** @class */ (function () {
  4615. function _Visitor() {
  4616. }
  4617. _Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  4618. _Visitor.prototype.visitContainer = function (container, context) {
  4619. var _this = this;
  4620. var nodes = [];
  4621. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  4622. return nodes;
  4623. };
  4624. _Visitor.prototype.visitIcu = function (icu, context) {
  4625. var _this = this;
  4626. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  4627. Object.keys(icu.cases).forEach(function (c) {
  4628. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  4629. });
  4630. nodes.push(new Text$2("}"));
  4631. return nodes;
  4632. };
  4633. _Visitor.prototype.visitTagPlaceholder = function (ph, context) {
  4634. var startTagAsText = new Text$2("<" + ph.tag + ">");
  4635. var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
  4636. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4637. var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
  4638. if (ph.isVoid) {
  4639. // void tags have no children nor closing tags
  4640. return [startTagPh];
  4641. }
  4642. var closeTagAsText = new Text$2("</" + ph.tag + ">");
  4643. var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
  4644. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4645. var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
  4646. return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
  4647. };
  4648. _Visitor.prototype.visitPlaceholder = function (ph, context) {
  4649. var interpolationAsText = new Text$2("{{" + ph.value + "}}");
  4650. // Example tag needs to be not-empty for TC.
  4651. var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
  4652. return [
  4653. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4654. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
  4655. ];
  4656. };
  4657. _Visitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4658. var icuExpression = ph.value.expression;
  4659. var icuType = ph.value.type;
  4660. var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  4661. var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}");
  4662. var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
  4663. return [
  4664. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4665. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
  4666. ];
  4667. };
  4668. _Visitor.prototype.serialize = function (nodes) {
  4669. var _this = this;
  4670. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  4671. };
  4672. return _Visitor;
  4673. }());
  4674. function digest$1(message) {
  4675. return decimalDigest(message);
  4676. }
  4677. // TC requires at least one non-empty example on placeholders
  4678. var ExampleVisitor = /** @class */ (function () {
  4679. function ExampleVisitor() {
  4680. }
  4681. ExampleVisitor.prototype.addDefaultExamples = function (node) {
  4682. node.visit(this);
  4683. return node;
  4684. };
  4685. ExampleVisitor.prototype.visitTag = function (tag) {
  4686. var _this = this;
  4687. if (tag.name === _PLACEHOLDER_TAG) {
  4688. if (!tag.children || tag.children.length == 0) {
  4689. var exText = new Text$2(tag.attrs['name'] || '...');
  4690. tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
  4691. }
  4692. }
  4693. else if (tag.children) {
  4694. tag.children.forEach(function (node) { return node.visit(_this); });
  4695. }
  4696. };
  4697. ExampleVisitor.prototype.visitText = function (text) { };
  4698. ExampleVisitor.prototype.visitDeclaration = function (decl) { };
  4699. ExampleVisitor.prototype.visitDoctype = function (doctype) { };
  4700. return ExampleVisitor;
  4701. }());
  4702. // XMB/XTB placeholders can only contain A-Z, 0-9 and _
  4703. function toPublicName(internalName) {
  4704. return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
  4705. }
  4706. /**
  4707. * @license
  4708. * Copyright Google Inc. All Rights Reserved.
  4709. *
  4710. * Use of this source code is governed by an MIT-style license that can be
  4711. * found in the LICENSE file at https://angular.io/license
  4712. */
  4713. function mapLiteral(obj, quoted) {
  4714. if (quoted === void 0) { quoted = false; }
  4715. return literalMap(Object.keys(obj).map(function (key) { return ({
  4716. key: key,
  4717. quoted: quoted,
  4718. value: obj[key],
  4719. }); }));
  4720. }
  4721. /**
  4722. * @license
  4723. * Copyright Google Inc. All Rights Reserved.
  4724. *
  4725. * Use of this source code is governed by an MIT-style license that can be
  4726. * found in the LICENSE file at https://angular.io/license
  4727. */
  4728. /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
  4729. var CLOSURE_TRANSLATION_PREFIX = 'MSG_';
  4730. /* Prefix for non-`goog.getMsg` i18n-related vars */
  4731. var TRANSLATION_PREFIX = 'I18N_';
  4732. /** Closure uses `goog.getMsg(message)` to lookup translations */
  4733. var GOOG_GET_MSG = 'goog.getMsg';
  4734. /** Name of the global variable that is used to determine if we use Closure translations or not */
  4735. var NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
  4736. /** I18n separators for metadata **/
  4737. var I18N_MEANING_SEPARATOR = '|';
  4738. var I18N_ID_SEPARATOR = '@@';
  4739. /** Name of the i18n attributes **/
  4740. var I18N_ATTR = 'i18n';
  4741. var I18N_ATTR_PREFIX = 'i18n-';
  4742. /** Prefix of var expressions used in ICUs */
  4743. var I18N_ICU_VAR_PREFIX = 'VAR_';
  4744. /** Prefix of ICU expressions for post processing */
  4745. var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
  4746. /** Placeholder wrapper for i18n expressions **/
  4747. var I18N_PLACEHOLDER_SYMBOL = '�';
  4748. function i18nTranslationToDeclStmt(variable$1, closureVar, message, meta, params) {
  4749. var statements = [];
  4750. // var I18N_X;
  4751. statements.push(new DeclareVarStmt(variable$1.name, undefined, INFERRED_TYPE, null, variable$1.sourceSpan));
  4752. var args = [literal(message)];
  4753. if (params && Object.keys(params).length) {
  4754. args.push(mapLiteral(params, true));
  4755. }
  4756. // Closure JSDoc comments
  4757. var docStatements = i18nMetaToDocStmt(meta);
  4758. var thenStatements = docStatements ? [docStatements] : [];
  4759. var googFnCall = variable(GOOG_GET_MSG).callFn(args);
  4760. // const MSG_... = goog.getMsg(..);
  4761. thenStatements.push(closureVar.set(googFnCall).toConstDecl());
  4762. // I18N_X = MSG_...;
  4763. thenStatements.push(new ExpressionStatement(variable$1.set(closureVar)));
  4764. var localizeFnCall = importExpr(Identifiers$1.i18nLocalize).callFn(args);
  4765. // I18N_X = i18nLocalize(...);
  4766. var elseStatements = [new ExpressionStatement(variable$1.set(localizeFnCall))];
  4767. // if(ngI18nClosureMode) { ... } else { ... }
  4768. statements.push(ifStmt(variable(NG_I18N_CLOSURE_MODE), thenStatements, elseStatements));
  4769. return statements;
  4770. }
  4771. // Converts i18n meta information for a message (id, description, meaning)
  4772. // to a JsDoc statement formatted as expected by the Closure compiler.
  4773. function i18nMetaToDocStmt(meta) {
  4774. var tags = [];
  4775. if (meta.description) {
  4776. tags.push({ tagName: "desc" /* Desc */, text: meta.description });
  4777. }
  4778. if (meta.meaning) {
  4779. tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
  4780. }
  4781. return tags.length == 0 ? null : new JSDocCommentStmt(tags);
  4782. }
  4783. function isI18nAttribute(name) {
  4784. return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
  4785. }
  4786. function isI18nRootNode(meta) {
  4787. return meta instanceof Message;
  4788. }
  4789. function isSingleI18nIcu(meta) {
  4790. return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
  4791. }
  4792. function hasI18nAttrs(element) {
  4793. return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); });
  4794. }
  4795. function metaFromI18nMessage(message, id) {
  4796. if (id === void 0) { id = null; }
  4797. return {
  4798. id: typeof id === 'string' ? id : message.id || '',
  4799. meaning: message.meaning || '',
  4800. description: message.description || ''
  4801. };
  4802. }
  4803. function icuFromI18nMessage(message) {
  4804. return message.nodes[0];
  4805. }
  4806. function wrapI18nPlaceholder(content, contextId) {
  4807. if (contextId === void 0) { contextId = 0; }
  4808. var blockId = contextId > 0 ? ":" + contextId : '';
  4809. return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL;
  4810. }
  4811. function assembleI18nBoundString(strings, bindingStartIndex, contextId) {
  4812. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  4813. if (contextId === void 0) { contextId = 0; }
  4814. if (!strings.length)
  4815. return '';
  4816. var acc = '';
  4817. var lastIdx = strings.length - 1;
  4818. for (var i = 0; i < lastIdx; i++) {
  4819. acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId);
  4820. }
  4821. acc += strings[lastIdx];
  4822. return acc;
  4823. }
  4824. function getSeqNumberGenerator(startsAt) {
  4825. if (startsAt === void 0) { startsAt = 0; }
  4826. var current = startsAt;
  4827. return function () { return current++; };
  4828. }
  4829. function placeholdersToParams(placeholders) {
  4830. var params = {};
  4831. placeholders.forEach(function (values, key) {
  4832. params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]);
  4833. });
  4834. return params;
  4835. }
  4836. function updatePlaceholderMap(map, name) {
  4837. var values = [];
  4838. for (var _i = 2; _i < arguments.length; _i++) {
  4839. values[_i - 2] = arguments[_i];
  4840. }
  4841. var current = map.get(name) || [];
  4842. current.push.apply(current, __spread(values));
  4843. map.set(name, current);
  4844. }
  4845. function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) {
  4846. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  4847. if (contextId === void 0) { contextId = 0; }
  4848. var startIdx = bindingStartIndex;
  4849. var placeholders = new Map();
  4850. var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta;
  4851. if (node) {
  4852. node
  4853. .children.filter(function (child) { return child instanceof Placeholder; })
  4854. .forEach(function (child, idx) {
  4855. var content = wrapI18nPlaceholder(startIdx + idx, contextId);
  4856. updatePlaceholderMap(placeholders, child.name, content);
  4857. });
  4858. }
  4859. return placeholders;
  4860. }
  4861. function findIndex(items, callback) {
  4862. for (var i = 0; i < items.length; i++) {
  4863. if (callback(items[i])) {
  4864. return i;
  4865. }
  4866. }
  4867. return -1;
  4868. }
  4869. /**
  4870. * Parses i18n metas like:
  4871. * - "@@id",
  4872. * - "description[@@id]",
  4873. * - "meaning|description[@@id]"
  4874. * and returns an object with parsed output.
  4875. *
  4876. * @param meta String that represents i18n meta
  4877. * @returns Object with id, meaning and description fields
  4878. */
  4879. function parseI18nMeta(meta) {
  4880. var _a, _b;
  4881. var id;
  4882. var meaning;
  4883. var description;
  4884. if (meta) {
  4885. var idIndex = meta.indexOf(I18N_ID_SEPARATOR);
  4886. var descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
  4887. var meaningAndDesc = void 0;
  4888. _a = __read((idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  4889. _b = __read((descIndex > -1) ?
  4890. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  4891. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  4892. }
  4893. return { id: id, meaning: meaning, description: description };
  4894. }
  4895. /**
  4896. * Converts internal placeholder names to public-facing format
  4897. * (for example to use in goog.getMsg call).
  4898. * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
  4899. *
  4900. * @param name The placeholder name that should be formatted
  4901. * @returns Formatted placeholder name
  4902. */
  4903. function formatI18nPlaceholderName(name) {
  4904. var chunks = toPublicName(name).split('_');
  4905. if (chunks.length === 1) {
  4906. // if no "_" found - just lowercase the value
  4907. return name.toLowerCase();
  4908. }
  4909. var postfix;
  4910. // eject last element if it's a number
  4911. if (/^\d+$/.test(chunks[chunks.length - 1])) {
  4912. postfix = chunks.pop();
  4913. }
  4914. var raw = chunks.shift().toLowerCase();
  4915. if (chunks.length) {
  4916. raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join('');
  4917. }
  4918. return postfix ? raw + "_" + postfix : raw;
  4919. }
  4920. /**
  4921. * Generates a prefix for translation const name.
  4922. *
  4923. * @param extra Additional local prefix that should be injected into translation var name
  4924. * @returns Complete translation const prefix
  4925. */
  4926. function getTranslationConstPrefix(extra) {
  4927. return ("" + CLOSURE_TRANSLATION_PREFIX + extra).toUpperCase();
  4928. }
  4929. /**
  4930. * Generates translation declaration statements.
  4931. *
  4932. * @param variable Translation value reference
  4933. * @param closureVar Variable for Closure `goog.getMsg` calls
  4934. * @param message Text message to be translated
  4935. * @param meta Object that contains meta information (id, meaning and description)
  4936. * @param params Object with placeholders key-value pairs
  4937. * @param transformFn Optional transformation (post processing) function reference
  4938. * @returns Array of Statements that represent a given translation
  4939. */
  4940. function getTranslationDeclStmts(variable, closureVar, message, meta, params, transformFn) {
  4941. if (params === void 0) { params = {}; }
  4942. var statements = [];
  4943. statements.push.apply(statements, __spread(i18nTranslationToDeclStmt(variable, closureVar, message, meta, params)));
  4944. if (transformFn) {
  4945. statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
  4946. }
  4947. return statements;
  4948. }
  4949. /**
  4950. * @license
  4951. * Copyright Google Inc. All Rights Reserved.
  4952. *
  4953. * Use of this source code is governed by an MIT-style license that can be
  4954. * found in the LICENSE file at https://angular.io/license
  4955. */
  4956. /**
  4957. * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
  4958. * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
  4959. * bot work in some cases when object keys are mangled by minifier.
  4960. *
  4961. * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
  4962. * inputs that contain potentially unsafe chars.
  4963. */
  4964. var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
  4965. /** Name of the temporary to use during data binding */
  4966. var TEMPORARY_NAME = '_t';
  4967. /** Name of the context parameter passed into a template function */
  4968. var CONTEXT_NAME = 'ctx';
  4969. /** Name of the RenderFlag passed into a template function */
  4970. var RENDER_FLAGS = 'rf';
  4971. /** The prefix reference variables */
  4972. var REFERENCE_PREFIX = '_r';
  4973. /** The name of the implicit context reference */
  4974. var IMPLICIT_REFERENCE = '$implicit';
  4975. /** Non bindable attribute name **/
  4976. var NON_BINDABLE_ATTR = 'ngNonBindable';
  4977. /**
  4978. * Creates an allocator for a temporary variable.
  4979. *
  4980. * A variable declaration is added to the statements the first time the allocator is invoked.
  4981. */
  4982. function temporaryAllocator(statements, name) {
  4983. var temp = null;
  4984. return function () {
  4985. if (!temp) {
  4986. statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
  4987. temp = variable(name);
  4988. }
  4989. return temp;
  4990. };
  4991. }
  4992. function unsupported(feature) {
  4993. if (this) {
  4994. throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet");
  4995. }
  4996. throw new Error("Feature " + feature + " is not supported yet");
  4997. }
  4998. function invalid$1(arg) {
  4999. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  5000. }
  5001. function asLiteral(value) {
  5002. if (Array.isArray(value)) {
  5003. return literalArr(value.map(asLiteral));
  5004. }
  5005. return literal(value, INFERRED_TYPE);
  5006. }
  5007. function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
  5008. if (Object.getOwnPropertyNames(keys).length > 0) {
  5009. return mapToExpression(keys, keepDeclared);
  5010. }
  5011. return null;
  5012. }
  5013. function mapToExpression(map, keepDeclared) {
  5014. return literalMap(Object.getOwnPropertyNames(map).map(function (key) {
  5015. var _a, _b;
  5016. // canonical syntax: `dirProp: publicProp`
  5017. // if there is no `:`, use dirProp = elProp
  5018. var value = map[key];
  5019. var declaredName;
  5020. var publicName;
  5021. var minifiedName;
  5022. if (Array.isArray(value)) {
  5023. _a = __read(value, 2), publicName = _a[0], declaredName = _a[1];
  5024. }
  5025. else {
  5026. _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1];
  5027. }
  5028. minifiedName = declaredName;
  5029. return {
  5030. key: minifiedName,
  5031. // put quotes around keys that contain potentially unsafe characters
  5032. quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
  5033. value: (keepDeclared && publicName !== declaredName) ?
  5034. literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
  5035. asLiteral(publicName)
  5036. };
  5037. }));
  5038. }
  5039. /**
  5040. * Remove trailing null nodes as they are implied.
  5041. */
  5042. function trimTrailingNulls(parameters) {
  5043. while (isNull(parameters[parameters.length - 1])) {
  5044. parameters.pop();
  5045. }
  5046. return parameters;
  5047. }
  5048. function getQueryPredicate(query, constantPool) {
  5049. if (Array.isArray(query.predicate)) {
  5050. var predicate_1 = [];
  5051. query.predicate.forEach(function (selector) {
  5052. // Each item in predicates array may contain strings with comma-separated refs
  5053. // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
  5054. // as separate array entities
  5055. var selectors = selector.split(',').map(function (token) { return literal(token.trim()); });
  5056. predicate_1.push.apply(predicate_1, __spread(selectors));
  5057. });
  5058. return constantPool.getConstLiteral(literalArr(predicate_1), true);
  5059. }
  5060. else {
  5061. return query.predicate;
  5062. }
  5063. }
  5064. var DefinitionMap = /** @class */ (function () {
  5065. function DefinitionMap() {
  5066. this.values = [];
  5067. }
  5068. DefinitionMap.prototype.set = function (key, value) {
  5069. if (value) {
  5070. this.values.push({ key: key, value: value, quoted: false });
  5071. }
  5072. };
  5073. DefinitionMap.prototype.toLiteralMap = function () { return literalMap(this.values); };
  5074. return DefinitionMap;
  5075. }());
  5076. /**
  5077. * Extract a map of properties to values for a given element or template node, which can be used
  5078. * by the directive matching machinery.
  5079. *
  5080. * @param elOrTpl the element or template in question
  5081. * @return an object set up for directive matching. For attributes on the element/template, this
  5082. * object maps a property name to its (static) value. For any bindings, this map simply maps the
  5083. * property name to an empty string.
  5084. */
  5085. function getAttrsForDirectiveMatching(elOrTpl) {
  5086. var attributesMap = {};
  5087. if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
  5088. elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; });
  5089. }
  5090. else {
  5091. elOrTpl.attributes.forEach(function (a) {
  5092. if (!isI18nAttribute(a.name)) {
  5093. attributesMap[a.name] = a.value;
  5094. }
  5095. });
  5096. elOrTpl.inputs.forEach(function (i) { attributesMap[i.name] = ''; });
  5097. elOrTpl.outputs.forEach(function (o) { attributesMap[o.name] = ''; });
  5098. }
  5099. return attributesMap;
  5100. }
  5101. /**
  5102. * @license
  5103. * Copyright Google Inc. All Rights Reserved.
  5104. *
  5105. * Use of this source code is governed by an MIT-style license that can be
  5106. * found in the LICENSE file at https://angular.io/license
  5107. */
  5108. var R3FactoryDelegateType;
  5109. (function (R3FactoryDelegateType) {
  5110. R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
  5111. R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
  5112. R3FactoryDelegateType[R3FactoryDelegateType["Factory"] = 2] = "Factory";
  5113. })(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
  5114. /**
  5115. * Resolved type of a dependency.
  5116. *
  5117. * Occasionally, dependencies will have special significance which is known statically. In that
  5118. * case the `R3ResolvedDependencyType` informs the factory generator that a particular dependency
  5119. * should be generated specially (usually by calling a special injection function instead of the
  5120. * standard one).
  5121. */
  5122. var R3ResolvedDependencyType;
  5123. (function (R3ResolvedDependencyType) {
  5124. /**
  5125. * A normal token dependency.
  5126. */
  5127. R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
  5128. /**
  5129. * The dependency is for an attribute.
  5130. *
  5131. * The token expression is a string representing the attribute name.
  5132. */
  5133. R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
  5134. })(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
  5135. /**
  5136. * Construct a factory function expression for the given `R3FactoryMetadata`.
  5137. */
  5138. function compileFactoryFunction(meta) {
  5139. var t = variable('t');
  5140. var statements = [];
  5141. // The type to instantiate via constructor invocation. If there is no delegated factory, meaning
  5142. // this type is always created by constructor invocation, then this is the type-to-create
  5143. // parameter provided by the user (t) if specified, or the current type if not. If there is a
  5144. // delegated factory (which is used to create the current type) then this is only the type-to-
  5145. // create parameter (t).
  5146. var typeForCtor = !isDelegatedMetadata(meta) ? new BinaryOperatorExpr(BinaryOperator.Or, t, meta.type) : t;
  5147. var ctorExpr = null;
  5148. if (meta.deps !== null) {
  5149. // There is a constructor (either explicitly or implicitly defined).
  5150. if (meta.deps !== 'invalid') {
  5151. ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn));
  5152. }
  5153. }
  5154. else {
  5155. var baseFactory = variable("\u0275" + meta.name + "_BaseFactory");
  5156. var getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory);
  5157. var baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.type])).toDeclStmt(INFERRED_TYPE, [
  5158. StmtModifier.Exported, StmtModifier.Final
  5159. ]);
  5160. statements.push(baseFactoryStmt);
  5161. // There is no constructor, use the base class' factory to construct typeForCtor.
  5162. ctorExpr = baseFactory.callFn([typeForCtor]);
  5163. }
  5164. var ctorExprFinal = ctorExpr;
  5165. var body = [];
  5166. var retExpr = null;
  5167. function makeConditionalFactory(nonCtorExpr) {
  5168. var r = variable('r');
  5169. body.push(r.set(NULL_EXPR).toDeclStmt());
  5170. var ctorStmt = null;
  5171. if (ctorExprFinal !== null) {
  5172. ctorStmt = r.set(ctorExprFinal).toStmt();
  5173. }
  5174. else {
  5175. ctorStmt = makeErrorStmt(meta.name);
  5176. }
  5177. body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
  5178. return r;
  5179. }
  5180. if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) {
  5181. var delegateFactory = variable("\u0275" + meta.name + "_BaseFactory");
  5182. var getFactoryOf = importExpr(Identifiers$1.getFactoryOf);
  5183. if (meta.delegate.isEquivalent(meta.type)) {
  5184. throw new Error("Illegal state: compiling factory that delegates to itself");
  5185. }
  5186. var delegateFactoryStmt = delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt(INFERRED_TYPE, [
  5187. StmtModifier.Exported, StmtModifier.Final
  5188. ]);
  5189. statements.push(delegateFactoryStmt);
  5190. retExpr = makeConditionalFactory(delegateFactory.callFn([]));
  5191. }
  5192. else if (isDelegatedMetadata(meta)) {
  5193. // This type is created with a delegated factory. If a type parameter is not specified, call
  5194. // the factory instead.
  5195. var delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn);
  5196. // Either call `new delegate(...)` or `delegate(...)` depending on meta.useNewForDelegate.
  5197. var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
  5198. InstantiateExpr :
  5199. InvokeFunctionExpr)(meta.delegate, delegateArgs);
  5200. retExpr = makeConditionalFactory(factoryExpr);
  5201. }
  5202. else if (isExpressionFactoryMetadata(meta)) {
  5203. // TODO(alxhub): decide whether to lower the value here or in the caller
  5204. retExpr = makeConditionalFactory(meta.expression);
  5205. }
  5206. else {
  5207. retExpr = ctorExpr;
  5208. }
  5209. if (retExpr !== null) {
  5210. body.push(new ReturnStatement(retExpr));
  5211. }
  5212. else {
  5213. body.push(makeErrorStmt(meta.name));
  5214. }
  5215. return {
  5216. factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory"),
  5217. statements: statements,
  5218. };
  5219. }
  5220. function injectDependencies(deps, injectFn) {
  5221. return deps.map(function (dep) { return compileInjectDependency(dep, injectFn); });
  5222. }
  5223. function compileInjectDependency(dep, injectFn) {
  5224. // Interpret the dependency according to its resolved type.
  5225. switch (dep.resolved) {
  5226. case R3ResolvedDependencyType.Token: {
  5227. // Build up the injection flags according to the metadata.
  5228. var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
  5229. (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
  5230. (dep.optional ? 8 /* Optional */ : 0);
  5231. // Build up the arguments to the injectFn call.
  5232. var injectArgs = [dep.token];
  5233. // If this dependency is optional or otherwise has non-default flags, then additional
  5234. // parameters describing how to inject the dependency must be passed to the inject function
  5235. // that's being used.
  5236. if (flags !== 0 /* Default */ || dep.optional) {
  5237. injectArgs.push(literal(flags));
  5238. }
  5239. return importExpr(injectFn).callFn(injectArgs);
  5240. }
  5241. case R3ResolvedDependencyType.Attribute:
  5242. // In the case of attributes, the attribute name in question is given as the token.
  5243. return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]);
  5244. default:
  5245. return unsupported("Unknown R3ResolvedDependencyType: " + R3ResolvedDependencyType[dep.resolved]);
  5246. }
  5247. }
  5248. /**
  5249. * A helper function useful for extracting `R3DependencyMetadata` from a Render2
  5250. * `CompileTypeMetadata` instance.
  5251. */
  5252. function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {
  5253. var e_1, _a;
  5254. // Use the `CompileReflector` to look up references to some well-known Angular types. These will
  5255. // be compared with the token to statically determine whether the token has significance to
  5256. // Angular, and set the correct `R3ResolvedDependencyType` as a result.
  5257. var injectorRef = reflector.resolveExternalReference(Identifiers.Injector);
  5258. // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.
  5259. var deps = [];
  5260. try {
  5261. for (var _b = __values(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {
  5262. var dependency = _c.value;
  5263. if (dependency.token) {
  5264. var tokenRef = tokenReference(dependency.token);
  5265. var resolved = dependency.isAttribute ?
  5266. R3ResolvedDependencyType.Attribute :
  5267. R3ResolvedDependencyType.Token;
  5268. // In the case of most dependencies, the token will be a reference to a type. Sometimes,
  5269. // however, it can be a string, in the case of older Angular code or @Attribute injection.
  5270. var token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);
  5271. // Construct the dependency.
  5272. deps.push({
  5273. token: token,
  5274. resolved: resolved,
  5275. host: !!dependency.isHost,
  5276. optional: !!dependency.isOptional,
  5277. self: !!dependency.isSelf,
  5278. skipSelf: !!dependency.isSkipSelf,
  5279. });
  5280. }
  5281. else {
  5282. unsupported('dependency without a token');
  5283. }
  5284. }
  5285. }
  5286. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  5287. finally {
  5288. try {
  5289. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  5290. }
  5291. finally { if (e_1) throw e_1.error; }
  5292. }
  5293. return deps;
  5294. }
  5295. function makeErrorStmt(name) {
  5296. return new ThrowStmt(new InstantiateExpr(new ReadVarExpr('Error'), [
  5297. literal(name + " has a constructor which is not compatible with Dependency Injection. It should probably not be @Injectable().")
  5298. ]));
  5299. }
  5300. function isDelegatedMetadata(meta) {
  5301. return meta.delegateType !== undefined;
  5302. }
  5303. function isExpressionFactoryMetadata(meta) {
  5304. return meta.expression !== undefined;
  5305. }
  5306. /**
  5307. * @license
  5308. * Copyright Google Inc. All Rights Reserved.
  5309. *
  5310. * Use of this source code is governed by an MIT-style license that can be
  5311. * found in the LICENSE file at https://angular.io/license
  5312. */
  5313. /**
  5314. * Convert an object map with `Expression` values into a `LiteralMapExpr`.
  5315. */
  5316. function mapToMapExpression(map) {
  5317. var result = Object.keys(map).map(function (key) { return ({ key: key, value: map[key], quoted: false }); });
  5318. return literalMap(result);
  5319. }
  5320. /**
  5321. * Convert metadata into an `Expression` in the given `OutputContext`.
  5322. *
  5323. * This operation will handle arrays, references to symbols, or literal `null` or `undefined`.
  5324. */
  5325. function convertMetaToOutput(meta, ctx) {
  5326. if (Array.isArray(meta)) {
  5327. return literalArr(meta.map(function (entry) { return convertMetaToOutput(entry, ctx); }));
  5328. }
  5329. if (meta instanceof StaticSymbol) {
  5330. return ctx.importExpr(meta);
  5331. }
  5332. if (meta == null) {
  5333. return literal(meta);
  5334. }
  5335. throw new Error("Internal error: Unsupported or unknown metadata: " + meta);
  5336. }
  5337. function typeWithParameters(type, numParams) {
  5338. var params = null;
  5339. if (numParams > 0) {
  5340. params = [];
  5341. for (var i = 0; i < numParams; i++) {
  5342. params.push(DYNAMIC_TYPE);
  5343. }
  5344. }
  5345. return expressionType(type, null, params);
  5346. }
  5347. var ANIMATE_SYMBOL_PREFIX = '@';
  5348. function prepareSyntheticPropertyName(name) {
  5349. return "" + ANIMATE_SYMBOL_PREFIX + name;
  5350. }
  5351. function prepareSyntheticListenerName(name, phase) {
  5352. return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase;
  5353. }
  5354. function prepareSyntheticListenerFunctionName(name, phase) {
  5355. return "animation_" + name + "_" + phase;
  5356. }
  5357. /**
  5358. * @license
  5359. * Copyright Google Inc. All Rights Reserved.
  5360. *
  5361. * Use of this source code is governed by an MIT-style license that can be
  5362. * found in the LICENSE file at https://angular.io/license
  5363. */
  5364. function compileInjectable(meta) {
  5365. var result = null;
  5366. var factoryMeta = {
  5367. name: meta.name,
  5368. type: meta.type,
  5369. deps: meta.ctorDeps,
  5370. injectFn: Identifiers.inject,
  5371. };
  5372. if (meta.useClass !== undefined) {
  5373. // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
  5374. // used to instantiate the class with dependencies injected, or deps are not specified and
  5375. // the factory of the class is used to instantiate it.
  5376. //
  5377. // A special case exists for useClass: Type where Type is the injectable type itself and no
  5378. // deps are specified, in which case 'useClass' is effectively ignored.
  5379. var useClassOnSelf = meta.useClass.isEquivalent(meta.type);
  5380. var deps = undefined;
  5381. if (meta.userDeps !== undefined) {
  5382. deps = meta.userDeps;
  5383. }
  5384. if (deps !== undefined) {
  5385. // factory: () => new meta.useClass(...deps)
  5386. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
  5387. }
  5388. else if (useClassOnSelf) {
  5389. result = compileFactoryFunction(factoryMeta);
  5390. }
  5391. else {
  5392. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateType: R3FactoryDelegateType.Factory }));
  5393. }
  5394. }
  5395. else if (meta.useFactory !== undefined) {
  5396. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function }));
  5397. }
  5398. else if (meta.useValue !== undefined) {
  5399. // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
  5400. // client code because meta.useValue is an Expression which will be defined even if the actual
  5401. // value is undefined.
  5402. result = compileFactoryFunction(__assign({}, factoryMeta, { expression: meta.useValue }));
  5403. }
  5404. else if (meta.useExisting !== undefined) {
  5405. // useExisting is an `inject` call on the existing token.
  5406. result = compileFactoryFunction(__assign({}, factoryMeta, { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) }));
  5407. }
  5408. else {
  5409. result = compileFactoryFunction(factoryMeta);
  5410. }
  5411. var token = meta.type;
  5412. var providedIn = meta.providedIn;
  5413. var expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression({ token: token, factory: result.factory, providedIn: providedIn })]);
  5414. var type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type, meta.typeArgumentCount)]));
  5415. return {
  5416. expression: expression,
  5417. type: type,
  5418. statements: result.statements,
  5419. };
  5420. }
  5421. /**
  5422. * @license
  5423. * Copyright Google Inc. All Rights Reserved.
  5424. *
  5425. * Use of this source code is governed by an MIT-style license that can be
  5426. * found in the LICENSE file at https://angular.io/license
  5427. */
  5428. function assertArrayOfStrings(identifier, value) {
  5429. if (value == null) {
  5430. return;
  5431. }
  5432. if (!Array.isArray(value)) {
  5433. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  5434. }
  5435. for (var i = 0; i < value.length; i += 1) {
  5436. if (typeof value[i] !== 'string') {
  5437. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  5438. }
  5439. }
  5440. }
  5441. var UNUSABLE_INTERPOLATION_REGEXPS = [
  5442. /^\s*$/,
  5443. /[<>]/,
  5444. /^[{}]$/,
  5445. /&(#|[a-z])/i,
  5446. /^\/\//,
  5447. ];
  5448. function assertInterpolationSymbols(identifier, value) {
  5449. if (value != null && !(Array.isArray(value) && value.length == 2)) {
  5450. throw new Error("Expected '" + identifier + "' to be an array, [start, end].");
  5451. }
  5452. else if (value != null) {
  5453. var start_1 = value[0];
  5454. var end_1 = value[1];
  5455. // Check for unusable interpolation symbols
  5456. UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) {
  5457. if (regexp.test(start_1) || regexp.test(end_1)) {
  5458. throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol.");
  5459. }
  5460. });
  5461. }
  5462. }
  5463. /**
  5464. * @license
  5465. * Copyright Google Inc. All Rights Reserved.
  5466. *
  5467. * Use of this source code is governed by an MIT-style license that can be
  5468. * found in the LICENSE file at https://angular.io/license
  5469. */
  5470. var InterpolationConfig = /** @class */ (function () {
  5471. function InterpolationConfig(start, end) {
  5472. this.start = start;
  5473. this.end = end;
  5474. }
  5475. InterpolationConfig.fromArray = function (markers) {
  5476. if (!markers) {
  5477. return DEFAULT_INTERPOLATION_CONFIG;
  5478. }
  5479. assertInterpolationSymbols('interpolation', markers);
  5480. return new InterpolationConfig(markers[0], markers[1]);
  5481. };
  5482. return InterpolationConfig;
  5483. }());
  5484. var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
  5485. /**
  5486. * @license
  5487. * Copyright Google Inc. All Rights Reserved.
  5488. *
  5489. * Use of this source code is governed by an MIT-style license that can be
  5490. * found in the LICENSE file at https://angular.io/license
  5491. */
  5492. // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  5493. var VERSION = 3;
  5494. var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
  5495. var SourceMapGenerator = /** @class */ (function () {
  5496. function SourceMapGenerator(file) {
  5497. if (file === void 0) { file = null; }
  5498. this.file = file;
  5499. this.sourcesContent = new Map();
  5500. this.lines = [];
  5501. this.lastCol0 = 0;
  5502. this.hasMappings = false;
  5503. }
  5504. // The content is `null` when the content is expected to be loaded using the URL
  5505. SourceMapGenerator.prototype.addSource = function (url, content) {
  5506. if (content === void 0) { content = null; }
  5507. if (!this.sourcesContent.has(url)) {
  5508. this.sourcesContent.set(url, content);
  5509. }
  5510. return this;
  5511. };
  5512. SourceMapGenerator.prototype.addLine = function () {
  5513. this.lines.push([]);
  5514. this.lastCol0 = 0;
  5515. return this;
  5516. };
  5517. SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
  5518. if (!this.currentLine) {
  5519. throw new Error("A line must be added before mappings can be added");
  5520. }
  5521. if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
  5522. throw new Error("Unknown source file \"" + sourceUrl + "\"");
  5523. }
  5524. if (col0 == null) {
  5525. throw new Error("The column in the generated code must be provided");
  5526. }
  5527. if (col0 < this.lastCol0) {
  5528. throw new Error("Mapping should be added in output order");
  5529. }
  5530. if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
  5531. throw new Error("The source location must be provided when a source url is provided");
  5532. }
  5533. this.hasMappings = true;
  5534. this.lastCol0 = col0;
  5535. this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
  5536. return this;
  5537. };
  5538. Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
  5539. get: function () { return this.lines.slice(-1)[0]; },
  5540. enumerable: true,
  5541. configurable: true
  5542. });
  5543. SourceMapGenerator.prototype.toJSON = function () {
  5544. var _this = this;
  5545. if (!this.hasMappings) {
  5546. return null;
  5547. }
  5548. var sourcesIndex = new Map();
  5549. var sources = [];
  5550. var sourcesContent = [];
  5551. Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
  5552. sourcesIndex.set(url, i);
  5553. sources.push(url);
  5554. sourcesContent.push(_this.sourcesContent.get(url) || null);
  5555. });
  5556. var mappings = '';
  5557. var lastCol0 = 0;
  5558. var lastSourceIndex = 0;
  5559. var lastSourceLine0 = 0;
  5560. var lastSourceCol0 = 0;
  5561. this.lines.forEach(function (segments) {
  5562. lastCol0 = 0;
  5563. mappings += segments
  5564. .map(function (segment) {
  5565. // zero-based starting column of the line in the generated code
  5566. var segAsStr = toBase64VLQ(segment.col0 - lastCol0);
  5567. lastCol0 = segment.col0;
  5568. if (segment.sourceUrl != null) {
  5569. // zero-based index into the “sources” list
  5570. segAsStr +=
  5571. toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
  5572. lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
  5573. // the zero-based starting line in the original source
  5574. segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
  5575. lastSourceLine0 = segment.sourceLine0;
  5576. // the zero-based starting column in the original source
  5577. segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
  5578. lastSourceCol0 = segment.sourceCol0;
  5579. }
  5580. return segAsStr;
  5581. })
  5582. .join(',');
  5583. mappings += ';';
  5584. });
  5585. mappings = mappings.slice(0, -1);
  5586. return {
  5587. 'file': this.file || '',
  5588. 'version': VERSION,
  5589. 'sourceRoot': '',
  5590. 'sources': sources,
  5591. 'sourcesContent': sourcesContent,
  5592. 'mappings': mappings,
  5593. };
  5594. };
  5595. SourceMapGenerator.prototype.toJsComment = function () {
  5596. return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
  5597. '';
  5598. };
  5599. return SourceMapGenerator;
  5600. }());
  5601. function toBase64String(value) {
  5602. var b64 = '';
  5603. value = utf8Encode(value);
  5604. for (var i = 0; i < value.length;) {
  5605. var i1 = value.charCodeAt(i++);
  5606. var i2 = value.charCodeAt(i++);
  5607. var i3 = value.charCodeAt(i++);
  5608. b64 += toBase64Digit(i1 >> 2);
  5609. b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
  5610. b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
  5611. b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
  5612. }
  5613. return b64;
  5614. }
  5615. function toBase64VLQ(value) {
  5616. value = value < 0 ? ((-value) << 1) + 1 : value << 1;
  5617. var out = '';
  5618. do {
  5619. var digit = value & 31;
  5620. value = value >> 5;
  5621. if (value > 0) {
  5622. digit = digit | 32;
  5623. }
  5624. out += toBase64Digit(digit);
  5625. } while (value > 0);
  5626. return out;
  5627. }
  5628. var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5629. function toBase64Digit(value) {
  5630. if (value < 0 || value >= 64) {
  5631. throw new Error("Can only encode value in the range [0, 63]");
  5632. }
  5633. return B64_DIGITS[value];
  5634. }
  5635. /**
  5636. * @license
  5637. * Copyright Google Inc. All Rights Reserved.
  5638. *
  5639. * Use of this source code is governed by an MIT-style license that can be
  5640. * found in the LICENSE file at https://angular.io/license
  5641. */
  5642. var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
  5643. var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
  5644. var _INDENT_WITH = ' ';
  5645. var CATCH_ERROR_VAR$1 = variable('error', null, null);
  5646. var CATCH_STACK_VAR$1 = variable('stack', null, null);
  5647. var _EmittedLine = /** @class */ (function () {
  5648. function _EmittedLine(indent) {
  5649. this.indent = indent;
  5650. this.partsLength = 0;
  5651. this.parts = [];
  5652. this.srcSpans = [];
  5653. }
  5654. return _EmittedLine;
  5655. }());
  5656. var EmitterVisitorContext = /** @class */ (function () {
  5657. function EmitterVisitorContext(_indent) {
  5658. this._indent = _indent;
  5659. this._classes = [];
  5660. this._preambleLineCount = 0;
  5661. this._lines = [new _EmittedLine(_indent)];
  5662. }
  5663. EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); };
  5664. Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
  5665. get: function () { return this._lines[this._lines.length - 1]; },
  5666. enumerable: true,
  5667. configurable: true
  5668. });
  5669. EmitterVisitorContext.prototype.println = function (from, lastPart) {
  5670. if (lastPart === void 0) { lastPart = ''; }
  5671. this.print(from || null, lastPart, true);
  5672. };
  5673. EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; };
  5674. EmitterVisitorContext.prototype.lineLength = function () {
  5675. return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
  5676. };
  5677. EmitterVisitorContext.prototype.print = function (from, part, newLine) {
  5678. if (newLine === void 0) { newLine = false; }
  5679. if (part.length > 0) {
  5680. this._currentLine.parts.push(part);
  5681. this._currentLine.partsLength += part.length;
  5682. this._currentLine.srcSpans.push(from && from.sourceSpan || null);
  5683. }
  5684. if (newLine) {
  5685. this._lines.push(new _EmittedLine(this._indent));
  5686. }
  5687. };
  5688. EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
  5689. if (this.lineIsEmpty()) {
  5690. this._lines.pop();
  5691. }
  5692. };
  5693. EmitterVisitorContext.prototype.incIndent = function () {
  5694. this._indent++;
  5695. if (this.lineIsEmpty()) {
  5696. this._currentLine.indent = this._indent;
  5697. }
  5698. };
  5699. EmitterVisitorContext.prototype.decIndent = function () {
  5700. this._indent--;
  5701. if (this.lineIsEmpty()) {
  5702. this._currentLine.indent = this._indent;
  5703. }
  5704. };
  5705. EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); };
  5706. EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); };
  5707. Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
  5708. get: function () {
  5709. return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
  5710. },
  5711. enumerable: true,
  5712. configurable: true
  5713. });
  5714. EmitterVisitorContext.prototype.toSource = function () {
  5715. return this.sourceLines
  5716. .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
  5717. .join('\n');
  5718. };
  5719. EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) {
  5720. if (startsAtLine === void 0) { startsAtLine = 0; }
  5721. var map = new SourceMapGenerator(genFilePath);
  5722. var firstOffsetMapped = false;
  5723. var mapFirstOffsetIfNeeded = function () {
  5724. if (!firstOffsetMapped) {
  5725. // Add a single space so that tools won't try to load the file from disk.
  5726. // Note: We are using virtual urls like `ng:///`, so we have to
  5727. // provide a content here.
  5728. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
  5729. firstOffsetMapped = true;
  5730. }
  5731. };
  5732. for (var i = 0; i < startsAtLine; i++) {
  5733. map.addLine();
  5734. mapFirstOffsetIfNeeded();
  5735. }
  5736. this.sourceLines.forEach(function (line, lineIdx) {
  5737. map.addLine();
  5738. var spans = line.srcSpans;
  5739. var parts = line.parts;
  5740. var col0 = line.indent * _INDENT_WITH.length;
  5741. var spanIdx = 0;
  5742. // skip leading parts without source spans
  5743. while (spanIdx < spans.length && !spans[spanIdx]) {
  5744. col0 += parts[spanIdx].length;
  5745. spanIdx++;
  5746. }
  5747. if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
  5748. firstOffsetMapped = true;
  5749. }
  5750. else {
  5751. mapFirstOffsetIfNeeded();
  5752. }
  5753. while (spanIdx < spans.length) {
  5754. var span = spans[spanIdx];
  5755. var source = span.start.file;
  5756. var sourceLine = span.start.line;
  5757. var sourceCol = span.start.col;
  5758. map.addSource(source.url, source.content)
  5759. .addMapping(col0, source.url, sourceLine, sourceCol);
  5760. col0 += parts[spanIdx].length;
  5761. spanIdx++;
  5762. // assign parts without span or the same span to the previous segment
  5763. while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
  5764. col0 += parts[spanIdx].length;
  5765. spanIdx++;
  5766. }
  5767. }
  5768. });
  5769. return map;
  5770. };
  5771. EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; };
  5772. EmitterVisitorContext.prototype.spanOf = function (line, column) {
  5773. var emittedLine = this._lines[line - this._preambleLineCount];
  5774. if (emittedLine) {
  5775. var columnsLeft = column - _createIndent(emittedLine.indent).length;
  5776. for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
  5777. var part = emittedLine.parts[partIndex];
  5778. if (part.length > columnsLeft) {
  5779. return emittedLine.srcSpans[partIndex];
  5780. }
  5781. columnsLeft -= part.length;
  5782. }
  5783. }
  5784. return null;
  5785. };
  5786. Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
  5787. get: function () {
  5788. if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
  5789. return this._lines.slice(0, -1);
  5790. }
  5791. return this._lines;
  5792. },
  5793. enumerable: true,
  5794. configurable: true
  5795. });
  5796. return EmitterVisitorContext;
  5797. }());
  5798. var AbstractEmitterVisitor = /** @class */ (function () {
  5799. function AbstractEmitterVisitor(_escapeDollarInStrings) {
  5800. this._escapeDollarInStrings = _escapeDollarInStrings;
  5801. }
  5802. AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
  5803. stmt.expr.visitExpression(this, ctx);
  5804. ctx.println(stmt, ';');
  5805. return null;
  5806. };
  5807. AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
  5808. ctx.print(stmt, "return ");
  5809. stmt.value.visitExpression(this, ctx);
  5810. ctx.println(stmt, ';');
  5811. return null;
  5812. };
  5813. AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
  5814. ctx.print(stmt, "if (");
  5815. stmt.condition.visitExpression(this, ctx);
  5816. ctx.print(stmt, ") {");
  5817. var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
  5818. if (stmt.trueCase.length <= 1 && !hasElseCase) {
  5819. ctx.print(stmt, " ");
  5820. this.visitAllStatements(stmt.trueCase, ctx);
  5821. ctx.removeEmptyLastLine();
  5822. ctx.print(stmt, " ");
  5823. }
  5824. else {
  5825. ctx.println();
  5826. ctx.incIndent();
  5827. this.visitAllStatements(stmt.trueCase, ctx);
  5828. ctx.decIndent();
  5829. if (hasElseCase) {
  5830. ctx.println(stmt, "} else {");
  5831. ctx.incIndent();
  5832. this.visitAllStatements(stmt.falseCase, ctx);
  5833. ctx.decIndent();
  5834. }
  5835. }
  5836. ctx.println(stmt, "}");
  5837. return null;
  5838. };
  5839. AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
  5840. ctx.print(stmt, "throw ");
  5841. stmt.error.visitExpression(this, ctx);
  5842. ctx.println(stmt, ";");
  5843. return null;
  5844. };
  5845. AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) {
  5846. if (stmt.multiline) {
  5847. ctx.println(stmt, "/* " + stmt.comment + " */");
  5848. }
  5849. else {
  5850. stmt.comment.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); });
  5851. }
  5852. return null;
  5853. };
  5854. AbstractEmitterVisitor.prototype.visitJSDocCommentStmt = function (stmt, ctx) {
  5855. ctx.println(stmt, "/*" + stmt.toString() + "*/");
  5856. return null;
  5857. };
  5858. AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
  5859. var lineWasEmpty = ctx.lineIsEmpty();
  5860. if (!lineWasEmpty) {
  5861. ctx.print(expr, '(');
  5862. }
  5863. ctx.print(expr, expr.name + " = ");
  5864. expr.value.visitExpression(this, ctx);
  5865. if (!lineWasEmpty) {
  5866. ctx.print(expr, ')');
  5867. }
  5868. return null;
  5869. };
  5870. AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
  5871. var lineWasEmpty = ctx.lineIsEmpty();
  5872. if (!lineWasEmpty) {
  5873. ctx.print(expr, '(');
  5874. }
  5875. expr.receiver.visitExpression(this, ctx);
  5876. ctx.print(expr, "[");
  5877. expr.index.visitExpression(this, ctx);
  5878. ctx.print(expr, "] = ");
  5879. expr.value.visitExpression(this, ctx);
  5880. if (!lineWasEmpty) {
  5881. ctx.print(expr, ')');
  5882. }
  5883. return null;
  5884. };
  5885. AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
  5886. var lineWasEmpty = ctx.lineIsEmpty();
  5887. if (!lineWasEmpty) {
  5888. ctx.print(expr, '(');
  5889. }
  5890. expr.receiver.visitExpression(this, ctx);
  5891. ctx.print(expr, "." + expr.name + " = ");
  5892. expr.value.visitExpression(this, ctx);
  5893. if (!lineWasEmpty) {
  5894. ctx.print(expr, ')');
  5895. }
  5896. return null;
  5897. };
  5898. AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  5899. expr.receiver.visitExpression(this, ctx);
  5900. var name = expr.name;
  5901. if (expr.builtin != null) {
  5902. name = this.getBuiltinMethodName(expr.builtin);
  5903. if (name == null) {
  5904. // some builtins just mean to skip the call.
  5905. return null;
  5906. }
  5907. }
  5908. ctx.print(expr, "." + name + "(");
  5909. this.visitAllExpressions(expr.args, ctx, ",");
  5910. ctx.print(expr, ")");
  5911. return null;
  5912. };
  5913. AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  5914. expr.fn.visitExpression(this, ctx);
  5915. ctx.print(expr, "(");
  5916. this.visitAllExpressions(expr.args, ctx, ',');
  5917. ctx.print(expr, ")");
  5918. return null;
  5919. };
  5920. AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  5921. throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
  5922. };
  5923. AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) {
  5924. ctx.print(expr, 'typeof ');
  5925. expr.expr.visitExpression(this, ctx);
  5926. };
  5927. AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  5928. var varName = ast.name;
  5929. if (ast.builtin != null) {
  5930. switch (ast.builtin) {
  5931. case BuiltinVar.Super:
  5932. varName = 'super';
  5933. break;
  5934. case BuiltinVar.This:
  5935. varName = 'this';
  5936. break;
  5937. case BuiltinVar.CatchError:
  5938. varName = CATCH_ERROR_VAR$1.name;
  5939. break;
  5940. case BuiltinVar.CatchStack:
  5941. varName = CATCH_STACK_VAR$1.name;
  5942. break;
  5943. default:
  5944. throw new Error("Unknown builtin variable " + ast.builtin);
  5945. }
  5946. }
  5947. ctx.print(ast, varName);
  5948. return null;
  5949. };
  5950. AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  5951. ctx.print(ast, "new ");
  5952. ast.classExpr.visitExpression(this, ctx);
  5953. ctx.print(ast, "(");
  5954. this.visitAllExpressions(ast.args, ctx, ',');
  5955. ctx.print(ast, ")");
  5956. return null;
  5957. };
  5958. AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  5959. var value = ast.value;
  5960. if (typeof value === 'string') {
  5961. ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
  5962. }
  5963. else {
  5964. ctx.print(ast, "" + value);
  5965. }
  5966. return null;
  5967. };
  5968. AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
  5969. ctx.print(ast, "(");
  5970. ast.condition.visitExpression(this, ctx);
  5971. ctx.print(ast, '? ');
  5972. ast.trueCase.visitExpression(this, ctx);
  5973. ctx.print(ast, ': ');
  5974. ast.falseCase.visitExpression(this, ctx);
  5975. ctx.print(ast, ")");
  5976. return null;
  5977. };
  5978. AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
  5979. ctx.print(ast, '!');
  5980. ast.condition.visitExpression(this, ctx);
  5981. return null;
  5982. };
  5983. AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  5984. ast.condition.visitExpression(this, ctx);
  5985. return null;
  5986. };
  5987. AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  5988. var opStr;
  5989. switch (ast.operator) {
  5990. case BinaryOperator.Equals:
  5991. opStr = '==';
  5992. break;
  5993. case BinaryOperator.Identical:
  5994. opStr = '===';
  5995. break;
  5996. case BinaryOperator.NotEquals:
  5997. opStr = '!=';
  5998. break;
  5999. case BinaryOperator.NotIdentical:
  6000. opStr = '!==';
  6001. break;
  6002. case BinaryOperator.And:
  6003. opStr = '&&';
  6004. break;
  6005. case BinaryOperator.BitwiseAnd:
  6006. opStr = '&';
  6007. break;
  6008. case BinaryOperator.Or:
  6009. opStr = '||';
  6010. break;
  6011. case BinaryOperator.Plus:
  6012. opStr = '+';
  6013. break;
  6014. case BinaryOperator.Minus:
  6015. opStr = '-';
  6016. break;
  6017. case BinaryOperator.Divide:
  6018. opStr = '/';
  6019. break;
  6020. case BinaryOperator.Multiply:
  6021. opStr = '*';
  6022. break;
  6023. case BinaryOperator.Modulo:
  6024. opStr = '%';
  6025. break;
  6026. case BinaryOperator.Lower:
  6027. opStr = '<';
  6028. break;
  6029. case BinaryOperator.LowerEquals:
  6030. opStr = '<=';
  6031. break;
  6032. case BinaryOperator.Bigger:
  6033. opStr = '>';
  6034. break;
  6035. case BinaryOperator.BiggerEquals:
  6036. opStr = '>=';
  6037. break;
  6038. default:
  6039. throw new Error("Unknown operator " + ast.operator);
  6040. }
  6041. if (ast.parens)
  6042. ctx.print(ast, "(");
  6043. ast.lhs.visitExpression(this, ctx);
  6044. ctx.print(ast, " " + opStr + " ");
  6045. ast.rhs.visitExpression(this, ctx);
  6046. if (ast.parens)
  6047. ctx.print(ast, ")");
  6048. return null;
  6049. };
  6050. AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
  6051. ast.receiver.visitExpression(this, ctx);
  6052. ctx.print(ast, ".");
  6053. ctx.print(ast, ast.name);
  6054. return null;
  6055. };
  6056. AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
  6057. ast.receiver.visitExpression(this, ctx);
  6058. ctx.print(ast, "[");
  6059. ast.index.visitExpression(this, ctx);
  6060. ctx.print(ast, "]");
  6061. return null;
  6062. };
  6063. AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  6064. ctx.print(ast, "[");
  6065. this.visitAllExpressions(ast.entries, ctx, ',');
  6066. ctx.print(ast, "]");
  6067. return null;
  6068. };
  6069. AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
  6070. var _this = this;
  6071. ctx.print(ast, "{");
  6072. this.visitAllObjects(function (entry) {
  6073. ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":");
  6074. entry.value.visitExpression(_this, ctx);
  6075. }, ast.entries, ctx, ',');
  6076. ctx.print(ast, "}");
  6077. return null;
  6078. };
  6079. AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
  6080. ctx.print(ast, '(');
  6081. this.visitAllExpressions(ast.parts, ctx, ',');
  6082. ctx.print(ast, ')');
  6083. return null;
  6084. };
  6085. AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) {
  6086. var _this = this;
  6087. this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator);
  6088. };
  6089. AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) {
  6090. var incrementedIndent = false;
  6091. for (var i = 0; i < expressions.length; i++) {
  6092. if (i > 0) {
  6093. if (ctx.lineLength() > 80) {
  6094. ctx.print(null, separator, true);
  6095. if (!incrementedIndent) {
  6096. // continuation are marked with double indent.
  6097. ctx.incIndent();
  6098. ctx.incIndent();
  6099. incrementedIndent = true;
  6100. }
  6101. }
  6102. else {
  6103. ctx.print(null, separator, false);
  6104. }
  6105. }
  6106. handler(expressions[i]);
  6107. }
  6108. if (incrementedIndent) {
  6109. // continuation are marked with double indent.
  6110. ctx.decIndent();
  6111. ctx.decIndent();
  6112. }
  6113. };
  6114. AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
  6115. var _this = this;
  6116. statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
  6117. };
  6118. return AbstractEmitterVisitor;
  6119. }());
  6120. function escapeIdentifier(input, escapeDollar, alwaysQuote) {
  6121. if (alwaysQuote === void 0) { alwaysQuote = true; }
  6122. if (input == null) {
  6123. return null;
  6124. }
  6125. var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
  6126. var match = [];
  6127. for (var _i = 0; _i < arguments.length; _i++) {
  6128. match[_i] = arguments[_i];
  6129. }
  6130. if (match[0] == '$') {
  6131. return escapeDollar ? '\\$' : '$';
  6132. }
  6133. else if (match[0] == '\n') {
  6134. return '\\n';
  6135. }
  6136. else if (match[0] == '\r') {
  6137. return '\\r';
  6138. }
  6139. else {
  6140. return "\\" + match[0];
  6141. }
  6142. });
  6143. var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
  6144. return requiresQuotes ? "'" + body + "'" : body;
  6145. }
  6146. function _createIndent(count) {
  6147. var res = '';
  6148. for (var i = 0; i < count; i++) {
  6149. res += _INDENT_WITH;
  6150. }
  6151. return res;
  6152. }
  6153. /**
  6154. * @license
  6155. * Copyright Google Inc. All Rights Reserved.
  6156. *
  6157. * Use of this source code is governed by an MIT-style license that can be
  6158. * found in the LICENSE file at https://angular.io/license
  6159. */
  6160. var AbstractJsEmitterVisitor = /** @class */ (function (_super) {
  6161. __extends(AbstractJsEmitterVisitor, _super);
  6162. function AbstractJsEmitterVisitor() {
  6163. return _super.call(this, false) || this;
  6164. }
  6165. AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  6166. var _this = this;
  6167. ctx.pushClass(stmt);
  6168. this._visitClassConstructor(stmt, ctx);
  6169. if (stmt.parent != null) {
  6170. ctx.print(stmt, stmt.name + ".prototype = Object.create(");
  6171. stmt.parent.visitExpression(this, ctx);
  6172. ctx.println(stmt, ".prototype);");
  6173. }
  6174. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); });
  6175. stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); });
  6176. ctx.popClass();
  6177. return null;
  6178. };
  6179. AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  6180. ctx.print(stmt, "function " + stmt.name + "(");
  6181. if (stmt.constructorMethod != null) {
  6182. this._visitParams(stmt.constructorMethod.params, ctx);
  6183. }
  6184. ctx.println(stmt, ") {");
  6185. ctx.incIndent();
  6186. if (stmt.constructorMethod != null) {
  6187. if (stmt.constructorMethod.body.length > 0) {
  6188. ctx.println(stmt, "var self = this;");
  6189. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  6190. }
  6191. }
  6192. ctx.decIndent();
  6193. ctx.println(stmt, "}");
  6194. };
  6195. AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) {
  6196. ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {");
  6197. ctx.incIndent();
  6198. if (getter.body.length > 0) {
  6199. ctx.println(stmt, "var self = this;");
  6200. this.visitAllStatements(getter.body, ctx);
  6201. }
  6202. ctx.decIndent();
  6203. ctx.println(stmt, "}});");
  6204. };
  6205. AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) {
  6206. ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function(");
  6207. this._visitParams(method.params, ctx);
  6208. ctx.println(stmt, ") {");
  6209. ctx.incIndent();
  6210. if (method.body.length > 0) {
  6211. ctx.println(stmt, "var self = this;");
  6212. this.visitAllStatements(method.body, ctx);
  6213. }
  6214. ctx.decIndent();
  6215. ctx.println(stmt, "};");
  6216. };
  6217. AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6218. throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
  6219. };
  6220. AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  6221. if (ast.builtin === BuiltinVar.This) {
  6222. ctx.print(ast, 'self');
  6223. }
  6224. else if (ast.builtin === BuiltinVar.Super) {
  6225. throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!");
  6226. }
  6227. else {
  6228. _super.prototype.visitReadVarExpr.call(this, ast, ctx);
  6229. }
  6230. return null;
  6231. };
  6232. AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  6233. ctx.print(stmt, "var " + stmt.name);
  6234. if (stmt.value) {
  6235. ctx.print(stmt, ' = ');
  6236. stmt.value.visitExpression(this, ctx);
  6237. }
  6238. ctx.println(stmt, ";");
  6239. return null;
  6240. };
  6241. AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  6242. ast.value.visitExpression(this, ctx);
  6243. return null;
  6244. };
  6245. AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  6246. var fnExpr = expr.fn;
  6247. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
  6248. ctx.currentClass.parent.visitExpression(this, ctx);
  6249. ctx.print(expr, ".call(this");
  6250. if (expr.args.length > 0) {
  6251. ctx.print(expr, ", ");
  6252. this.visitAllExpressions(expr.args, ctx, ',');
  6253. }
  6254. ctx.print(expr, ")");
  6255. }
  6256. else {
  6257. _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx);
  6258. }
  6259. return null;
  6260. };
  6261. AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  6262. ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "(");
  6263. this._visitParams(ast.params, ctx);
  6264. ctx.println(ast, ") {");
  6265. ctx.incIndent();
  6266. this.visitAllStatements(ast.statements, ctx);
  6267. ctx.decIndent();
  6268. ctx.print(ast, "}");
  6269. return null;
  6270. };
  6271. AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  6272. ctx.print(stmt, "function " + stmt.name + "(");
  6273. this._visitParams(stmt.params, ctx);
  6274. ctx.println(stmt, ") {");
  6275. ctx.incIndent();
  6276. this.visitAllStatements(stmt.statements, ctx);
  6277. ctx.decIndent();
  6278. ctx.println(stmt, "}");
  6279. return null;
  6280. };
  6281. AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  6282. ctx.println(stmt, "try {");
  6283. ctx.incIndent();
  6284. this.visitAllStatements(stmt.bodyStmts, ctx);
  6285. ctx.decIndent();
  6286. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  6287. ctx.incIndent();
  6288. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
  6289. StmtModifier.Final
  6290. ])].concat(stmt.catchStmts);
  6291. this.visitAllStatements(catchStmts, ctx);
  6292. ctx.decIndent();
  6293. ctx.println(stmt, "}");
  6294. return null;
  6295. };
  6296. AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  6297. this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ',');
  6298. };
  6299. AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  6300. var name;
  6301. switch (method) {
  6302. case BuiltinMethod.ConcatArray:
  6303. name = 'concat';
  6304. break;
  6305. case BuiltinMethod.SubscribeObservable:
  6306. name = 'subscribe';
  6307. break;
  6308. case BuiltinMethod.Bind:
  6309. name = 'bind';
  6310. break;
  6311. default:
  6312. throw new Error("Unknown builtin method: " + method);
  6313. }
  6314. return name;
  6315. };
  6316. return AbstractJsEmitterVisitor;
  6317. }(AbstractEmitterVisitor));
  6318. /**
  6319. * @license
  6320. * Copyright Google Inc. All Rights Reserved.
  6321. *
  6322. * Use of this source code is governed by an MIT-style license that can be
  6323. * found in the LICENSE file at https://angular.io/license
  6324. */
  6325. /**
  6326. * A helper class to manage the evaluation of JIT generated code.
  6327. */
  6328. var JitEvaluator = /** @class */ (function () {
  6329. function JitEvaluator() {
  6330. }
  6331. /**
  6332. *
  6333. * @param sourceUrl The URL of the generated code.
  6334. * @param statements An array of Angular statement AST nodes to be evaluated.
  6335. * @param reflector A helper used when converting the statements to executable code.
  6336. * @param createSourceMaps If true then create a source-map for the generated code and include it
  6337. * inline as a source-map comment.
  6338. * @returns A map of all the variables in the generated code.
  6339. */
  6340. JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) {
  6341. var converter = new JitEmitterVisitor(reflector);
  6342. var ctx = EmitterVisitorContext.createRoot();
  6343. // Ensure generated code is in strict mode
  6344. if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
  6345. statements = __spread([
  6346. literal('use strict').toStmt()
  6347. ], statements);
  6348. }
  6349. converter.visitAllStatements(statements, ctx);
  6350. converter.createReturnStmt(ctx);
  6351. return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
  6352. };
  6353. /**
  6354. * Evaluate a piece of JIT generated code.
  6355. * @param sourceUrl The URL of this generated code.
  6356. * @param ctx A context object that contains an AST of the code to be evaluated.
  6357. * @param vars A map containing the names and values of variables that the evaluated code might
  6358. * reference.
  6359. * @param createSourceMap If true then create a source-map for the generated code and include it
  6360. * inline as a source-map comment.
  6361. * @returns The result of evaluating the code.
  6362. */
  6363. JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) {
  6364. var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl;
  6365. var fnArgNames = [];
  6366. var fnArgValues = [];
  6367. for (var argName in vars) {
  6368. fnArgValues.push(vars[argName]);
  6369. fnArgNames.push(argName);
  6370. }
  6371. if (createSourceMap) {
  6372. // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
  6373. // E.g. ```
  6374. // function anonymous(a,b,c
  6375. // /**/) { ... }```
  6376. // We don't want to hard code this fact, so we auto detect it via an empty function first.
  6377. var emptyFn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat('return null;'))))().toString();
  6378. var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
  6379. fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment();
  6380. }
  6381. var fn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat(fnBody))))();
  6382. return this.executeFunction(fn, fnArgValues);
  6383. };
  6384. /**
  6385. * Execute a JIT generated function by calling it.
  6386. *
  6387. * This method can be overridden in tests to capture the functions that are generated
  6388. * by this `JitEvaluator` class.
  6389. *
  6390. * @param fn A function to execute.
  6391. * @param args The arguments to pass to the function being executed.
  6392. * @returns The return value of the executed function.
  6393. */
  6394. JitEvaluator.prototype.executeFunction = function (fn, args) { return fn.apply(void 0, __spread(args)); };
  6395. return JitEvaluator;
  6396. }());
  6397. /**
  6398. * An Angular AST visitor that converts AST nodes into executable JavaScript code.
  6399. */
  6400. var JitEmitterVisitor = /** @class */ (function (_super) {
  6401. __extends(JitEmitterVisitor, _super);
  6402. function JitEmitterVisitor(reflector) {
  6403. var _this = _super.call(this) || this;
  6404. _this.reflector = reflector;
  6405. _this._evalArgNames = [];
  6406. _this._evalArgValues = [];
  6407. _this._evalExportedVars = [];
  6408. return _this;
  6409. }
  6410. JitEmitterVisitor.prototype.createReturnStmt = function (ctx) {
  6411. var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); })));
  6412. stmt.visitStatement(this, ctx);
  6413. };
  6414. JitEmitterVisitor.prototype.getArgs = function () {
  6415. var result = {};
  6416. for (var i = 0; i < this._evalArgNames.length; i++) {
  6417. result[this._evalArgNames[i]] = this._evalArgValues[i];
  6418. }
  6419. return result;
  6420. };
  6421. JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  6422. this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
  6423. return null;
  6424. };
  6425. JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6426. this._emitReferenceToExternal(ast, ast.node, ctx);
  6427. return null;
  6428. };
  6429. JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  6430. if (stmt.hasModifier(StmtModifier.Exported)) {
  6431. this._evalExportedVars.push(stmt.name);
  6432. }
  6433. return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx);
  6434. };
  6435. JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  6436. if (stmt.hasModifier(StmtModifier.Exported)) {
  6437. this._evalExportedVars.push(stmt.name);
  6438. }
  6439. return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx);
  6440. };
  6441. JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  6442. if (stmt.hasModifier(StmtModifier.Exported)) {
  6443. this._evalExportedVars.push(stmt.name);
  6444. }
  6445. return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx);
  6446. };
  6447. JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) {
  6448. var id = this._evalArgValues.indexOf(value);
  6449. if (id === -1) {
  6450. id = this._evalArgValues.length;
  6451. this._evalArgValues.push(value);
  6452. var name_1 = identifierName({ reference: value }) || 'val';
  6453. this._evalArgNames.push("jit_" + name_1 + "_" + id);
  6454. }
  6455. ctx.print(ast, this._evalArgNames[id]);
  6456. };
  6457. return JitEmitterVisitor;
  6458. }(AbstractJsEmitterVisitor));
  6459. function isUseStrictStatement(statement) {
  6460. return statement.isEquivalent(literal('use strict').toStmt());
  6461. }
  6462. /**
  6463. * @license
  6464. * Copyright Google Inc. All Rights Reserved.
  6465. *
  6466. * Use of this source code is governed by an MIT-style license that can be
  6467. * found in the LICENSE file at https://angular.io/license
  6468. */
  6469. /**
  6470. * Implementation of `CompileReflector` which resolves references to @angular/core
  6471. * symbols at runtime, according to a consumer-provided mapping.
  6472. *
  6473. * Only supports `resolveExternalReference`, all other methods throw.
  6474. */
  6475. var R3JitReflector = /** @class */ (function () {
  6476. function R3JitReflector(context) {
  6477. this.context = context;
  6478. }
  6479. R3JitReflector.prototype.resolveExternalReference = function (ref) {
  6480. // This reflector only handles @angular/core imports.
  6481. if (ref.moduleName !== '@angular/core') {
  6482. throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported.");
  6483. }
  6484. if (!this.context.hasOwnProperty(ref.name)) {
  6485. throw new Error("No value provided for @angular/core symbol '" + ref.name + "'.");
  6486. }
  6487. return this.context[ref.name];
  6488. };
  6489. R3JitReflector.prototype.parameters = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6490. R3JitReflector.prototype.annotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6491. R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6492. R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6493. R3JitReflector.prototype.propMetadata = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6494. R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) { throw new Error('Not implemented.'); };
  6495. R3JitReflector.prototype.guards = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6496. R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) { throw new Error('Not implemented.'); };
  6497. return R3JitReflector;
  6498. }());
  6499. /**
  6500. * @license
  6501. * Copyright Google Inc. All Rights Reserved.
  6502. *
  6503. * Use of this source code is governed by an MIT-style license that can be
  6504. * found in the LICENSE file at https://angular.io/license
  6505. */
  6506. /**
  6507. * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
  6508. */
  6509. function compileNgModule(meta) {
  6510. var moduleType = meta.type, bootstrap = meta.bootstrap, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, schemas = meta.schemas, containsForwardDecls = meta.containsForwardDecls, emitInline = meta.emitInline, id = meta.id;
  6511. var additionalStatements = [];
  6512. var definitionMap = {
  6513. type: moduleType
  6514. };
  6515. // Only generate the keys in the metadata if the arrays have values.
  6516. if (bootstrap.length) {
  6517. definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
  6518. }
  6519. // If requested to emit scope information inline, pass the declarations, imports and exports to
  6520. // the `ɵɵdefineNgModule` call. The JIT compilation uses this.
  6521. if (emitInline) {
  6522. if (declarations.length) {
  6523. definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
  6524. }
  6525. if (imports.length) {
  6526. definitionMap.imports = refsToArray(imports, containsForwardDecls);
  6527. }
  6528. if (exports.length) {
  6529. definitionMap.exports = refsToArray(exports, containsForwardDecls);
  6530. }
  6531. }
  6532. // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
  6533. // prevent tree-shaking of the declarations, imports and exports references.
  6534. else {
  6535. var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
  6536. if (setNgModuleScopeCall !== null) {
  6537. additionalStatements.push(setNgModuleScopeCall);
  6538. }
  6539. }
  6540. if (schemas && schemas.length) {
  6541. definitionMap.schemas = literalArr(schemas.map(function (ref) { return ref.value; }));
  6542. }
  6543. if (id) {
  6544. definitionMap.id = id;
  6545. }
  6546. var expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
  6547. var type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [
  6548. new ExpressionType(moduleType), tupleTypeOf(declarations), tupleTypeOf(imports),
  6549. tupleTypeOf(exports)
  6550. ]));
  6551. return { expression: expression, type: type, additionalStatements: additionalStatements };
  6552. }
  6553. /**
  6554. * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
  6555. * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
  6556. * such that the references to declarations, imports and exports may be elided causing these
  6557. * symbols to become tree-shakeable.
  6558. */
  6559. function generateSetNgModuleScopeCall(meta) {
  6560. var moduleType = meta.type, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls;
  6561. var scopeMap = {};
  6562. if (declarations.length) {
  6563. scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
  6564. }
  6565. if (imports.length) {
  6566. scopeMap.imports = refsToArray(imports, containsForwardDecls);
  6567. }
  6568. if (exports.length) {
  6569. scopeMap.exports = refsToArray(exports, containsForwardDecls);
  6570. }
  6571. if (Object.keys(scopeMap).length === 0) {
  6572. return null;
  6573. }
  6574. var fnCall = new InvokeFunctionExpr(
  6575. /* fn */ importExpr(Identifiers$1.setNgModuleScope),
  6576. /* args */ [moduleType, mapToMapExpression(scopeMap)],
  6577. /* type */ undefined,
  6578. /* sourceSpan */ undefined,
  6579. /* pure */ true);
  6580. return fnCall.toStmt();
  6581. }
  6582. function compileInjector(meta) {
  6583. var result = compileFactoryFunction({
  6584. name: meta.name,
  6585. type: meta.type,
  6586. deps: meta.deps,
  6587. injectFn: Identifiers$1.inject,
  6588. });
  6589. var definitionMap = {
  6590. factory: result.factory,
  6591. };
  6592. if (meta.providers !== null) {
  6593. definitionMap.providers = meta.providers;
  6594. }
  6595. if (meta.imports.length > 0) {
  6596. definitionMap.imports = literalArr(meta.imports);
  6597. }
  6598. var expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]);
  6599. var type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type)]));
  6600. return { expression: expression, type: type, statements: result.statements };
  6601. }
  6602. // TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations.
  6603. function compileNgModuleFromRender2(ctx, ngModule, injectableCompiler) {
  6604. var className = identifierName(ngModule.type);
  6605. var rawImports = ngModule.rawImports ? [ngModule.rawImports] : [];
  6606. var rawExports = ngModule.rawExports ? [ngModule.rawExports] : [];
  6607. var injectorDefArg = mapLiteral({
  6608. 'factory': injectableCompiler.factoryFor({ type: ngModule.type, symbol: ngModule.type.reference }, ctx),
  6609. 'providers': convertMetaToOutput(ngModule.rawProviders, ctx),
  6610. 'imports': convertMetaToOutput(__spread(rawImports, rawExports), ctx),
  6611. });
  6612. var injectorDef = importExpr(Identifiers$1.defineInjector).callFn([injectorDefArg]);
  6613. ctx.statements.push(new ClassStmt(
  6614. /* name */ className,
  6615. /* parent */ null,
  6616. /* fields */ [new ClassField(
  6617. /* name */ 'ngInjectorDef',
  6618. /* type */ INFERRED_TYPE,
  6619. /* modifiers */ [StmtModifier.Static],
  6620. /* initializer */ injectorDef)],
  6621. /* getters */ [],
  6622. /* constructorMethod */ new ClassMethod(null, [], []),
  6623. /* methods */ []));
  6624. }
  6625. function tupleTypeOf(exp) {
  6626. var types = exp.map(function (ref) { return typeofExpr(ref.type); });
  6627. return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
  6628. }
  6629. function refsToArray(refs, shouldForwardDeclare) {
  6630. var values = literalArr(refs.map(function (ref) { return ref.value; }));
  6631. return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
  6632. }
  6633. /**
  6634. * @license
  6635. * Copyright Google Inc. All Rights Reserved.
  6636. *
  6637. * Use of this source code is governed by an MIT-style license that can be
  6638. * found in the LICENSE file at https://angular.io/license
  6639. */
  6640. function compilePipeFromMetadata(metadata) {
  6641. var definitionMapValues = [];
  6642. // e.g. `name: 'myPipe'`
  6643. definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
  6644. // e.g. `type: MyPipe`
  6645. definitionMapValues.push({ key: 'type', value: metadata.type, quoted: false });
  6646. var templateFactory = compileFactoryFunction({
  6647. name: metadata.name,
  6648. type: metadata.type,
  6649. deps: metadata.deps,
  6650. injectFn: Identifiers$1.directiveInject,
  6651. });
  6652. definitionMapValues.push({ key: 'factory', value: templateFactory.factory, quoted: false });
  6653. // e.g. `pure: true`
  6654. definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
  6655. var expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]);
  6656. var type = new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [
  6657. typeWithParameters(metadata.type, metadata.typeArgumentCount),
  6658. new ExpressionType(new LiteralExpr(metadata.pipeName)),
  6659. ]));
  6660. return { expression: expression, type: type, statements: templateFactory.statements };
  6661. }
  6662. /**
  6663. * Write a pipe definition to the output context.
  6664. */
  6665. function compilePipeFromRender2(outputCtx, pipe, reflector) {
  6666. var name = identifierName(pipe.type);
  6667. if (!name) {
  6668. return error("Cannot resolve the name of " + pipe.type);
  6669. }
  6670. var metadata = {
  6671. name: name,
  6672. pipeName: pipe.name,
  6673. type: outputCtx.importExpr(pipe.type.reference),
  6674. typeArgumentCount: 0,
  6675. deps: dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector),
  6676. pure: pipe.pure,
  6677. };
  6678. var res = compilePipeFromMetadata(metadata);
  6679. var definitionField = outputCtx.constantPool.propertyNameOf(3 /* Pipe */);
  6680. outputCtx.statements.push(new ClassStmt(
  6681. /* name */ name,
  6682. /* parent */ null,
  6683. /* fields */ [new ClassField(
  6684. /* name */ definitionField,
  6685. /* type */ INFERRED_TYPE,
  6686. /* modifiers */ [StmtModifier.Static],
  6687. /* initializer */ res.expression)],
  6688. /* getters */ [],
  6689. /* constructorMethod */ new ClassMethod(null, [], []),
  6690. /* methods */ []));
  6691. }
  6692. /**
  6693. * @license
  6694. * Copyright Google Inc. All Rights Reserved.
  6695. *
  6696. * Use of this source code is governed by an MIT-style license that can be
  6697. * found in the LICENSE file at https://angular.io/license
  6698. */
  6699. var ParserError = /** @class */ (function () {
  6700. function ParserError(message, input, errLocation, ctxLocation) {
  6701. this.input = input;
  6702. this.errLocation = errLocation;
  6703. this.ctxLocation = ctxLocation;
  6704. this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation;
  6705. }
  6706. return ParserError;
  6707. }());
  6708. var ParseSpan = /** @class */ (function () {
  6709. function ParseSpan(start, end) {
  6710. this.start = start;
  6711. this.end = end;
  6712. }
  6713. return ParseSpan;
  6714. }());
  6715. var AST = /** @class */ (function () {
  6716. function AST(span) {
  6717. this.span = span;
  6718. }
  6719. AST.prototype.visit = function (visitor, context) {
  6720. if (context === void 0) { context = null; }
  6721. return null;
  6722. };
  6723. AST.prototype.toString = function () { return 'AST'; };
  6724. return AST;
  6725. }());
  6726. /**
  6727. * Represents a quoted expression of the form:
  6728. *
  6729. * quote = prefix `:` uninterpretedExpression
  6730. * prefix = identifier
  6731. * uninterpretedExpression = arbitrary string
  6732. *
  6733. * A quoted expression is meant to be pre-processed by an AST transformer that
  6734. * converts it into another AST that no longer contains quoted expressions.
  6735. * It is meant to allow third-party developers to extend Angular template
  6736. * expression language. The `uninterpretedExpression` part of the quote is
  6737. * therefore not interpreted by the Angular's own expression parser.
  6738. */
  6739. var Quote = /** @class */ (function (_super) {
  6740. __extends(Quote, _super);
  6741. function Quote(span, prefix, uninterpretedExpression, location) {
  6742. var _this = _super.call(this, span) || this;
  6743. _this.prefix = prefix;
  6744. _this.uninterpretedExpression = uninterpretedExpression;
  6745. _this.location = location;
  6746. return _this;
  6747. }
  6748. Quote.prototype.visit = function (visitor, context) {
  6749. if (context === void 0) { context = null; }
  6750. return visitor.visitQuote(this, context);
  6751. };
  6752. Quote.prototype.toString = function () { return 'Quote'; };
  6753. return Quote;
  6754. }(AST));
  6755. var EmptyExpr = /** @class */ (function (_super) {
  6756. __extends(EmptyExpr, _super);
  6757. function EmptyExpr() {
  6758. return _super !== null && _super.apply(this, arguments) || this;
  6759. }
  6760. EmptyExpr.prototype.visit = function (visitor, context) {
  6761. if (context === void 0) { context = null; }
  6762. // do nothing
  6763. };
  6764. return EmptyExpr;
  6765. }(AST));
  6766. var ImplicitReceiver = /** @class */ (function (_super) {
  6767. __extends(ImplicitReceiver, _super);
  6768. function ImplicitReceiver() {
  6769. return _super !== null && _super.apply(this, arguments) || this;
  6770. }
  6771. ImplicitReceiver.prototype.visit = function (visitor, context) {
  6772. if (context === void 0) { context = null; }
  6773. return visitor.visitImplicitReceiver(this, context);
  6774. };
  6775. return ImplicitReceiver;
  6776. }(AST));
  6777. /**
  6778. * Multiple expressions separated by a semicolon.
  6779. */
  6780. var Chain = /** @class */ (function (_super) {
  6781. __extends(Chain, _super);
  6782. function Chain(span, expressions) {
  6783. var _this = _super.call(this, span) || this;
  6784. _this.expressions = expressions;
  6785. return _this;
  6786. }
  6787. Chain.prototype.visit = function (visitor, context) {
  6788. if (context === void 0) { context = null; }
  6789. return visitor.visitChain(this, context);
  6790. };
  6791. return Chain;
  6792. }(AST));
  6793. var Conditional = /** @class */ (function (_super) {
  6794. __extends(Conditional, _super);
  6795. function Conditional(span, condition, trueExp, falseExp) {
  6796. var _this = _super.call(this, span) || this;
  6797. _this.condition = condition;
  6798. _this.trueExp = trueExp;
  6799. _this.falseExp = falseExp;
  6800. return _this;
  6801. }
  6802. Conditional.prototype.visit = function (visitor, context) {
  6803. if (context === void 0) { context = null; }
  6804. return visitor.visitConditional(this, context);
  6805. };
  6806. return Conditional;
  6807. }(AST));
  6808. var PropertyRead = /** @class */ (function (_super) {
  6809. __extends(PropertyRead, _super);
  6810. function PropertyRead(span, receiver, name) {
  6811. var _this = _super.call(this, span) || this;
  6812. _this.receiver = receiver;
  6813. _this.name = name;
  6814. return _this;
  6815. }
  6816. PropertyRead.prototype.visit = function (visitor, context) {
  6817. if (context === void 0) { context = null; }
  6818. return visitor.visitPropertyRead(this, context);
  6819. };
  6820. return PropertyRead;
  6821. }(AST));
  6822. var PropertyWrite = /** @class */ (function (_super) {
  6823. __extends(PropertyWrite, _super);
  6824. function PropertyWrite(span, receiver, name, value) {
  6825. var _this = _super.call(this, span) || this;
  6826. _this.receiver = receiver;
  6827. _this.name = name;
  6828. _this.value = value;
  6829. return _this;
  6830. }
  6831. PropertyWrite.prototype.visit = function (visitor, context) {
  6832. if (context === void 0) { context = null; }
  6833. return visitor.visitPropertyWrite(this, context);
  6834. };
  6835. return PropertyWrite;
  6836. }(AST));
  6837. var SafePropertyRead = /** @class */ (function (_super) {
  6838. __extends(SafePropertyRead, _super);
  6839. function SafePropertyRead(span, receiver, name) {
  6840. var _this = _super.call(this, span) || this;
  6841. _this.receiver = receiver;
  6842. _this.name = name;
  6843. return _this;
  6844. }
  6845. SafePropertyRead.prototype.visit = function (visitor, context) {
  6846. if (context === void 0) { context = null; }
  6847. return visitor.visitSafePropertyRead(this, context);
  6848. };
  6849. return SafePropertyRead;
  6850. }(AST));
  6851. var KeyedRead = /** @class */ (function (_super) {
  6852. __extends(KeyedRead, _super);
  6853. function KeyedRead(span, obj, key) {
  6854. var _this = _super.call(this, span) || this;
  6855. _this.obj = obj;
  6856. _this.key = key;
  6857. return _this;
  6858. }
  6859. KeyedRead.prototype.visit = function (visitor, context) {
  6860. if (context === void 0) { context = null; }
  6861. return visitor.visitKeyedRead(this, context);
  6862. };
  6863. return KeyedRead;
  6864. }(AST));
  6865. var KeyedWrite = /** @class */ (function (_super) {
  6866. __extends(KeyedWrite, _super);
  6867. function KeyedWrite(span, obj, key, value) {
  6868. var _this = _super.call(this, span) || this;
  6869. _this.obj = obj;
  6870. _this.key = key;
  6871. _this.value = value;
  6872. return _this;
  6873. }
  6874. KeyedWrite.prototype.visit = function (visitor, context) {
  6875. if (context === void 0) { context = null; }
  6876. return visitor.visitKeyedWrite(this, context);
  6877. };
  6878. return KeyedWrite;
  6879. }(AST));
  6880. var BindingPipe = /** @class */ (function (_super) {
  6881. __extends(BindingPipe, _super);
  6882. function BindingPipe(span, exp, name, args) {
  6883. var _this = _super.call(this, span) || this;
  6884. _this.exp = exp;
  6885. _this.name = name;
  6886. _this.args = args;
  6887. return _this;
  6888. }
  6889. BindingPipe.prototype.visit = function (visitor, context) {
  6890. if (context === void 0) { context = null; }
  6891. return visitor.visitPipe(this, context);
  6892. };
  6893. return BindingPipe;
  6894. }(AST));
  6895. var LiteralPrimitive = /** @class */ (function (_super) {
  6896. __extends(LiteralPrimitive, _super);
  6897. function LiteralPrimitive(span, value) {
  6898. var _this = _super.call(this, span) || this;
  6899. _this.value = value;
  6900. return _this;
  6901. }
  6902. LiteralPrimitive.prototype.visit = function (visitor, context) {
  6903. if (context === void 0) { context = null; }
  6904. return visitor.visitLiteralPrimitive(this, context);
  6905. };
  6906. return LiteralPrimitive;
  6907. }(AST));
  6908. var LiteralArray = /** @class */ (function (_super) {
  6909. __extends(LiteralArray, _super);
  6910. function LiteralArray(span, expressions) {
  6911. var _this = _super.call(this, span) || this;
  6912. _this.expressions = expressions;
  6913. return _this;
  6914. }
  6915. LiteralArray.prototype.visit = function (visitor, context) {
  6916. if (context === void 0) { context = null; }
  6917. return visitor.visitLiteralArray(this, context);
  6918. };
  6919. return LiteralArray;
  6920. }(AST));
  6921. var LiteralMap = /** @class */ (function (_super) {
  6922. __extends(LiteralMap, _super);
  6923. function LiteralMap(span, keys, values) {
  6924. var _this = _super.call(this, span) || this;
  6925. _this.keys = keys;
  6926. _this.values = values;
  6927. return _this;
  6928. }
  6929. LiteralMap.prototype.visit = function (visitor, context) {
  6930. if (context === void 0) { context = null; }
  6931. return visitor.visitLiteralMap(this, context);
  6932. };
  6933. return LiteralMap;
  6934. }(AST));
  6935. var Interpolation = /** @class */ (function (_super) {
  6936. __extends(Interpolation, _super);
  6937. function Interpolation(span, strings, expressions) {
  6938. var _this = _super.call(this, span) || this;
  6939. _this.strings = strings;
  6940. _this.expressions = expressions;
  6941. return _this;
  6942. }
  6943. Interpolation.prototype.visit = function (visitor, context) {
  6944. if (context === void 0) { context = null; }
  6945. return visitor.visitInterpolation(this, context);
  6946. };
  6947. return Interpolation;
  6948. }(AST));
  6949. var Binary = /** @class */ (function (_super) {
  6950. __extends(Binary, _super);
  6951. function Binary(span, operation, left, right) {
  6952. var _this = _super.call(this, span) || this;
  6953. _this.operation = operation;
  6954. _this.left = left;
  6955. _this.right = right;
  6956. return _this;
  6957. }
  6958. Binary.prototype.visit = function (visitor, context) {
  6959. if (context === void 0) { context = null; }
  6960. return visitor.visitBinary(this, context);
  6961. };
  6962. return Binary;
  6963. }(AST));
  6964. var PrefixNot = /** @class */ (function (_super) {
  6965. __extends(PrefixNot, _super);
  6966. function PrefixNot(span, expression) {
  6967. var _this = _super.call(this, span) || this;
  6968. _this.expression = expression;
  6969. return _this;
  6970. }
  6971. PrefixNot.prototype.visit = function (visitor, context) {
  6972. if (context === void 0) { context = null; }
  6973. return visitor.visitPrefixNot(this, context);
  6974. };
  6975. return PrefixNot;
  6976. }(AST));
  6977. var NonNullAssert = /** @class */ (function (_super) {
  6978. __extends(NonNullAssert, _super);
  6979. function NonNullAssert(span, expression) {
  6980. var _this = _super.call(this, span) || this;
  6981. _this.expression = expression;
  6982. return _this;
  6983. }
  6984. NonNullAssert.prototype.visit = function (visitor, context) {
  6985. if (context === void 0) { context = null; }
  6986. return visitor.visitNonNullAssert(this, context);
  6987. };
  6988. return NonNullAssert;
  6989. }(AST));
  6990. var MethodCall = /** @class */ (function (_super) {
  6991. __extends(MethodCall, _super);
  6992. function MethodCall(span, receiver, name, args) {
  6993. var _this = _super.call(this, span) || this;
  6994. _this.receiver = receiver;
  6995. _this.name = name;
  6996. _this.args = args;
  6997. return _this;
  6998. }
  6999. MethodCall.prototype.visit = function (visitor, context) {
  7000. if (context === void 0) { context = null; }
  7001. return visitor.visitMethodCall(this, context);
  7002. };
  7003. return MethodCall;
  7004. }(AST));
  7005. var SafeMethodCall = /** @class */ (function (_super) {
  7006. __extends(SafeMethodCall, _super);
  7007. function SafeMethodCall(span, receiver, name, args) {
  7008. var _this = _super.call(this, span) || this;
  7009. _this.receiver = receiver;
  7010. _this.name = name;
  7011. _this.args = args;
  7012. return _this;
  7013. }
  7014. SafeMethodCall.prototype.visit = function (visitor, context) {
  7015. if (context === void 0) { context = null; }
  7016. return visitor.visitSafeMethodCall(this, context);
  7017. };
  7018. return SafeMethodCall;
  7019. }(AST));
  7020. var FunctionCall = /** @class */ (function (_super) {
  7021. __extends(FunctionCall, _super);
  7022. function FunctionCall(span, target, args) {
  7023. var _this = _super.call(this, span) || this;
  7024. _this.target = target;
  7025. _this.args = args;
  7026. return _this;
  7027. }
  7028. FunctionCall.prototype.visit = function (visitor, context) {
  7029. if (context === void 0) { context = null; }
  7030. return visitor.visitFunctionCall(this, context);
  7031. };
  7032. return FunctionCall;
  7033. }(AST));
  7034. var ASTWithSource = /** @class */ (function (_super) {
  7035. __extends(ASTWithSource, _super);
  7036. function ASTWithSource(ast, source, location, errors) {
  7037. var _this = _super.call(this, new ParseSpan(0, source == null ? 0 : source.length)) || this;
  7038. _this.ast = ast;
  7039. _this.source = source;
  7040. _this.location = location;
  7041. _this.errors = errors;
  7042. return _this;
  7043. }
  7044. ASTWithSource.prototype.visit = function (visitor, context) {
  7045. if (context === void 0) { context = null; }
  7046. return this.ast.visit(visitor, context);
  7047. };
  7048. ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; };
  7049. return ASTWithSource;
  7050. }(AST));
  7051. var TemplateBinding = /** @class */ (function () {
  7052. function TemplateBinding(span, key, keyIsVar, name, expression) {
  7053. this.span = span;
  7054. this.key = key;
  7055. this.keyIsVar = keyIsVar;
  7056. this.name = name;
  7057. this.expression = expression;
  7058. }
  7059. return TemplateBinding;
  7060. }());
  7061. var NullAstVisitor = /** @class */ (function () {
  7062. function NullAstVisitor() {
  7063. }
  7064. NullAstVisitor.prototype.visitBinary = function (ast, context) { };
  7065. NullAstVisitor.prototype.visitChain = function (ast, context) { };
  7066. NullAstVisitor.prototype.visitConditional = function (ast, context) { };
  7067. NullAstVisitor.prototype.visitFunctionCall = function (ast, context) { };
  7068. NullAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { };
  7069. NullAstVisitor.prototype.visitInterpolation = function (ast, context) { };
  7070. NullAstVisitor.prototype.visitKeyedRead = function (ast, context) { };
  7071. NullAstVisitor.prototype.visitKeyedWrite = function (ast, context) { };
  7072. NullAstVisitor.prototype.visitLiteralArray = function (ast, context) { };
  7073. NullAstVisitor.prototype.visitLiteralMap = function (ast, context) { };
  7074. NullAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { };
  7075. NullAstVisitor.prototype.visitMethodCall = function (ast, context) { };
  7076. NullAstVisitor.prototype.visitPipe = function (ast, context) { };
  7077. NullAstVisitor.prototype.visitPrefixNot = function (ast, context) { };
  7078. NullAstVisitor.prototype.visitNonNullAssert = function (ast, context) { };
  7079. NullAstVisitor.prototype.visitPropertyRead = function (ast, context) { };
  7080. NullAstVisitor.prototype.visitPropertyWrite = function (ast, context) { };
  7081. NullAstVisitor.prototype.visitQuote = function (ast, context) { };
  7082. NullAstVisitor.prototype.visitSafeMethodCall = function (ast, context) { };
  7083. NullAstVisitor.prototype.visitSafePropertyRead = function (ast, context) { };
  7084. return NullAstVisitor;
  7085. }());
  7086. var RecursiveAstVisitor$1 = /** @class */ (function () {
  7087. function RecursiveAstVisitor() {
  7088. }
  7089. RecursiveAstVisitor.prototype.visitBinary = function (ast, context) {
  7090. ast.left.visit(this, context);
  7091. ast.right.visit(this, context);
  7092. return null;
  7093. };
  7094. RecursiveAstVisitor.prototype.visitChain = function (ast, context) { return this.visitAll(ast.expressions, context); };
  7095. RecursiveAstVisitor.prototype.visitConditional = function (ast, context) {
  7096. ast.condition.visit(this, context);
  7097. ast.trueExp.visit(this, context);
  7098. ast.falseExp.visit(this, context);
  7099. return null;
  7100. };
  7101. RecursiveAstVisitor.prototype.visitPipe = function (ast, context) {
  7102. ast.exp.visit(this, context);
  7103. this.visitAll(ast.args, context);
  7104. return null;
  7105. };
  7106. RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) {
  7107. ast.target.visit(this, context);
  7108. this.visitAll(ast.args, context);
  7109. return null;
  7110. };
  7111. RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { return null; };
  7112. RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) {
  7113. return this.visitAll(ast.expressions, context);
  7114. };
  7115. RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) {
  7116. ast.obj.visit(this, context);
  7117. ast.key.visit(this, context);
  7118. return null;
  7119. };
  7120. RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) {
  7121. ast.obj.visit(this, context);
  7122. ast.key.visit(this, context);
  7123. ast.value.visit(this, context);
  7124. return null;
  7125. };
  7126. RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) {
  7127. return this.visitAll(ast.expressions, context);
  7128. };
  7129. RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { return this.visitAll(ast.values, context); };
  7130. RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { return null; };
  7131. RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) {
  7132. ast.receiver.visit(this, context);
  7133. return this.visitAll(ast.args, context);
  7134. };
  7135. RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) {
  7136. ast.expression.visit(this, context);
  7137. return null;
  7138. };
  7139. RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) {
  7140. ast.expression.visit(this, context);
  7141. return null;
  7142. };
  7143. RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) {
  7144. ast.receiver.visit(this, context);
  7145. return null;
  7146. };
  7147. RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) {
  7148. ast.receiver.visit(this, context);
  7149. ast.value.visit(this, context);
  7150. return null;
  7151. };
  7152. RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) {
  7153. ast.receiver.visit(this, context);
  7154. return null;
  7155. };
  7156. RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) {
  7157. ast.receiver.visit(this, context);
  7158. return this.visitAll(ast.args, context);
  7159. };
  7160. RecursiveAstVisitor.prototype.visitAll = function (asts, context) {
  7161. var _this = this;
  7162. asts.forEach(function (ast) { return ast.visit(_this, context); });
  7163. return null;
  7164. };
  7165. RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { return null; };
  7166. return RecursiveAstVisitor;
  7167. }());
  7168. var AstTransformer$1 = /** @class */ (function () {
  7169. function AstTransformer() {
  7170. }
  7171. AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
  7172. AstTransformer.prototype.visitInterpolation = function (ast, context) {
  7173. return new Interpolation(ast.span, ast.strings, this.visitAll(ast.expressions));
  7174. };
  7175. AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
  7176. return new LiteralPrimitive(ast.span, ast.value);
  7177. };
  7178. AstTransformer.prototype.visitPropertyRead = function (ast, context) {
  7179. return new PropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  7180. };
  7181. AstTransformer.prototype.visitPropertyWrite = function (ast, context) {
  7182. return new PropertyWrite(ast.span, ast.receiver.visit(this), ast.name, ast.value.visit(this));
  7183. };
  7184. AstTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  7185. return new SafePropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  7186. };
  7187. AstTransformer.prototype.visitMethodCall = function (ast, context) {
  7188. return new MethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  7189. };
  7190. AstTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  7191. return new SafeMethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  7192. };
  7193. AstTransformer.prototype.visitFunctionCall = function (ast, context) {
  7194. return new FunctionCall(ast.span, ast.target.visit(this), this.visitAll(ast.args));
  7195. };
  7196. AstTransformer.prototype.visitLiteralArray = function (ast, context) {
  7197. return new LiteralArray(ast.span, this.visitAll(ast.expressions));
  7198. };
  7199. AstTransformer.prototype.visitLiteralMap = function (ast, context) {
  7200. return new LiteralMap(ast.span, ast.keys, this.visitAll(ast.values));
  7201. };
  7202. AstTransformer.prototype.visitBinary = function (ast, context) {
  7203. return new Binary(ast.span, ast.operation, ast.left.visit(this), ast.right.visit(this));
  7204. };
  7205. AstTransformer.prototype.visitPrefixNot = function (ast, context) {
  7206. return new PrefixNot(ast.span, ast.expression.visit(this));
  7207. };
  7208. AstTransformer.prototype.visitNonNullAssert = function (ast, context) {
  7209. return new NonNullAssert(ast.span, ast.expression.visit(this));
  7210. };
  7211. AstTransformer.prototype.visitConditional = function (ast, context) {
  7212. return new Conditional(ast.span, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
  7213. };
  7214. AstTransformer.prototype.visitPipe = function (ast, context) {
  7215. return new BindingPipe(ast.span, ast.exp.visit(this), ast.name, this.visitAll(ast.args));
  7216. };
  7217. AstTransformer.prototype.visitKeyedRead = function (ast, context) {
  7218. return new KeyedRead(ast.span, ast.obj.visit(this), ast.key.visit(this));
  7219. };
  7220. AstTransformer.prototype.visitKeyedWrite = function (ast, context) {
  7221. return new KeyedWrite(ast.span, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
  7222. };
  7223. AstTransformer.prototype.visitAll = function (asts) {
  7224. var res = new Array(asts.length);
  7225. for (var i = 0; i < asts.length; ++i) {
  7226. res[i] = asts[i].visit(this);
  7227. }
  7228. return res;
  7229. };
  7230. AstTransformer.prototype.visitChain = function (ast, context) {
  7231. return new Chain(ast.span, this.visitAll(ast.expressions));
  7232. };
  7233. AstTransformer.prototype.visitQuote = function (ast, context) {
  7234. return new Quote(ast.span, ast.prefix, ast.uninterpretedExpression, ast.location);
  7235. };
  7236. return AstTransformer;
  7237. }());
  7238. // A transformer that only creates new nodes if the transformer makes a change or
  7239. // a change is made a child node.
  7240. var AstMemoryEfficientTransformer = /** @class */ (function () {
  7241. function AstMemoryEfficientTransformer() {
  7242. }
  7243. AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
  7244. AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) {
  7245. var expressions = this.visitAll(ast.expressions);
  7246. if (expressions !== ast.expressions)
  7247. return new Interpolation(ast.span, ast.strings, expressions);
  7248. return ast;
  7249. };
  7250. AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return ast; };
  7251. AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) {
  7252. var receiver = ast.receiver.visit(this);
  7253. if (receiver !== ast.receiver) {
  7254. return new PropertyRead(ast.span, receiver, ast.name);
  7255. }
  7256. return ast;
  7257. };
  7258. AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) {
  7259. var receiver = ast.receiver.visit(this);
  7260. var value = ast.value.visit(this);
  7261. if (receiver !== ast.receiver || value !== ast.value) {
  7262. return new PropertyWrite(ast.span, receiver, ast.name, value);
  7263. }
  7264. return ast;
  7265. };
  7266. AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  7267. var receiver = ast.receiver.visit(this);
  7268. if (receiver !== ast.receiver) {
  7269. return new SafePropertyRead(ast.span, receiver, ast.name);
  7270. }
  7271. return ast;
  7272. };
  7273. AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) {
  7274. var receiver = ast.receiver.visit(this);
  7275. var args = this.visitAll(ast.args);
  7276. if (receiver !== ast.receiver || args !== ast.args) {
  7277. return new MethodCall(ast.span, receiver, ast.name, args);
  7278. }
  7279. return ast;
  7280. };
  7281. AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  7282. var receiver = ast.receiver.visit(this);
  7283. var args = this.visitAll(ast.args);
  7284. if (receiver !== ast.receiver || args !== ast.args) {
  7285. return new SafeMethodCall(ast.span, receiver, ast.name, args);
  7286. }
  7287. return ast;
  7288. };
  7289. AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) {
  7290. var target = ast.target && ast.target.visit(this);
  7291. var args = this.visitAll(ast.args);
  7292. if (target !== ast.target || args !== ast.args) {
  7293. return new FunctionCall(ast.span, target, args);
  7294. }
  7295. return ast;
  7296. };
  7297. AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) {
  7298. var expressions = this.visitAll(ast.expressions);
  7299. if (expressions !== ast.expressions) {
  7300. return new LiteralArray(ast.span, expressions);
  7301. }
  7302. return ast;
  7303. };
  7304. AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) {
  7305. var values = this.visitAll(ast.values);
  7306. if (values !== ast.values) {
  7307. return new LiteralMap(ast.span, ast.keys, values);
  7308. }
  7309. return ast;
  7310. };
  7311. AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) {
  7312. var left = ast.left.visit(this);
  7313. var right = ast.right.visit(this);
  7314. if (left !== ast.left || right !== ast.right) {
  7315. return new Binary(ast.span, ast.operation, left, right);
  7316. }
  7317. return ast;
  7318. };
  7319. AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) {
  7320. var expression = ast.expression.visit(this);
  7321. if (expression !== ast.expression) {
  7322. return new PrefixNot(ast.span, expression);
  7323. }
  7324. return ast;
  7325. };
  7326. AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) {
  7327. var expression = ast.expression.visit(this);
  7328. if (expression !== ast.expression) {
  7329. return new NonNullAssert(ast.span, expression);
  7330. }
  7331. return ast;
  7332. };
  7333. AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) {
  7334. var condition = ast.condition.visit(this);
  7335. var trueExp = ast.trueExp.visit(this);
  7336. var falseExp = ast.falseExp.visit(this);
  7337. if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
  7338. return new Conditional(ast.span, condition, trueExp, falseExp);
  7339. }
  7340. return ast;
  7341. };
  7342. AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) {
  7343. var exp = ast.exp.visit(this);
  7344. var args = this.visitAll(ast.args);
  7345. if (exp !== ast.exp || args !== ast.args) {
  7346. return new BindingPipe(ast.span, exp, ast.name, args);
  7347. }
  7348. return ast;
  7349. };
  7350. AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) {
  7351. var obj = ast.obj.visit(this);
  7352. var key = ast.key.visit(this);
  7353. if (obj !== ast.obj || key !== ast.key) {
  7354. return new KeyedRead(ast.span, obj, key);
  7355. }
  7356. return ast;
  7357. };
  7358. AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) {
  7359. var obj = ast.obj.visit(this);
  7360. var key = ast.key.visit(this);
  7361. var value = ast.value.visit(this);
  7362. if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
  7363. return new KeyedWrite(ast.span, obj, key, value);
  7364. }
  7365. return ast;
  7366. };
  7367. AstMemoryEfficientTransformer.prototype.visitAll = function (asts) {
  7368. var res = new Array(asts.length);
  7369. var modified = false;
  7370. for (var i = 0; i < asts.length; ++i) {
  7371. var original = asts[i];
  7372. var value = original.visit(this);
  7373. res[i] = value;
  7374. modified = modified || value !== original;
  7375. }
  7376. return modified ? res : asts;
  7377. };
  7378. AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) {
  7379. var expressions = this.visitAll(ast.expressions);
  7380. if (expressions !== ast.expressions) {
  7381. return new Chain(ast.span, expressions);
  7382. }
  7383. return ast;
  7384. };
  7385. AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) { return ast; };
  7386. return AstMemoryEfficientTransformer;
  7387. }());
  7388. function visitAstChildren(ast, visitor, context) {
  7389. function visit(ast) {
  7390. visitor.visit && visitor.visit(ast, context) || ast.visit(visitor, context);
  7391. }
  7392. function visitAll(asts) { asts.forEach(visit); }
  7393. ast.visit({
  7394. visitBinary: function (ast) {
  7395. visit(ast.left);
  7396. visit(ast.right);
  7397. },
  7398. visitChain: function (ast) { visitAll(ast.expressions); },
  7399. visitConditional: function (ast) {
  7400. visit(ast.condition);
  7401. visit(ast.trueExp);
  7402. visit(ast.falseExp);
  7403. },
  7404. visitFunctionCall: function (ast) {
  7405. if (ast.target) {
  7406. visit(ast.target);
  7407. }
  7408. visitAll(ast.args);
  7409. },
  7410. visitImplicitReceiver: function (ast) { },
  7411. visitInterpolation: function (ast) { visitAll(ast.expressions); },
  7412. visitKeyedRead: function (ast) {
  7413. visit(ast.obj);
  7414. visit(ast.key);
  7415. },
  7416. visitKeyedWrite: function (ast) {
  7417. visit(ast.obj);
  7418. visit(ast.key);
  7419. visit(ast.obj);
  7420. },
  7421. visitLiteralArray: function (ast) { visitAll(ast.expressions); },
  7422. visitLiteralMap: function (ast) { },
  7423. visitLiteralPrimitive: function (ast) { },
  7424. visitMethodCall: function (ast) {
  7425. visit(ast.receiver);
  7426. visitAll(ast.args);
  7427. },
  7428. visitPipe: function (ast) {
  7429. visit(ast.exp);
  7430. visitAll(ast.args);
  7431. },
  7432. visitPrefixNot: function (ast) { visit(ast.expression); },
  7433. visitNonNullAssert: function (ast) { visit(ast.expression); },
  7434. visitPropertyRead: function (ast) { visit(ast.receiver); },
  7435. visitPropertyWrite: function (ast) {
  7436. visit(ast.receiver);
  7437. visit(ast.value);
  7438. },
  7439. visitQuote: function (ast) { },
  7440. visitSafeMethodCall: function (ast) {
  7441. visit(ast.receiver);
  7442. visitAll(ast.args);
  7443. },
  7444. visitSafePropertyRead: function (ast) { visit(ast.receiver); },
  7445. });
  7446. }
  7447. // Bindings
  7448. var ParsedProperty = /** @class */ (function () {
  7449. function ParsedProperty(name, expression, type, sourceSpan) {
  7450. this.name = name;
  7451. this.expression = expression;
  7452. this.type = type;
  7453. this.sourceSpan = sourceSpan;
  7454. this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
  7455. this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
  7456. }
  7457. return ParsedProperty;
  7458. }());
  7459. var ParsedPropertyType;
  7460. (function (ParsedPropertyType) {
  7461. ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
  7462. ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
  7463. ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
  7464. })(ParsedPropertyType || (ParsedPropertyType = {}));
  7465. var ParsedEvent = /** @class */ (function () {
  7466. // Regular events have a target
  7467. // Animation events have a phase
  7468. function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan, handlerSpan) {
  7469. this.name = name;
  7470. this.targetOrPhase = targetOrPhase;
  7471. this.type = type;
  7472. this.handler = handler;
  7473. this.sourceSpan = sourceSpan;
  7474. this.handlerSpan = handlerSpan;
  7475. }
  7476. return ParsedEvent;
  7477. }());
  7478. var ParsedVariable = /** @class */ (function () {
  7479. function ParsedVariable(name, value, sourceSpan) {
  7480. this.name = name;
  7481. this.value = value;
  7482. this.sourceSpan = sourceSpan;
  7483. }
  7484. return ParsedVariable;
  7485. }());
  7486. var BoundElementProperty = /** @class */ (function () {
  7487. function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan) {
  7488. this.name = name;
  7489. this.type = type;
  7490. this.securityContext = securityContext;
  7491. this.value = value;
  7492. this.unit = unit;
  7493. this.sourceSpan = sourceSpan;
  7494. }
  7495. return BoundElementProperty;
  7496. }());
  7497. /**
  7498. * @license
  7499. * Copyright Google Inc. All Rights Reserved.
  7500. *
  7501. * Use of this source code is governed by an MIT-style license that can be
  7502. * found in the LICENSE file at https://angular.io/license
  7503. */
  7504. var EventHandlerVars = /** @class */ (function () {
  7505. function EventHandlerVars() {
  7506. }
  7507. EventHandlerVars.event = variable('$event');
  7508. return EventHandlerVars;
  7509. }());
  7510. var ConvertActionBindingResult = /** @class */ (function () {
  7511. function ConvertActionBindingResult(
  7512. /**
  7513. * Render2 compatible statements,
  7514. */
  7515. stmts,
  7516. /**
  7517. * Variable name used with render2 compatible statements.
  7518. */
  7519. allowDefault) {
  7520. this.stmts = stmts;
  7521. this.allowDefault = allowDefault;
  7522. /**
  7523. * This is bit of a hack. It converts statements which render2 expects to statements which are
  7524. * expected by render3.
  7525. *
  7526. * Example: `<div click="doSomething($event)">` will generate:
  7527. *
  7528. * Render3:
  7529. * ```
  7530. * const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
  7531. * return pd_b;
  7532. * ```
  7533. *
  7534. * but render2 expects:
  7535. * ```
  7536. * return ctx.doSomething($event);
  7537. * ```
  7538. */
  7539. // TODO(misko): remove this hack once we no longer support ViewEngine.
  7540. this.render3Stmts = stmts.map(function (statement) {
  7541. if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
  7542. statement.value instanceof BinaryOperatorExpr) {
  7543. var lhs = statement.value.lhs;
  7544. return new ReturnStatement(lhs.value);
  7545. }
  7546. return statement;
  7547. });
  7548. }
  7549. return ConvertActionBindingResult;
  7550. }());
  7551. /**
  7552. * Converts the given expression AST into an executable output AST, assuming the expression is
  7553. * used in an action binding (e.g. an event handler).
  7554. */
  7555. function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan) {
  7556. if (!localResolver) {
  7557. localResolver = new DefaultLocalResolver();
  7558. }
  7559. var actionWithoutBuiltins = convertPropertyBindingBuiltins({
  7560. createLiteralArrayConverter: function (argCount) {
  7561. // Note: no caching for literal arrays in actions.
  7562. return function (args) { return literalArr(args); };
  7563. },
  7564. createLiteralMapConverter: function (keys) {
  7565. // Note: no caching for literal maps in actions.
  7566. return function (values) {
  7567. var entries = keys.map(function (k, i) { return ({
  7568. key: k.key,
  7569. value: values[i],
  7570. quoted: k.quoted,
  7571. }); });
  7572. return literalMap(entries);
  7573. };
  7574. },
  7575. createPipeConverter: function (name) {
  7576. throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name);
  7577. }
  7578. }, action);
  7579. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan);
  7580. var actionStmts = [];
  7581. flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
  7582. prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
  7583. if (visitor.usesImplicitReceiver) {
  7584. localResolver.notifyImplicitReceiverUse();
  7585. }
  7586. var lastIndex = actionStmts.length - 1;
  7587. var preventDefaultVar = null;
  7588. if (lastIndex >= 0) {
  7589. var lastStatement = actionStmts[lastIndex];
  7590. var returnExpr = convertStmtIntoExpression(lastStatement);
  7591. if (returnExpr) {
  7592. // Note: We need to cast the result of the method call to dynamic,
  7593. // as it might be a void method!
  7594. preventDefaultVar = createPreventDefaultVar(bindingId);
  7595. actionStmts[lastIndex] =
  7596. preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
  7597. .toDeclStmt(null, [StmtModifier.Final]);
  7598. }
  7599. }
  7600. return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
  7601. }
  7602. function convertPropertyBindingBuiltins(converterFactory, ast) {
  7603. return convertBuiltins(converterFactory, ast);
  7604. }
  7605. var ConvertPropertyBindingResult = /** @class */ (function () {
  7606. function ConvertPropertyBindingResult(stmts, currValExpr) {
  7607. this.stmts = stmts;
  7608. this.currValExpr = currValExpr;
  7609. }
  7610. return ConvertPropertyBindingResult;
  7611. }());
  7612. var BindingForm;
  7613. (function (BindingForm) {
  7614. // The general form of binding expression, supports all expressions.
  7615. BindingForm[BindingForm["General"] = 0] = "General";
  7616. // Try to generate a simple binding (no temporaries or statements)
  7617. // otherwise generate a general binding
  7618. BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
  7619. })(BindingForm || (BindingForm = {}));
  7620. /**
  7621. * Converts the given expression AST into an executable output AST, assuming the expression
  7622. * is used in property binding. The expression has to be preprocessed via
  7623. * `convertPropertyBindingBuiltins`.
  7624. */
  7625. function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
  7626. if (!localResolver) {
  7627. localResolver = new DefaultLocalResolver();
  7628. }
  7629. var currValExpr = createCurrValueExpr(bindingId);
  7630. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
  7631. var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
  7632. var stmts = getStatementsFromVisitor(visitor, bindingId);
  7633. if (visitor.usesImplicitReceiver) {
  7634. localResolver.notifyImplicitReceiverUse();
  7635. }
  7636. if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
  7637. return new ConvertPropertyBindingResult([], outputExpr);
  7638. }
  7639. stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [StmtModifier.Final]));
  7640. return new ConvertPropertyBindingResult(stmts, currValExpr);
  7641. }
  7642. /**
  7643. * Given some expression, such as a binding or interpolation expression, and a context expression to
  7644. * look values up on, visit each facet of the given expression resolving values from the context
  7645. * expression such that a list of arguments can be derived from the found values that can be used as
  7646. * arguments to an external update instruction.
  7647. *
  7648. * @param localResolver The resolver to use to look up expressions by name appropriately
  7649. * @param contextVariableExpression The expression representing the context variable used to create
  7650. * the final argument expressions
  7651. * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
  7652. * be resolved and what arguments list to build.
  7653. * @param bindingId A name prefix used to create temporary variable names if they're needed for the
  7654. * arguments generated
  7655. * @returns An array of expressions that can be passed as arguments to instruction expressions like
  7656. * `o.importExpr(R3.propertyInterpolate).callFn(result)`
  7657. */
  7658. function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
  7659. var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
  7660. var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
  7661. if (visitor.usesImplicitReceiver) {
  7662. localResolver.notifyImplicitReceiverUse();
  7663. }
  7664. var stmts = getStatementsFromVisitor(visitor, bindingId);
  7665. // Removing the first argument, because it was a length for ViewEngine, not Ivy.
  7666. var args = outputExpr.args.slice(1);
  7667. if (expressionWithArgumentsToExtract instanceof Interpolation) {
  7668. // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
  7669. // args returned to just the value, because we're going to pass it to a special instruction.
  7670. var strings = expressionWithArgumentsToExtract.strings;
  7671. if (args.length === 3 && strings[0] === '' && strings[1] === '') {
  7672. // Single argument interpolate instructions.
  7673. args = [args[1]];
  7674. }
  7675. else if (args.length >= 19) {
  7676. // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
  7677. // an array of arguments
  7678. args = [literalArr(args)];
  7679. }
  7680. }
  7681. return { stmts: stmts, args: args };
  7682. }
  7683. function getStatementsFromVisitor(visitor, bindingId) {
  7684. var stmts = [];
  7685. for (var i = 0; i < visitor.temporaryCount; i++) {
  7686. stmts.push(temporaryDeclaration(bindingId, i));
  7687. }
  7688. return stmts;
  7689. }
  7690. function convertBuiltins(converterFactory, ast) {
  7691. var visitor = new _BuiltinAstConverter(converterFactory);
  7692. return ast.visit(visitor);
  7693. }
  7694. function temporaryName(bindingId, temporaryNumber) {
  7695. return "tmp_" + bindingId + "_" + temporaryNumber;
  7696. }
  7697. function temporaryDeclaration(bindingId, temporaryNumber) {
  7698. return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
  7699. }
  7700. function prependTemporaryDecls(temporaryCount, bindingId, statements) {
  7701. for (var i = temporaryCount - 1; i >= 0; i--) {
  7702. statements.unshift(temporaryDeclaration(bindingId, i));
  7703. }
  7704. }
  7705. var _Mode;
  7706. (function (_Mode) {
  7707. _Mode[_Mode["Statement"] = 0] = "Statement";
  7708. _Mode[_Mode["Expression"] = 1] = "Expression";
  7709. })(_Mode || (_Mode = {}));
  7710. function ensureStatementMode(mode, ast) {
  7711. if (mode !== _Mode.Statement) {
  7712. throw new Error("Expected a statement, but saw " + ast);
  7713. }
  7714. }
  7715. function ensureExpressionMode(mode, ast) {
  7716. if (mode !== _Mode.Expression) {
  7717. throw new Error("Expected an expression, but saw " + ast);
  7718. }
  7719. }
  7720. function convertToStatementIfNeeded(mode, expr) {
  7721. if (mode === _Mode.Statement) {
  7722. return expr.toStmt();
  7723. }
  7724. else {
  7725. return expr;
  7726. }
  7727. }
  7728. var _BuiltinAstConverter = /** @class */ (function (_super) {
  7729. __extends(_BuiltinAstConverter, _super);
  7730. function _BuiltinAstConverter(_converterFactory) {
  7731. var _this = _super.call(this) || this;
  7732. _this._converterFactory = _converterFactory;
  7733. return _this;
  7734. }
  7735. _BuiltinAstConverter.prototype.visitPipe = function (ast, context) {
  7736. var _this = this;
  7737. var args = __spread([ast.exp], ast.args).map(function (ast) { return ast.visit(_this, context); });
  7738. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createPipeConverter(ast.name, args.length));
  7739. };
  7740. _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) {
  7741. var _this = this;
  7742. var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); });
  7743. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
  7744. };
  7745. _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) {
  7746. var _this = this;
  7747. var args = ast.values.map(function (ast) { return ast.visit(_this, context); });
  7748. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
  7749. };
  7750. return _BuiltinAstConverter;
  7751. }(AstTransformer$1));
  7752. var _AstToIrVisitor = /** @class */ (function () {
  7753. function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan) {
  7754. this._localResolver = _localResolver;
  7755. this._implicitReceiver = _implicitReceiver;
  7756. this.bindingId = bindingId;
  7757. this.interpolationFunction = interpolationFunction;
  7758. this.baseSourceSpan = baseSourceSpan;
  7759. this._nodeMap = new Map();
  7760. this._resultMap = new Map();
  7761. this._currentTemporary = 0;
  7762. this.temporaryCount = 0;
  7763. this.usesImplicitReceiver = false;
  7764. }
  7765. _AstToIrVisitor.prototype.visitBinary = function (ast, mode) {
  7766. var op;
  7767. switch (ast.operation) {
  7768. case '+':
  7769. op = BinaryOperator.Plus;
  7770. break;
  7771. case '-':
  7772. op = BinaryOperator.Minus;
  7773. break;
  7774. case '*':
  7775. op = BinaryOperator.Multiply;
  7776. break;
  7777. case '/':
  7778. op = BinaryOperator.Divide;
  7779. break;
  7780. case '%':
  7781. op = BinaryOperator.Modulo;
  7782. break;
  7783. case '&&':
  7784. op = BinaryOperator.And;
  7785. break;
  7786. case '||':
  7787. op = BinaryOperator.Or;
  7788. break;
  7789. case '==':
  7790. op = BinaryOperator.Equals;
  7791. break;
  7792. case '!=':
  7793. op = BinaryOperator.NotEquals;
  7794. break;
  7795. case '===':
  7796. op = BinaryOperator.Identical;
  7797. break;
  7798. case '!==':
  7799. op = BinaryOperator.NotIdentical;
  7800. break;
  7801. case '<':
  7802. op = BinaryOperator.Lower;
  7803. break;
  7804. case '>':
  7805. op = BinaryOperator.Bigger;
  7806. break;
  7807. case '<=':
  7808. op = BinaryOperator.LowerEquals;
  7809. break;
  7810. case '>=':
  7811. op = BinaryOperator.BiggerEquals;
  7812. break;
  7813. default:
  7814. throw new Error("Unsupported operation " + ast.operation);
  7815. }
  7816. return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
  7817. };
  7818. _AstToIrVisitor.prototype.visitChain = function (ast, mode) {
  7819. ensureStatementMode(mode, ast);
  7820. return this.visitAll(ast.expressions, mode);
  7821. };
  7822. _AstToIrVisitor.prototype.visitConditional = function (ast, mode) {
  7823. var value = this._visit(ast.condition, _Mode.Expression);
  7824. return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
  7825. };
  7826. _AstToIrVisitor.prototype.visitPipe = function (ast, mode) {
  7827. throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name);
  7828. };
  7829. _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) {
  7830. var convertedArgs = this.visitAll(ast.args, _Mode.Expression);
  7831. var fnResult;
  7832. if (ast instanceof BuiltinFunctionCall) {
  7833. fnResult = ast.converter(convertedArgs);
  7834. }
  7835. else {
  7836. fnResult = this._visit(ast.target, _Mode.Expression)
  7837. .callFn(convertedArgs, this.convertSourceSpan(ast.span));
  7838. }
  7839. return convertToStatementIfNeeded(mode, fnResult);
  7840. };
  7841. _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) {
  7842. ensureExpressionMode(mode, ast);
  7843. this.usesImplicitReceiver = true;
  7844. return this._implicitReceiver;
  7845. };
  7846. _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) {
  7847. ensureExpressionMode(mode, ast);
  7848. var args = [literal(ast.expressions.length)];
  7849. for (var i = 0; i < ast.strings.length - 1; i++) {
  7850. args.push(literal(ast.strings[i]));
  7851. args.push(this._visit(ast.expressions[i], _Mode.Expression));
  7852. }
  7853. args.push(literal(ast.strings[ast.strings.length - 1]));
  7854. if (this.interpolationFunction) {
  7855. return this.interpolationFunction(args);
  7856. }
  7857. return ast.expressions.length <= 9 ?
  7858. importExpr(Identifiers.inlineInterpolate).callFn(args) :
  7859. importExpr(Identifiers.interpolate).callFn([
  7860. args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
  7861. ]);
  7862. };
  7863. _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) {
  7864. var leftMostSafe = this.leftMostSafeNode(ast);
  7865. if (leftMostSafe) {
  7866. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7867. }
  7868. else {
  7869. return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
  7870. }
  7871. };
  7872. _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) {
  7873. var obj = this._visit(ast.obj, _Mode.Expression);
  7874. var key = this._visit(ast.key, _Mode.Expression);
  7875. var value = this._visit(ast.value, _Mode.Expression);
  7876. return convertToStatementIfNeeded(mode, obj.key(key).set(value));
  7877. };
  7878. _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) {
  7879. throw new Error("Illegal State: literal arrays should have been converted into functions");
  7880. };
  7881. _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) {
  7882. throw new Error("Illegal State: literal maps should have been converted into functions");
  7883. };
  7884. _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) {
  7885. // For literal values of null, undefined, true, or false allow type interference
  7886. // to infer the type.
  7887. var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
  7888. INFERRED_TYPE :
  7889. undefined;
  7890. return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
  7891. };
  7892. _AstToIrVisitor.prototype._getLocal = function (name) { return this._localResolver.getLocal(name); };
  7893. _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) {
  7894. if (ast.receiver instanceof ImplicitReceiver && ast.name == '$any') {
  7895. var args = this.visitAll(ast.args, _Mode.Expression);
  7896. if (args.length != 1) {
  7897. throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none'));
  7898. }
  7899. return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
  7900. }
  7901. var leftMostSafe = this.leftMostSafeNode(ast);
  7902. if (leftMostSafe) {
  7903. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7904. }
  7905. else {
  7906. var args = this.visitAll(ast.args, _Mode.Expression);
  7907. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7908. var result = null;
  7909. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7910. if (receiver === this._implicitReceiver) {
  7911. var varExpr = this._getLocal(ast.name);
  7912. if (varExpr) {
  7913. // Restore the previous "usesImplicitReceiver" state since the implicit
  7914. // receiver has been replaced with a resolved local expression.
  7915. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7916. result = varExpr.callFn(args);
  7917. }
  7918. }
  7919. if (result == null) {
  7920. result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
  7921. }
  7922. return convertToStatementIfNeeded(mode, result);
  7923. }
  7924. };
  7925. _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) {
  7926. return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
  7927. };
  7928. _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) {
  7929. return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
  7930. };
  7931. _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) {
  7932. var leftMostSafe = this.leftMostSafeNode(ast);
  7933. if (leftMostSafe) {
  7934. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7935. }
  7936. else {
  7937. var result = null;
  7938. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7939. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7940. if (receiver === this._implicitReceiver) {
  7941. result = this._getLocal(ast.name);
  7942. if (result) {
  7943. // Restore the previous "usesImplicitReceiver" state since the implicit
  7944. // receiver has been replaced with a resolved local expression.
  7945. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7946. }
  7947. }
  7948. if (result == null) {
  7949. result = receiver.prop(ast.name);
  7950. }
  7951. return convertToStatementIfNeeded(mode, result);
  7952. }
  7953. };
  7954. _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) {
  7955. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7956. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7957. var varExpr = null;
  7958. if (receiver === this._implicitReceiver) {
  7959. var localExpr = this._getLocal(ast.name);
  7960. if (localExpr) {
  7961. if (localExpr instanceof ReadPropExpr) {
  7962. // If the local variable is a property read expression, it's a reference
  7963. // to a 'context.property' value and will be used as the target of the
  7964. // write expression.
  7965. varExpr = localExpr;
  7966. // Restore the previous "usesImplicitReceiver" state since the implicit
  7967. // receiver has been replaced with a resolved local expression.
  7968. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7969. }
  7970. else {
  7971. // Otherwise it's an error.
  7972. throw new Error('Cannot assign to a reference or variable!');
  7973. }
  7974. }
  7975. }
  7976. // If no local expression could be produced, use the original receiver's
  7977. // property as the target.
  7978. if (varExpr === null) {
  7979. varExpr = receiver.prop(ast.name);
  7980. }
  7981. return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
  7982. };
  7983. _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) {
  7984. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  7985. };
  7986. _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) {
  7987. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  7988. };
  7989. _AstToIrVisitor.prototype.visitAll = function (asts, mode) {
  7990. var _this = this;
  7991. return asts.map(function (ast) { return _this._visit(ast, mode); });
  7992. };
  7993. _AstToIrVisitor.prototype.visitQuote = function (ast, mode) {
  7994. throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location);
  7995. };
  7996. _AstToIrVisitor.prototype._visit = function (ast, mode) {
  7997. var result = this._resultMap.get(ast);
  7998. if (result)
  7999. return result;
  8000. return (this._nodeMap.get(ast) || ast).visit(this, mode);
  8001. };
  8002. _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) {
  8003. // If the expression contains a safe access node on the left it needs to be converted to
  8004. // an expression that guards the access to the member by checking the receiver for blank. As
  8005. // execution proceeds from left to right, the left most part of the expression must be guarded
  8006. // first but, because member access is left associative, the right side of the expression is at
  8007. // the top of the AST. The desired result requires lifting a copy of the the left part of the
  8008. // expression up to test it for blank before generating the unguarded version.
  8009. // Consider, for example the following expression: a?.b.c?.d.e
  8010. // This results in the ast:
  8011. // .
  8012. // / \
  8013. // ?. e
  8014. // / \
  8015. // . d
  8016. // / \
  8017. // ?. c
  8018. // / \
  8019. // a b
  8020. // The following tree should be generated:
  8021. //
  8022. // /---- ? ----\
  8023. // / | \
  8024. // a /--- ? ---\ null
  8025. // / | \
  8026. // . . null
  8027. // / \ / \
  8028. // . c . e
  8029. // / \ / \
  8030. // a b . d
  8031. // / \
  8032. // . c
  8033. // / \
  8034. // a b
  8035. //
  8036. // Notice that the first guard condition is the left hand of the left most safe access node
  8037. // which comes in as leftMostSafe to this routine.
  8038. var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
  8039. var temporary = undefined;
  8040. if (this.needsTemporary(leftMostSafe.receiver)) {
  8041. // If the expression has method calls or pipes then we need to save the result into a
  8042. // temporary variable to avoid calling stateful or impure code more than once.
  8043. temporary = this.allocateTemporary();
  8044. // Preserve the result in the temporary variable
  8045. guardedExpression = temporary.set(guardedExpression);
  8046. // Ensure all further references to the guarded expression refer to the temporary instead.
  8047. this._resultMap.set(leftMostSafe.receiver, temporary);
  8048. }
  8049. var condition = guardedExpression.isBlank();
  8050. // Convert the ast to an unguarded access to the receiver's member. The map will substitute
  8051. // leftMostNode with its unguarded version in the call to `this.visit()`.
  8052. if (leftMostSafe instanceof SafeMethodCall) {
  8053. this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
  8054. }
  8055. else {
  8056. this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name));
  8057. }
  8058. // Recursively convert the node now without the guarded member access.
  8059. var access = this._visit(ast, _Mode.Expression);
  8060. // Remove the mapping. This is not strictly required as the converter only traverses each node
  8061. // once but is safer if the conversion is changed to traverse the nodes more than once.
  8062. this._nodeMap.delete(leftMostSafe);
  8063. // If we allocated a temporary, release it.
  8064. if (temporary) {
  8065. this.releaseTemporary(temporary);
  8066. }
  8067. // Produce the conditional
  8068. return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
  8069. };
  8070. // Given a expression of the form a?.b.c?.d.e the the left most safe node is
  8071. // the (a?.b). The . and ?. are left associative thus can be rewritten as:
  8072. // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
  8073. // safe method call as this needs be transform initially to:
  8074. // a == null ? null : a.c.b.c?.d.e
  8075. // then to:
  8076. // a == null ? null : a.b.c == null ? null : a.b.c.d.e
  8077. _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) {
  8078. var _this = this;
  8079. var visit = function (visitor, ast) {
  8080. return (_this._nodeMap.get(ast) || ast).visit(visitor);
  8081. };
  8082. return ast.visit({
  8083. visitBinary: function (ast) { return null; },
  8084. visitChain: function (ast) { return null; },
  8085. visitConditional: function (ast) { return null; },
  8086. visitFunctionCall: function (ast) { return null; },
  8087. visitImplicitReceiver: function (ast) { return null; },
  8088. visitInterpolation: function (ast) { return null; },
  8089. visitKeyedRead: function (ast) { return visit(this, ast.obj); },
  8090. visitKeyedWrite: function (ast) { return null; },
  8091. visitLiteralArray: function (ast) { return null; },
  8092. visitLiteralMap: function (ast) { return null; },
  8093. visitLiteralPrimitive: function (ast) { return null; },
  8094. visitMethodCall: function (ast) { return visit(this, ast.receiver); },
  8095. visitPipe: function (ast) { return null; },
  8096. visitPrefixNot: function (ast) { return null; },
  8097. visitNonNullAssert: function (ast) { return null; },
  8098. visitPropertyRead: function (ast) { return visit(this, ast.receiver); },
  8099. visitPropertyWrite: function (ast) { return null; },
  8100. visitQuote: function (ast) { return null; },
  8101. visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; },
  8102. visitSafePropertyRead: function (ast) {
  8103. return visit(this, ast.receiver) || ast;
  8104. }
  8105. });
  8106. };
  8107. // Returns true of the AST includes a method or a pipe indicating that, if the
  8108. // expression is used as the target of a safe property or method access then
  8109. // the expression should be stored into a temporary variable.
  8110. _AstToIrVisitor.prototype.needsTemporary = function (ast) {
  8111. var _this = this;
  8112. var visit = function (visitor, ast) {
  8113. return ast && (_this._nodeMap.get(ast) || ast).visit(visitor);
  8114. };
  8115. var visitSome = function (visitor, ast) {
  8116. return ast.some(function (ast) { return visit(visitor, ast); });
  8117. };
  8118. return ast.visit({
  8119. visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); },
  8120. visitChain: function (ast) { return false; },
  8121. visitConditional: function (ast) {
  8122. return visit(this, ast.condition) || visit(this, ast.trueExp) ||
  8123. visit(this, ast.falseExp);
  8124. },
  8125. visitFunctionCall: function (ast) { return true; },
  8126. visitImplicitReceiver: function (ast) { return false; },
  8127. visitInterpolation: function (ast) { return visitSome(this, ast.expressions); },
  8128. visitKeyedRead: function (ast) { return false; },
  8129. visitKeyedWrite: function (ast) { return false; },
  8130. visitLiteralArray: function (ast) { return true; },
  8131. visitLiteralMap: function (ast) { return true; },
  8132. visitLiteralPrimitive: function (ast) { return false; },
  8133. visitMethodCall: function (ast) { return true; },
  8134. visitPipe: function (ast) { return true; },
  8135. visitPrefixNot: function (ast) { return visit(this, ast.expression); },
  8136. visitNonNullAssert: function (ast) { return visit(this, ast.expression); },
  8137. visitPropertyRead: function (ast) { return false; },
  8138. visitPropertyWrite: function (ast) { return false; },
  8139. visitQuote: function (ast) { return false; },
  8140. visitSafeMethodCall: function (ast) { return true; },
  8141. visitSafePropertyRead: function (ast) { return false; }
  8142. });
  8143. };
  8144. _AstToIrVisitor.prototype.allocateTemporary = function () {
  8145. var tempNumber = this._currentTemporary++;
  8146. this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
  8147. return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
  8148. };
  8149. _AstToIrVisitor.prototype.releaseTemporary = function (temporary) {
  8150. this._currentTemporary--;
  8151. if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
  8152. throw new Error("Temporary " + temporary.name + " released out of order");
  8153. }
  8154. };
  8155. /**
  8156. * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
  8157. *
  8158. * `ParseSpan` objects are relative to the start of the expression.
  8159. * This method converts these to full `ParseSourceSpan` objects that
  8160. * show where the span is within the overall source file.
  8161. *
  8162. * @param span the relative span to convert.
  8163. * @returns a `ParseSourceSpan` for the the given span or null if no
  8164. * `baseSourceSpan` was provided to this class.
  8165. */
  8166. _AstToIrVisitor.prototype.convertSourceSpan = function (span) {
  8167. if (this.baseSourceSpan) {
  8168. var start = this.baseSourceSpan.start.moveBy(span.start);
  8169. var end = this.baseSourceSpan.start.moveBy(span.end);
  8170. return new ParseSourceSpan(start, end);
  8171. }
  8172. else {
  8173. return null;
  8174. }
  8175. };
  8176. return _AstToIrVisitor;
  8177. }());
  8178. function flattenStatements(arg, output) {
  8179. if (Array.isArray(arg)) {
  8180. arg.forEach(function (entry) { return flattenStatements(entry, output); });
  8181. }
  8182. else {
  8183. output.push(arg);
  8184. }
  8185. }
  8186. var DefaultLocalResolver = /** @class */ (function () {
  8187. function DefaultLocalResolver() {
  8188. }
  8189. DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  8190. DefaultLocalResolver.prototype.getLocal = function (name) {
  8191. if (name === EventHandlerVars.event.name) {
  8192. return EventHandlerVars.event;
  8193. }
  8194. return null;
  8195. };
  8196. return DefaultLocalResolver;
  8197. }());
  8198. function createCurrValueExpr(bindingId) {
  8199. return variable("currVal_" + bindingId); // fix syntax highlighting: `
  8200. }
  8201. function createPreventDefaultVar(bindingId) {
  8202. return variable("pd_" + bindingId);
  8203. }
  8204. function convertStmtIntoExpression(stmt) {
  8205. if (stmt instanceof ExpressionStatement) {
  8206. return stmt.expr;
  8207. }
  8208. else if (stmt instanceof ReturnStatement) {
  8209. return stmt.value;
  8210. }
  8211. return null;
  8212. }
  8213. var BuiltinFunctionCall = /** @class */ (function (_super) {
  8214. __extends(BuiltinFunctionCall, _super);
  8215. function BuiltinFunctionCall(span, args, converter) {
  8216. var _this = _super.call(this, span, null, args) || this;
  8217. _this.args = args;
  8218. _this.converter = converter;
  8219. return _this;
  8220. }
  8221. return BuiltinFunctionCall;
  8222. }(FunctionCall));
  8223. /**
  8224. * @license
  8225. * Copyright Google Inc. All Rights Reserved.
  8226. *
  8227. * Use of this source code is governed by an MIT-style license that can be
  8228. * found in the LICENSE file at https://angular.io/license
  8229. */
  8230. /**
  8231. * This file is a port of shadowCSS from webcomponents.js to TypeScript.
  8232. *
  8233. * Please make sure to keep to edits in sync with the source file.
  8234. *
  8235. * Source:
  8236. * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
  8237. *
  8238. * The original file level comment is reproduced below
  8239. */
  8240. /*
  8241. This is a limited shim for ShadowDOM css styling.
  8242. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
  8243. The intention here is to support only the styling features which can be
  8244. relatively simply implemented. The goal is to allow users to avoid the
  8245. most obvious pitfalls and do so without compromising performance significantly.
  8246. For ShadowDOM styling that's not covered here, a set of best practices
  8247. can be provided that should allow users to accomplish more complex styling.
  8248. The following is a list of specific ShadowDOM styling features and a brief
  8249. discussion of the approach used to shim.
  8250. Shimmed features:
  8251. * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
  8252. element using the :host rule. To shim this feature, the :host styles are
  8253. reformatted and prefixed with a given scope name and promoted to a
  8254. document level stylesheet.
  8255. For example, given a scope name of .foo, a rule like this:
  8256. :host {
  8257. background: red;
  8258. }
  8259. }
  8260. becomes:
  8261. .foo {
  8262. background: red;
  8263. }
  8264. * encapsulation: Styles defined within ShadowDOM, apply only to
  8265. dom inside the ShadowDOM. Polymer uses one of two techniques to implement
  8266. this feature.
  8267. By default, rules are prefixed with the host element tag name
  8268. as a descendant selector. This ensures styling does not leak out of the 'top'
  8269. of the element's ShadowDOM. For example,
  8270. div {
  8271. font-weight: bold;
  8272. }
  8273. becomes:
  8274. x-foo div {
  8275. font-weight: bold;
  8276. }
  8277. becomes:
  8278. Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
  8279. selectors are scoped by adding an attribute selector suffix to each
  8280. simple selector that contains the host element tag name. Each element
  8281. in the element's ShadowDOM template is also given the scope attribute.
  8282. Thus, these rules match only elements that have the scope attribute.
  8283. For example, given a scope name of x-foo, a rule like this:
  8284. div {
  8285. font-weight: bold;
  8286. }
  8287. becomes:
  8288. div[x-foo] {
  8289. font-weight: bold;
  8290. }
  8291. Note that elements that are dynamically added to a scope must have the scope
  8292. selector added to them manually.
  8293. * upper/lower bound encapsulation: Styles which are defined outside a
  8294. shadowRoot should not cross the ShadowDOM boundary and should not apply
  8295. inside a shadowRoot.
  8296. This styling behavior is not emulated. Some possible ways to do this that
  8297. were rejected due to complexity and/or performance concerns include: (1) reset
  8298. every possible property for every possible selector for a given scope name;
  8299. (2) re-implement css in javascript.
  8300. As an alternative, users should make sure to use selectors
  8301. specific to the scope in which they are working.
  8302. * ::distributed: This behavior is not emulated. It's often not necessary
  8303. to style the contents of a specific insertion point and instead, descendants
  8304. of the host element can be styled selectively. Users can also create an
  8305. extra node around an insertion point and style that node's contents
  8306. via descendent selectors. For example, with a shadowRoot like this:
  8307. <style>
  8308. ::content(div) {
  8309. background: red;
  8310. }
  8311. </style>
  8312. <content></content>
  8313. could become:
  8314. <style>
  8315. / *@polyfill .content-container div * /
  8316. ::content(div) {
  8317. background: red;
  8318. }
  8319. </style>
  8320. <div class="content-container">
  8321. <content></content>
  8322. </div>
  8323. Note the use of @polyfill in the comment above a ShadowDOM specific style
  8324. declaration. This is a directive to the styling shim to use the selector
  8325. in comments in lieu of the next selector when running under polyfill.
  8326. */
  8327. var ShadowCss = /** @class */ (function () {
  8328. function ShadowCss() {
  8329. this.strictStyling = true;
  8330. }
  8331. /*
  8332. * Shim some cssText with the given selector. Returns cssText that can
  8333. * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
  8334. *
  8335. * When strictStyling is true:
  8336. * - selector is the attribute added to all elements inside the host,
  8337. * - hostSelector is the attribute added to the host itself.
  8338. */
  8339. ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
  8340. if (hostSelector === void 0) { hostSelector = ''; }
  8341. var commentsWithHash = extractCommentsWithHash(cssText);
  8342. cssText = stripComments(cssText);
  8343. cssText = this._insertDirectives(cssText);
  8344. var scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
  8345. return __spread([scopedCssText], commentsWithHash).join('\n');
  8346. };
  8347. ShadowCss.prototype._insertDirectives = function (cssText) {
  8348. cssText = this._insertPolyfillDirectivesInCssText(cssText);
  8349. return this._insertPolyfillRulesInCssText(cssText);
  8350. };
  8351. /*
  8352. * Process styles to convert native ShadowDOM rules that will trip
  8353. * up the css parser; we rely on decorating the stylesheet with inert rules.
  8354. *
  8355. * For example, we convert this rule:
  8356. *
  8357. * polyfill-next-selector { content: ':host menu-item'; }
  8358. * ::content menu-item {
  8359. *
  8360. * to this:
  8361. *
  8362. * scopeName menu-item {
  8363. *
  8364. **/
  8365. ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
  8366. // Difference with webcomponents.js: does not handle comments
  8367. return cssText.replace(_cssContentNextSelectorRe, function () {
  8368. var m = [];
  8369. for (var _i = 0; _i < arguments.length; _i++) {
  8370. m[_i] = arguments[_i];
  8371. }
  8372. return m[2] + '{';
  8373. });
  8374. };
  8375. /*
  8376. * Process styles to add rules which will only apply under the polyfill
  8377. *
  8378. * For example, we convert this rule:
  8379. *
  8380. * polyfill-rule {
  8381. * content: ':host menu-item';
  8382. * ...
  8383. * }
  8384. *
  8385. * to this:
  8386. *
  8387. * scopeName menu-item {...}
  8388. *
  8389. **/
  8390. ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
  8391. // Difference with webcomponents.js: does not handle comments
  8392. return cssText.replace(_cssContentRuleRe, function () {
  8393. var m = [];
  8394. for (var _i = 0; _i < arguments.length; _i++) {
  8395. m[_i] = arguments[_i];
  8396. }
  8397. var rule = m[0].replace(m[1], '').replace(m[2], '');
  8398. return m[4] + rule;
  8399. });
  8400. };
  8401. /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
  8402. *
  8403. * .foo {... }
  8404. *
  8405. * and converts this to
  8406. *
  8407. * scopeName .foo { ... }
  8408. */
  8409. ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
  8410. var unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
  8411. // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
  8412. cssText = this._insertPolyfillHostInCssText(cssText);
  8413. cssText = this._convertColonHost(cssText);
  8414. cssText = this._convertColonHostContext(cssText);
  8415. cssText = this._convertShadowDOMSelectors(cssText);
  8416. if (scopeSelector) {
  8417. cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
  8418. }
  8419. cssText = cssText + '\n' + unscopedRules;
  8420. return cssText.trim();
  8421. };
  8422. /*
  8423. * Process styles to add rules which will only apply under the polyfill
  8424. * and do not process via CSSOM. (CSSOM is destructive to rules on rare
  8425. * occasions, e.g. -webkit-calc on Safari.)
  8426. * For example, we convert this rule:
  8427. *
  8428. * @polyfill-unscoped-rule {
  8429. * content: 'menu-item';
  8430. * ... }
  8431. *
  8432. * to this:
  8433. *
  8434. * menu-item {...}
  8435. *
  8436. **/
  8437. ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
  8438. // Difference with webcomponents.js: does not handle comments
  8439. var r = '';
  8440. var m;
  8441. _cssContentUnscopedRuleRe.lastIndex = 0;
  8442. while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
  8443. var rule = m[0].replace(m[2], '').replace(m[1], m[4]);
  8444. r += rule + '\n\n';
  8445. }
  8446. return r;
  8447. };
  8448. /*
  8449. * convert a rule like :host(.foo) > .bar { }
  8450. *
  8451. * to
  8452. *
  8453. * .foo<scopeName> > .bar
  8454. */
  8455. ShadowCss.prototype._convertColonHost = function (cssText) {
  8456. return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
  8457. };
  8458. /*
  8459. * convert a rule like :host-context(.foo) > .bar { }
  8460. *
  8461. * to
  8462. *
  8463. * .foo<scopeName> > .bar, .foo scopeName > .bar { }
  8464. *
  8465. * and
  8466. *
  8467. * :host-context(.foo:host) .bar { ... }
  8468. *
  8469. * to
  8470. *
  8471. * .foo<scopeName> .bar { ... }
  8472. */
  8473. ShadowCss.prototype._convertColonHostContext = function (cssText) {
  8474. return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
  8475. };
  8476. ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) {
  8477. // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
  8478. return cssText.replace(regExp, function () {
  8479. var m = [];
  8480. for (var _i = 0; _i < arguments.length; _i++) {
  8481. m[_i] = arguments[_i];
  8482. }
  8483. if (m[2]) {
  8484. var parts = m[2].split(',');
  8485. var r = [];
  8486. for (var i = 0; i < parts.length; i++) {
  8487. var p = parts[i].trim();
  8488. if (!p)
  8489. break;
  8490. r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
  8491. }
  8492. return r.join(',');
  8493. }
  8494. else {
  8495. return _polyfillHostNoCombinator + m[3];
  8496. }
  8497. });
  8498. };
  8499. ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) {
  8500. if (part.indexOf(_polyfillHost) > -1) {
  8501. return this._colonHostPartReplacer(host, part, suffix);
  8502. }
  8503. else {
  8504. return host + part + suffix + ', ' + part + ' ' + host + suffix;
  8505. }
  8506. };
  8507. ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) {
  8508. return host + part.replace(_polyfillHost, '') + suffix;
  8509. };
  8510. /*
  8511. * Convert combinators like ::shadow and pseudo-elements like ::content
  8512. * by replacing with space.
  8513. */
  8514. ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
  8515. return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText);
  8516. };
  8517. // change a selector like 'div' to 'name div'
  8518. ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
  8519. var _this = this;
  8520. return processRules(cssText, function (rule) {
  8521. var selector = rule.selector;
  8522. var content = rule.content;
  8523. if (rule.selector[0] != '@') {
  8524. selector =
  8525. _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
  8526. }
  8527. else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
  8528. rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
  8529. content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
  8530. }
  8531. return new CssRule(selector, content);
  8532. });
  8533. };
  8534. ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
  8535. var _this = this;
  8536. return selector.split(',')
  8537. .map(function (part) { return part.trim().split(_shadowDeepSelectors); })
  8538. .map(function (deepParts) {
  8539. var _a = __read(deepParts), shallowPart = _a[0], otherParts = _a.slice(1);
  8540. var applyScope = function (shallowPart) {
  8541. if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) {
  8542. return strict ?
  8543. _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
  8544. _this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
  8545. }
  8546. else {
  8547. return shallowPart;
  8548. }
  8549. };
  8550. return __spread([applyScope(shallowPart)], otherParts).join(' ');
  8551. })
  8552. .join(', ');
  8553. };
  8554. ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
  8555. var re = this._makeScopeMatcher(scopeSelector);
  8556. return !re.test(selector);
  8557. };
  8558. ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
  8559. var lre = /\[/g;
  8560. var rre = /\]/g;
  8561. scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
  8562. return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
  8563. };
  8564. ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
  8565. // Difference from webcomponents.js: scopeSelector could not be an array
  8566. return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
  8567. };
  8568. // scope via name and [is=name]
  8569. ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
  8570. // In Android browser, the lastIndex is not reset when the regex is used in String.replace()
  8571. _polyfillHostRe.lastIndex = 0;
  8572. if (_polyfillHostRe.test(selector)) {
  8573. var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
  8574. return selector
  8575. .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) {
  8576. return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) {
  8577. return before + replaceBy_1 + colon + after;
  8578. });
  8579. })
  8580. .replace(_polyfillHostRe, replaceBy_1 + ' ');
  8581. }
  8582. return scopeSelector + ' ' + selector;
  8583. };
  8584. // return a selector with [name] suffix on each simple selector
  8585. // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
  8586. ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) {
  8587. var _this = this;
  8588. var isRe = /\[is=([^\]]*)\]/g;
  8589. scopeSelector = scopeSelector.replace(isRe, function (_) {
  8590. var parts = [];
  8591. for (var _i = 1; _i < arguments.length; _i++) {
  8592. parts[_i - 1] = arguments[_i];
  8593. }
  8594. return parts[0];
  8595. });
  8596. var attrName = '[' + scopeSelector + ']';
  8597. var _scopeSelectorPart = function (p) {
  8598. var scopedP = p.trim();
  8599. if (!scopedP) {
  8600. return '';
  8601. }
  8602. if (p.indexOf(_polyfillHostNoCombinator) > -1) {
  8603. scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
  8604. }
  8605. else {
  8606. // remove :host since it should be unnecessary
  8607. var t = p.replace(_polyfillHostRe, '');
  8608. if (t.length > 0) {
  8609. var matches = t.match(/([^:]*)(:*)(.*)/);
  8610. if (matches) {
  8611. scopedP = matches[1] + attrName + matches[2] + matches[3];
  8612. }
  8613. }
  8614. }
  8615. return scopedP;
  8616. };
  8617. var safeContent = new SafeSelector(selector);
  8618. selector = safeContent.content();
  8619. var scopedSelector = '';
  8620. var startIndex = 0;
  8621. var res;
  8622. var sep = /( |>|\+|~(?!=))\s*/g;
  8623. // If a selector appears before :host it should not be shimmed as it
  8624. // matches on ancestor elements and not on elements in the host's shadow
  8625. // `:host-context(div)` is transformed to
  8626. // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
  8627. // the `div` is not part of the component in the 2nd selectors and should not be scoped.
  8628. // Historically `component-tag:host` was matching the component so we also want to preserve
  8629. // this behavior to avoid breaking legacy apps (it should not match).
  8630. // The behavior should be:
  8631. // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
  8632. // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
  8633. // `:host-context(tag)`)
  8634. var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
  8635. // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
  8636. var shouldScope = !hasHost;
  8637. while ((res = sep.exec(selector)) !== null) {
  8638. var separator = res[1];
  8639. var part_1 = selector.slice(startIndex, res.index).trim();
  8640. shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1;
  8641. var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1;
  8642. scopedSelector += scopedPart + " " + separator + " ";
  8643. startIndex = sep.lastIndex;
  8644. }
  8645. var part = selector.substring(startIndex);
  8646. shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
  8647. scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
  8648. // replace the placeholders with their original values
  8649. return safeContent.restore(scopedSelector);
  8650. };
  8651. ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
  8652. return selector.replace(_colonHostContextRe, _polyfillHostContext)
  8653. .replace(_colonHostRe, _polyfillHost);
  8654. };
  8655. return ShadowCss;
  8656. }());
  8657. var SafeSelector = /** @class */ (function () {
  8658. function SafeSelector(selector) {
  8659. var _this = this;
  8660. this.placeholders = [];
  8661. this.index = 0;
  8662. // Replaces attribute selectors with placeholders.
  8663. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
  8664. selector = selector.replace(/(\[[^\]]*\])/g, function (_, keep) {
  8665. var replaceBy = "__ph-" + _this.index + "__";
  8666. _this.placeholders.push(keep);
  8667. _this.index++;
  8668. return replaceBy;
  8669. });
  8670. // Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
  8671. // WS and "+" would otherwise be interpreted as selector separators.
  8672. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) {
  8673. var replaceBy = "__ph-" + _this.index + "__";
  8674. _this.placeholders.push(exp);
  8675. _this.index++;
  8676. return pseudo + replaceBy;
  8677. });
  8678. }
  8679. SafeSelector.prototype.restore = function (content) {
  8680. var _this = this;
  8681. return content.replace(/__ph-(\d+)__/g, function (ph, index) { return _this.placeholders[+index]; });
  8682. };
  8683. SafeSelector.prototype.content = function () { return this._content; };
  8684. return SafeSelector;
  8685. }());
  8686. var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
  8687. var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8688. var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8689. var _polyfillHost = '-shadowcsshost';
  8690. // note: :host-context pre-processed to -shadowcsshostcontext.
  8691. var _polyfillHostContext = '-shadowcsscontext';
  8692. var _parenSuffix = ')(?:\\((' +
  8693. '(?:\\([^)(]*\\)|[^)(]*)+?' +
  8694. ')\\))?([^,{]*)';
  8695. var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
  8696. var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
  8697. var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
  8698. var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
  8699. var _shadowDOMSelectorsRe = [
  8700. /::shadow/g,
  8701. /::content/g,
  8702. // Deprecated selectors
  8703. /\/shadow-deep\//g,
  8704. /\/shadow\//g,
  8705. ];
  8706. // The deep combinator is deprecated in the CSS spec
  8707. // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
  8708. // see https://github.com/angular/angular/pull/17677
  8709. var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
  8710. var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
  8711. var _polyfillHostRe = /-shadowcsshost/gim;
  8712. var _colonHostRe = /:host/gim;
  8713. var _colonHostContextRe = /:host-context/gim;
  8714. var _commentRe = /\/\*\s*[\s\S]*?\*\//g;
  8715. function stripComments(input) {
  8716. return input.replace(_commentRe, '');
  8717. }
  8718. var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
  8719. function extractCommentsWithHash(input) {
  8720. return input.match(_commentWithHashRe) || [];
  8721. }
  8722. var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
  8723. var _curlyRe = /([{}])/g;
  8724. var OPEN_CURLY = '{';
  8725. var CLOSE_CURLY = '}';
  8726. var BLOCK_PLACEHOLDER = '%BLOCK%';
  8727. var CssRule = /** @class */ (function () {
  8728. function CssRule(selector, content) {
  8729. this.selector = selector;
  8730. this.content = content;
  8731. }
  8732. return CssRule;
  8733. }());
  8734. function processRules(input, ruleCallback) {
  8735. var inputWithEscapedBlocks = escapeBlocks(input);
  8736. var nextBlockIndex = 0;
  8737. return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () {
  8738. var m = [];
  8739. for (var _i = 0; _i < arguments.length; _i++) {
  8740. m[_i] = arguments[_i];
  8741. }
  8742. var selector = m[2];
  8743. var content = '';
  8744. var suffix = m[4];
  8745. var contentPrefix = '';
  8746. if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
  8747. content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
  8748. suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
  8749. contentPrefix = '{';
  8750. }
  8751. var rule = ruleCallback(new CssRule(selector, content));
  8752. return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
  8753. });
  8754. }
  8755. var StringWithEscapedBlocks = /** @class */ (function () {
  8756. function StringWithEscapedBlocks(escapedString, blocks) {
  8757. this.escapedString = escapedString;
  8758. this.blocks = blocks;
  8759. }
  8760. return StringWithEscapedBlocks;
  8761. }());
  8762. function escapeBlocks(input) {
  8763. var inputParts = input.split(_curlyRe);
  8764. var resultParts = [];
  8765. var escapedBlocks = [];
  8766. var bracketCount = 0;
  8767. var currentBlockParts = [];
  8768. for (var partIndex = 0; partIndex < inputParts.length; partIndex++) {
  8769. var part = inputParts[partIndex];
  8770. if (part == CLOSE_CURLY) {
  8771. bracketCount--;
  8772. }
  8773. if (bracketCount > 0) {
  8774. currentBlockParts.push(part);
  8775. }
  8776. else {
  8777. if (currentBlockParts.length > 0) {
  8778. escapedBlocks.push(currentBlockParts.join(''));
  8779. resultParts.push(BLOCK_PLACEHOLDER);
  8780. currentBlockParts = [];
  8781. }
  8782. resultParts.push(part);
  8783. }
  8784. if (part == OPEN_CURLY) {
  8785. bracketCount++;
  8786. }
  8787. }
  8788. if (currentBlockParts.length > 0) {
  8789. escapedBlocks.push(currentBlockParts.join(''));
  8790. resultParts.push(BLOCK_PLACEHOLDER);
  8791. }
  8792. return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
  8793. }
  8794. /**
  8795. * @license
  8796. * Copyright Google Inc. All Rights Reserved.
  8797. *
  8798. * Use of this source code is governed by an MIT-style license that can be
  8799. * found in the LICENSE file at https://angular.io/license
  8800. */
  8801. var COMPONENT_VARIABLE = '%COMP%';
  8802. var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
  8803. var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
  8804. var StylesCompileDependency = /** @class */ (function () {
  8805. function StylesCompileDependency(name, moduleUrl, setValue) {
  8806. this.name = name;
  8807. this.moduleUrl = moduleUrl;
  8808. this.setValue = setValue;
  8809. }
  8810. return StylesCompileDependency;
  8811. }());
  8812. var CompiledStylesheet = /** @class */ (function () {
  8813. function CompiledStylesheet(outputCtx, stylesVar, dependencies, isShimmed, meta) {
  8814. this.outputCtx = outputCtx;
  8815. this.stylesVar = stylesVar;
  8816. this.dependencies = dependencies;
  8817. this.isShimmed = isShimmed;
  8818. this.meta = meta;
  8819. }
  8820. return CompiledStylesheet;
  8821. }());
  8822. var StyleCompiler = /** @class */ (function () {
  8823. function StyleCompiler(_urlResolver) {
  8824. this._urlResolver = _urlResolver;
  8825. this._shadowCss = new ShadowCss();
  8826. }
  8827. StyleCompiler.prototype.compileComponent = function (outputCtx, comp) {
  8828. var template = comp.template;
  8829. return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({
  8830. styles: template.styles,
  8831. styleUrls: template.styleUrls,
  8832. moduleUrl: identifierModuleUrl(comp.type)
  8833. }), this.needsStyleShim(comp), true);
  8834. };
  8835. StyleCompiler.prototype.compileStyles = function (outputCtx, comp, stylesheet, shim) {
  8836. if (shim === void 0) { shim = this.needsStyleShim(comp); }
  8837. return this._compileStyles(outputCtx, comp, stylesheet, shim, false);
  8838. };
  8839. StyleCompiler.prototype.needsStyleShim = function (comp) {
  8840. return comp.template.encapsulation === ViewEncapsulation.Emulated;
  8841. };
  8842. StyleCompiler.prototype._compileStyles = function (outputCtx, comp, stylesheet, shim, isComponentStylesheet) {
  8843. var _this = this;
  8844. var styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); });
  8845. var dependencies = [];
  8846. stylesheet.styleUrls.forEach(function (styleUrl) {
  8847. var exprIndex = styleExpressions.length;
  8848. // Note: This placeholder will be filled later.
  8849. styleExpressions.push(null);
  8850. dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, function (value) { return styleExpressions[exprIndex] = outputCtx.importExpr(value); }));
  8851. });
  8852. // styles variable contains plain strings and arrays of other styles arrays (recursive),
  8853. // so we set its type to dynamic.
  8854. var stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
  8855. var stmt = variable(stylesVar)
  8856. .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
  8857. .toDeclStmt(null, isComponentStylesheet ? [StmtModifier.Final] : [
  8858. StmtModifier.Final, StmtModifier.Exported
  8859. ]);
  8860. outputCtx.statements.push(stmt);
  8861. return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet);
  8862. };
  8863. StyleCompiler.prototype._shimIfNeeded = function (style, shim) {
  8864. return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style;
  8865. };
  8866. return StyleCompiler;
  8867. }());
  8868. function getStylesVarName(component) {
  8869. var result = "styles";
  8870. if (component) {
  8871. result += "_" + identifierName(component.type);
  8872. }
  8873. return result;
  8874. }
  8875. /**
  8876. * @license
  8877. * Copyright Google Inc. All Rights Reserved.
  8878. *
  8879. * Use of this source code is governed by an MIT-style license that can be
  8880. * found in the LICENSE file at https://angular.io/license
  8881. */
  8882. /**
  8883. * A path is an ordered set of elements. Typically a path is to a
  8884. * particular offset in a source file. The head of the list is the top
  8885. * most node. The tail is the node that contains the offset directly.
  8886. *
  8887. * For example, the expression `a + b + c` might have an ast that looks
  8888. * like:
  8889. * +
  8890. * / \
  8891. * a +
  8892. * / \
  8893. * b c
  8894. *
  8895. * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
  8896. * 'c' at 9-10]` and the path the node at offset 1 would be
  8897. * `['+' at 1-10, 'a' at 1-2]`.
  8898. */
  8899. var AstPath = /** @class */ (function () {
  8900. function AstPath(path, position) {
  8901. if (position === void 0) { position = -1; }
  8902. this.path = path;
  8903. this.position = position;
  8904. }
  8905. Object.defineProperty(AstPath.prototype, "empty", {
  8906. get: function () { return !this.path || !this.path.length; },
  8907. enumerable: true,
  8908. configurable: true
  8909. });
  8910. Object.defineProperty(AstPath.prototype, "head", {
  8911. get: function () { return this.path[0]; },
  8912. enumerable: true,
  8913. configurable: true
  8914. });
  8915. Object.defineProperty(AstPath.prototype, "tail", {
  8916. get: function () { return this.path[this.path.length - 1]; },
  8917. enumerable: true,
  8918. configurable: true
  8919. });
  8920. AstPath.prototype.parentOf = function (node) {
  8921. return node && this.path[this.path.indexOf(node) - 1];
  8922. };
  8923. AstPath.prototype.childOf = function (node) { return this.path[this.path.indexOf(node) + 1]; };
  8924. AstPath.prototype.first = function (ctor) {
  8925. for (var i = this.path.length - 1; i >= 0; i--) {
  8926. var item = this.path[i];
  8927. if (item instanceof ctor)
  8928. return item;
  8929. }
  8930. };
  8931. AstPath.prototype.push = function (node) { this.path.push(node); };
  8932. AstPath.prototype.pop = function () { return this.path.pop(); };
  8933. return AstPath;
  8934. }());
  8935. /**
  8936. * @license
  8937. * Copyright Google Inc. All Rights Reserved.
  8938. *
  8939. * Use of this source code is governed by an MIT-style license that can be
  8940. * found in the LICENSE file at https://angular.io/license
  8941. */
  8942. var Text$3 = /** @class */ (function () {
  8943. function Text(value, sourceSpan, i18n) {
  8944. this.value = value;
  8945. this.sourceSpan = sourceSpan;
  8946. this.i18n = i18n;
  8947. }
  8948. Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  8949. return Text;
  8950. }());
  8951. var Expansion = /** @class */ (function () {
  8952. function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
  8953. this.switchValue = switchValue;
  8954. this.type = type;
  8955. this.cases = cases;
  8956. this.sourceSpan = sourceSpan;
  8957. this.switchValueSourceSpan = switchValueSourceSpan;
  8958. this.i18n = i18n;
  8959. }
  8960. Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); };
  8961. return Expansion;
  8962. }());
  8963. var ExpansionCase = /** @class */ (function () {
  8964. function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
  8965. this.value = value;
  8966. this.expression = expression;
  8967. this.sourceSpan = sourceSpan;
  8968. this.valueSourceSpan = valueSourceSpan;
  8969. this.expSourceSpan = expSourceSpan;
  8970. }
  8971. ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); };
  8972. return ExpansionCase;
  8973. }());
  8974. var Attribute = /** @class */ (function () {
  8975. function Attribute(name, value, sourceSpan, valueSpan, i18n) {
  8976. this.name = name;
  8977. this.value = value;
  8978. this.sourceSpan = sourceSpan;
  8979. this.valueSpan = valueSpan;
  8980. this.i18n = i18n;
  8981. }
  8982. Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); };
  8983. return Attribute;
  8984. }());
  8985. var Element$1 = /** @class */ (function () {
  8986. function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  8987. if (startSourceSpan === void 0) { startSourceSpan = null; }
  8988. if (endSourceSpan === void 0) { endSourceSpan = null; }
  8989. this.name = name;
  8990. this.attrs = attrs;
  8991. this.children = children;
  8992. this.sourceSpan = sourceSpan;
  8993. this.startSourceSpan = startSourceSpan;
  8994. this.endSourceSpan = endSourceSpan;
  8995. this.i18n = i18n;
  8996. }
  8997. Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); };
  8998. return Element;
  8999. }());
  9000. var Comment = /** @class */ (function () {
  9001. function Comment(value, sourceSpan) {
  9002. this.value = value;
  9003. this.sourceSpan = sourceSpan;
  9004. }
  9005. Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); };
  9006. return Comment;
  9007. }());
  9008. function visitAll$1(visitor, nodes, context) {
  9009. if (context === void 0) { context = null; }
  9010. var result = [];
  9011. var visit = visitor.visit ?
  9012. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  9013. function (ast) { return ast.visit(visitor, context); };
  9014. nodes.forEach(function (ast) {
  9015. var astResult = visit(ast);
  9016. if (astResult) {
  9017. result.push(astResult);
  9018. }
  9019. });
  9020. return result;
  9021. }
  9022. var RecursiveVisitor = /** @class */ (function () {
  9023. function RecursiveVisitor() {
  9024. }
  9025. RecursiveVisitor.prototype.visitElement = function (ast, context) {
  9026. this.visitChildren(context, function (visit) {
  9027. visit(ast.attrs);
  9028. visit(ast.children);
  9029. });
  9030. };
  9031. RecursiveVisitor.prototype.visitAttribute = function (ast, context) { };
  9032. RecursiveVisitor.prototype.visitText = function (ast, context) { };
  9033. RecursiveVisitor.prototype.visitComment = function (ast, context) { };
  9034. RecursiveVisitor.prototype.visitExpansion = function (ast, context) {
  9035. return this.visitChildren(context, function (visit) { visit(ast.cases); });
  9036. };
  9037. RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { };
  9038. RecursiveVisitor.prototype.visitChildren = function (context, cb) {
  9039. var results = [];
  9040. var t = this;
  9041. function visit(children) {
  9042. if (children)
  9043. results.push(visitAll$1(t, children, context));
  9044. }
  9045. cb(visit);
  9046. return [].concat.apply([], results);
  9047. };
  9048. return RecursiveVisitor;
  9049. }());
  9050. function spanOf(ast) {
  9051. var start = ast.sourceSpan.start.offset;
  9052. var end = ast.sourceSpan.end.offset;
  9053. if (ast instanceof Element$1) {
  9054. if (ast.endSourceSpan) {
  9055. end = ast.endSourceSpan.end.offset;
  9056. }
  9057. else if (ast.children && ast.children.length) {
  9058. end = spanOf(ast.children[ast.children.length - 1]).end;
  9059. }
  9060. }
  9061. return { start: start, end: end };
  9062. }
  9063. function findNode(nodes, position) {
  9064. var path = [];
  9065. var visitor = new /** @class */ (function (_super) {
  9066. __extends(class_1, _super);
  9067. function class_1() {
  9068. return _super !== null && _super.apply(this, arguments) || this;
  9069. }
  9070. class_1.prototype.visit = function (ast, context) {
  9071. var span = spanOf(ast);
  9072. if (span.start <= position && position < span.end) {
  9073. path.push(ast);
  9074. }
  9075. else {
  9076. // Returning a value here will result in the children being skipped.
  9077. return true;
  9078. }
  9079. };
  9080. return class_1;
  9081. }(RecursiveVisitor));
  9082. visitAll$1(visitor, nodes);
  9083. return new AstPath(path, position);
  9084. }
  9085. /**
  9086. * @license
  9087. * Copyright Google Inc. All Rights Reserved.
  9088. *
  9089. * Use of this source code is governed by an MIT-style license that can be
  9090. * found in the LICENSE file at https://angular.io/license
  9091. */
  9092. var TokenType;
  9093. (function (TokenType) {
  9094. TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
  9095. TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
  9096. TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
  9097. TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
  9098. TokenType[TokenType["TEXT"] = 4] = "TEXT";
  9099. TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT";
  9100. TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT";
  9101. TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START";
  9102. TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END";
  9103. TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START";
  9104. TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END";
  9105. TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME";
  9106. TokenType[TokenType["ATTR_QUOTE"] = 12] = "ATTR_QUOTE";
  9107. TokenType[TokenType["ATTR_VALUE"] = 13] = "ATTR_VALUE";
  9108. TokenType[TokenType["DOC_TYPE"] = 14] = "DOC_TYPE";
  9109. TokenType[TokenType["EXPANSION_FORM_START"] = 15] = "EXPANSION_FORM_START";
  9110. TokenType[TokenType["EXPANSION_CASE_VALUE"] = 16] = "EXPANSION_CASE_VALUE";
  9111. TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 17] = "EXPANSION_CASE_EXP_START";
  9112. TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 18] = "EXPANSION_CASE_EXP_END";
  9113. TokenType[TokenType["EXPANSION_FORM_END"] = 19] = "EXPANSION_FORM_END";
  9114. TokenType[TokenType["EOF"] = 20] = "EOF";
  9115. })(TokenType || (TokenType = {}));
  9116. var Token = /** @class */ (function () {
  9117. function Token(type, parts, sourceSpan) {
  9118. this.type = type;
  9119. this.parts = parts;
  9120. this.sourceSpan = sourceSpan;
  9121. }
  9122. return Token;
  9123. }());
  9124. var TokenError = /** @class */ (function (_super) {
  9125. __extends(TokenError, _super);
  9126. function TokenError(errorMsg, tokenType, span) {
  9127. var _this = _super.call(this, span, errorMsg) || this;
  9128. _this.tokenType = tokenType;
  9129. return _this;
  9130. }
  9131. return TokenError;
  9132. }(ParseError));
  9133. var TokenizeResult = /** @class */ (function () {
  9134. function TokenizeResult(tokens, errors) {
  9135. this.tokens = tokens;
  9136. this.errors = errors;
  9137. }
  9138. return TokenizeResult;
  9139. }());
  9140. function tokenize(source, url, getTagDefinition, options) {
  9141. if (options === void 0) { options = {}; }
  9142. return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options).tokenize();
  9143. }
  9144. var _CR_OR_CRLF_REGEXP = /\r\n?/g;
  9145. function _unexpectedCharacterErrorMsg(charCode) {
  9146. var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
  9147. return "Unexpected character \"" + char + "\"";
  9148. }
  9149. function _unknownEntityErrorMsg(entitySrc) {
  9150. return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
  9151. }
  9152. var _ControlFlowError = /** @class */ (function () {
  9153. function _ControlFlowError(error) {
  9154. this.error = error;
  9155. }
  9156. return _ControlFlowError;
  9157. }());
  9158. // See http://www.w3.org/TR/html51/syntax.html#writing
  9159. var _Tokenizer = /** @class */ (function () {
  9160. /**
  9161. * @param _file The html source file being tokenized.
  9162. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
  9163. * @param options Configuration of the tokenization.
  9164. */
  9165. function _Tokenizer(_file, _getTagDefinition, options) {
  9166. this._getTagDefinition = _getTagDefinition;
  9167. this._currentTokenStart = null;
  9168. this._currentTokenType = null;
  9169. this._expansionCaseStack = [];
  9170. this._inInterpolation = false;
  9171. this.tokens = [];
  9172. this.errors = [];
  9173. this._tokenizeIcu = options.tokenizeExpansionForms || false;
  9174. this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  9175. this._leadingTriviaCodePoints =
  9176. options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; });
  9177. var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
  9178. this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
  9179. new PlainCharacterCursor(_file, range);
  9180. try {
  9181. this._cursor.init();
  9182. }
  9183. catch (e) {
  9184. this.handleError(e);
  9185. }
  9186. }
  9187. _Tokenizer.prototype._processCarriageReturns = function (content) {
  9188. // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
  9189. // In order to keep the original position in the source, we can not
  9190. // pre-process it.
  9191. // Instead CRs are processed right before instantiating the tokens.
  9192. return content.replace(_CR_OR_CRLF_REGEXP, '\n');
  9193. };
  9194. _Tokenizer.prototype.tokenize = function () {
  9195. while (this._cursor.peek() !== $EOF) {
  9196. var start = this._cursor.clone();
  9197. try {
  9198. if (this._attemptCharCode($LT)) {
  9199. if (this._attemptCharCode($BANG)) {
  9200. if (this._attemptCharCode($LBRACKET)) {
  9201. this._consumeCdata(start);
  9202. }
  9203. else if (this._attemptCharCode($MINUS)) {
  9204. this._consumeComment(start);
  9205. }
  9206. else {
  9207. this._consumeDocType(start);
  9208. }
  9209. }
  9210. else if (this._attemptCharCode($SLASH)) {
  9211. this._consumeTagClose(start);
  9212. }
  9213. else {
  9214. this._consumeTagOpen(start);
  9215. }
  9216. }
  9217. else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
  9218. this._consumeText();
  9219. }
  9220. }
  9221. catch (e) {
  9222. this.handleError(e);
  9223. }
  9224. }
  9225. this._beginToken(TokenType.EOF);
  9226. this._endToken([]);
  9227. return new TokenizeResult(mergeTextTokens(this.tokens), this.errors);
  9228. };
  9229. /**
  9230. * @returns whether an ICU token has been created
  9231. * @internal
  9232. */
  9233. _Tokenizer.prototype._tokenizeExpansionForm = function () {
  9234. if (this.isExpansionFormStart()) {
  9235. this._consumeExpansionFormStart();
  9236. return true;
  9237. }
  9238. if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
  9239. this._consumeExpansionCaseStart();
  9240. return true;
  9241. }
  9242. if (this._cursor.peek() === $RBRACE) {
  9243. if (this._isInExpansionCase()) {
  9244. this._consumeExpansionCaseEnd();
  9245. return true;
  9246. }
  9247. if (this._isInExpansionForm()) {
  9248. this._consumeExpansionFormEnd();
  9249. return true;
  9250. }
  9251. }
  9252. return false;
  9253. };
  9254. _Tokenizer.prototype._beginToken = function (type, start) {
  9255. if (start === void 0) { start = this._cursor.clone(); }
  9256. this._currentTokenStart = start;
  9257. this._currentTokenType = type;
  9258. };
  9259. _Tokenizer.prototype._endToken = function (parts, end) {
  9260. if (end === void 0) { end = this._cursor.clone(); }
  9261. if (this._currentTokenStart === null) {
  9262. throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
  9263. }
  9264. if (this._currentTokenType === null) {
  9265. throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
  9266. }
  9267. var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
  9268. this.tokens.push(token);
  9269. this._currentTokenStart = null;
  9270. this._currentTokenType = null;
  9271. return token;
  9272. };
  9273. _Tokenizer.prototype._createError = function (msg, span) {
  9274. if (this._isInExpansionForm()) {
  9275. msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)";
  9276. }
  9277. var error = new TokenError(msg, this._currentTokenType, span);
  9278. this._currentTokenStart = null;
  9279. this._currentTokenType = null;
  9280. return new _ControlFlowError(error);
  9281. };
  9282. _Tokenizer.prototype.handleError = function (e) {
  9283. if (e instanceof CursorError) {
  9284. e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
  9285. }
  9286. if (e instanceof _ControlFlowError) {
  9287. this.errors.push(e.error);
  9288. }
  9289. else {
  9290. throw e;
  9291. }
  9292. };
  9293. _Tokenizer.prototype._attemptCharCode = function (charCode) {
  9294. if (this._cursor.peek() === charCode) {
  9295. this._cursor.advance();
  9296. return true;
  9297. }
  9298. return false;
  9299. };
  9300. _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) {
  9301. if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
  9302. this._cursor.advance();
  9303. return true;
  9304. }
  9305. return false;
  9306. };
  9307. _Tokenizer.prototype._requireCharCode = function (charCode) {
  9308. var location = this._cursor.clone();
  9309. if (!this._attemptCharCode(charCode)) {
  9310. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  9311. }
  9312. };
  9313. _Tokenizer.prototype._attemptStr = function (chars) {
  9314. var len = chars.length;
  9315. if (this._cursor.charsLeft() < len) {
  9316. return false;
  9317. }
  9318. var initialPosition = this._cursor.clone();
  9319. for (var i = 0; i < len; i++) {
  9320. if (!this._attemptCharCode(chars.charCodeAt(i))) {
  9321. // If attempting to parse the string fails, we want to reset the parser
  9322. // to where it was before the attempt
  9323. this._cursor = initialPosition;
  9324. return false;
  9325. }
  9326. }
  9327. return true;
  9328. };
  9329. _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) {
  9330. for (var i = 0; i < chars.length; i++) {
  9331. if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
  9332. return false;
  9333. }
  9334. }
  9335. return true;
  9336. };
  9337. _Tokenizer.prototype._requireStr = function (chars) {
  9338. var location = this._cursor.clone();
  9339. if (!this._attemptStr(chars)) {
  9340. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  9341. }
  9342. };
  9343. _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) {
  9344. while (!predicate(this._cursor.peek())) {
  9345. this._cursor.advance();
  9346. }
  9347. };
  9348. _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) {
  9349. var start = this._cursor.clone();
  9350. this._attemptCharCodeUntilFn(predicate);
  9351. var end = this._cursor.clone();
  9352. if (end.diff(start) < len) {
  9353. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  9354. }
  9355. };
  9356. _Tokenizer.prototype._attemptUntilChar = function (char) {
  9357. while (this._cursor.peek() !== char) {
  9358. this._cursor.advance();
  9359. }
  9360. };
  9361. _Tokenizer.prototype._readChar = function (decodeEntities) {
  9362. if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
  9363. return this._decodeEntity();
  9364. }
  9365. else {
  9366. // Don't rely upon reading directly from `_input` as the actual char value
  9367. // may have been generated from an escape sequence.
  9368. var char = String.fromCodePoint(this._cursor.peek());
  9369. this._cursor.advance();
  9370. return char;
  9371. }
  9372. };
  9373. _Tokenizer.prototype._decodeEntity = function () {
  9374. var start = this._cursor.clone();
  9375. this._cursor.advance();
  9376. if (this._attemptCharCode($HASH)) {
  9377. var isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
  9378. var codeStart = this._cursor.clone();
  9379. this._attemptCharCodeUntilFn(isDigitEntityEnd);
  9380. if (this._cursor.peek() != $SEMICOLON) {
  9381. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan());
  9382. }
  9383. var strNum = this._cursor.getChars(codeStart);
  9384. this._cursor.advance();
  9385. try {
  9386. var charCode = parseInt(strNum, isHex ? 16 : 10);
  9387. return String.fromCharCode(charCode);
  9388. }
  9389. catch (_a) {
  9390. throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
  9391. }
  9392. }
  9393. else {
  9394. var nameStart = this._cursor.clone();
  9395. this._attemptCharCodeUntilFn(isNamedEntityEnd);
  9396. if (this._cursor.peek() != $SEMICOLON) {
  9397. this._cursor = nameStart;
  9398. return '&';
  9399. }
  9400. var name_1 = this._cursor.getChars(nameStart);
  9401. this._cursor.advance();
  9402. var char = NAMED_ENTITIES[name_1];
  9403. if (!char) {
  9404. throw this._createError(_unknownEntityErrorMsg(name_1), this._cursor.getSpan(start));
  9405. }
  9406. return char;
  9407. }
  9408. };
  9409. _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) {
  9410. this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
  9411. var parts = [];
  9412. while (true) {
  9413. var tagCloseStart = this._cursor.clone();
  9414. var foundEndMarker = endMarkerPredicate();
  9415. this._cursor = tagCloseStart;
  9416. if (foundEndMarker) {
  9417. break;
  9418. }
  9419. parts.push(this._readChar(decodeEntities));
  9420. }
  9421. return this._endToken([this._processCarriageReturns(parts.join(''))]);
  9422. };
  9423. _Tokenizer.prototype._consumeComment = function (start) {
  9424. var _this = this;
  9425. this._beginToken(TokenType.COMMENT_START, start);
  9426. this._requireCharCode($MINUS);
  9427. this._endToken([]);
  9428. this._consumeRawText(false, function () { return _this._attemptStr('-->'); });
  9429. this._beginToken(TokenType.COMMENT_END);
  9430. this._requireStr('-->');
  9431. this._endToken([]);
  9432. };
  9433. _Tokenizer.prototype._consumeCdata = function (start) {
  9434. var _this = this;
  9435. this._beginToken(TokenType.CDATA_START, start);
  9436. this._requireStr('CDATA[');
  9437. this._endToken([]);
  9438. this._consumeRawText(false, function () { return _this._attemptStr(']]>'); });
  9439. this._beginToken(TokenType.CDATA_END);
  9440. this._requireStr(']]>');
  9441. this._endToken([]);
  9442. };
  9443. _Tokenizer.prototype._consumeDocType = function (start) {
  9444. this._beginToken(TokenType.DOC_TYPE, start);
  9445. var contentStart = this._cursor.clone();
  9446. this._attemptUntilChar($GT);
  9447. var content = this._cursor.getChars(contentStart);
  9448. this._cursor.advance();
  9449. this._endToken([content]);
  9450. };
  9451. _Tokenizer.prototype._consumePrefixAndName = function () {
  9452. var nameOrPrefixStart = this._cursor.clone();
  9453. var prefix = '';
  9454. while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
  9455. this._cursor.advance();
  9456. }
  9457. var nameStart;
  9458. if (this._cursor.peek() === $COLON) {
  9459. prefix = this._cursor.getChars(nameOrPrefixStart);
  9460. this._cursor.advance();
  9461. nameStart = this._cursor.clone();
  9462. }
  9463. else {
  9464. nameStart = nameOrPrefixStart;
  9465. }
  9466. this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
  9467. var name = this._cursor.getChars(nameStart);
  9468. return [prefix, name];
  9469. };
  9470. _Tokenizer.prototype._consumeTagOpen = function (start) {
  9471. var tagName;
  9472. var prefix;
  9473. var openTagToken;
  9474. var tokensBeforeTagOpen = this.tokens.length;
  9475. var innerStart = this._cursor.clone();
  9476. try {
  9477. if (!isAsciiLetter(this._cursor.peek())) {
  9478. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  9479. }
  9480. openTagToken = this._consumeTagOpenStart(start);
  9481. prefix = openTagToken.parts[0];
  9482. tagName = openTagToken.parts[1];
  9483. this._attemptCharCodeUntilFn(isNotWhitespace);
  9484. while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT) {
  9485. this._consumeAttributeName();
  9486. this._attemptCharCodeUntilFn(isNotWhitespace);
  9487. if (this._attemptCharCode($EQ)) {
  9488. this._attemptCharCodeUntilFn(isNotWhitespace);
  9489. this._consumeAttributeValue();
  9490. }
  9491. this._attemptCharCodeUntilFn(isNotWhitespace);
  9492. }
  9493. this._consumeTagOpenEnd();
  9494. }
  9495. catch (e) {
  9496. if (e instanceof _ControlFlowError) {
  9497. // When the start tag is invalid (including invalid "attributes"), assume we want a "<"
  9498. this._cursor = innerStart;
  9499. if (openTagToken) {
  9500. this.tokens.length = tokensBeforeTagOpen;
  9501. }
  9502. // Back to back text tokens are merged at the end
  9503. this._beginToken(TokenType.TEXT, start);
  9504. this._endToken(['<']);
  9505. return;
  9506. }
  9507. throw e;
  9508. }
  9509. var contentTokenType = this._getTagDefinition(tagName).contentType;
  9510. if (contentTokenType === TagContentType.RAW_TEXT) {
  9511. this._consumeRawTextWithTagClose(prefix, tagName, false);
  9512. }
  9513. else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
  9514. this._consumeRawTextWithTagClose(prefix, tagName, true);
  9515. }
  9516. };
  9517. _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) {
  9518. var _this = this;
  9519. var textToken = this._consumeRawText(decodeEntities, function () {
  9520. if (!_this._attemptCharCode($LT))
  9521. return false;
  9522. if (!_this._attemptCharCode($SLASH))
  9523. return false;
  9524. _this._attemptCharCodeUntilFn(isNotWhitespace);
  9525. if (!_this._attemptStrCaseInsensitive(tagName))
  9526. return false;
  9527. _this._attemptCharCodeUntilFn(isNotWhitespace);
  9528. return _this._attemptCharCode($GT);
  9529. });
  9530. this._beginToken(TokenType.TAG_CLOSE);
  9531. this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3);
  9532. this._cursor.advance(); // Consume the `>`
  9533. this._endToken([prefix, tagName]);
  9534. };
  9535. _Tokenizer.prototype._consumeTagOpenStart = function (start) {
  9536. this._beginToken(TokenType.TAG_OPEN_START, start);
  9537. var parts = this._consumePrefixAndName();
  9538. return this._endToken(parts);
  9539. };
  9540. _Tokenizer.prototype._consumeAttributeName = function () {
  9541. var attrNameStart = this._cursor.peek();
  9542. if (attrNameStart === $SQ || attrNameStart === $DQ) {
  9543. throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
  9544. }
  9545. this._beginToken(TokenType.ATTR_NAME);
  9546. var prefixAndName = this._consumePrefixAndName();
  9547. this._endToken(prefixAndName);
  9548. };
  9549. _Tokenizer.prototype._consumeAttributeValue = function () {
  9550. var value;
  9551. if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
  9552. this._beginToken(TokenType.ATTR_QUOTE);
  9553. var quoteChar = this._cursor.peek();
  9554. this._cursor.advance();
  9555. this._endToken([String.fromCodePoint(quoteChar)]);
  9556. this._beginToken(TokenType.ATTR_VALUE);
  9557. var parts = [];
  9558. while (this._cursor.peek() !== quoteChar) {
  9559. parts.push(this._readChar(true));
  9560. }
  9561. value = parts.join('');
  9562. this._endToken([this._processCarriageReturns(value)]);
  9563. this._beginToken(TokenType.ATTR_QUOTE);
  9564. this._cursor.advance();
  9565. this._endToken([String.fromCodePoint(quoteChar)]);
  9566. }
  9567. else {
  9568. this._beginToken(TokenType.ATTR_VALUE);
  9569. var valueStart = this._cursor.clone();
  9570. this._requireCharCodeUntilFn(isNameEnd, 1);
  9571. value = this._cursor.getChars(valueStart);
  9572. this._endToken([this._processCarriageReturns(value)]);
  9573. }
  9574. };
  9575. _Tokenizer.prototype._consumeTagOpenEnd = function () {
  9576. var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
  9577. this._beginToken(tokenType);
  9578. this._requireCharCode($GT);
  9579. this._endToken([]);
  9580. };
  9581. _Tokenizer.prototype._consumeTagClose = function (start) {
  9582. this._beginToken(TokenType.TAG_CLOSE, start);
  9583. this._attemptCharCodeUntilFn(isNotWhitespace);
  9584. var prefixAndName = this._consumePrefixAndName();
  9585. this._attemptCharCodeUntilFn(isNotWhitespace);
  9586. this._requireCharCode($GT);
  9587. this._endToken(prefixAndName);
  9588. };
  9589. _Tokenizer.prototype._consumeExpansionFormStart = function () {
  9590. this._beginToken(TokenType.EXPANSION_FORM_START);
  9591. this._requireCharCode($LBRACE);
  9592. this._endToken([]);
  9593. this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
  9594. this._beginToken(TokenType.RAW_TEXT);
  9595. var condition = this._readUntil($COMMA);
  9596. this._endToken([condition]);
  9597. this._requireCharCode($COMMA);
  9598. this._attemptCharCodeUntilFn(isNotWhitespace);
  9599. this._beginToken(TokenType.RAW_TEXT);
  9600. var type = this._readUntil($COMMA);
  9601. this._endToken([type]);
  9602. this._requireCharCode($COMMA);
  9603. this._attemptCharCodeUntilFn(isNotWhitespace);
  9604. };
  9605. _Tokenizer.prototype._consumeExpansionCaseStart = function () {
  9606. this._beginToken(TokenType.EXPANSION_CASE_VALUE);
  9607. var value = this._readUntil($LBRACE).trim();
  9608. this._endToken([value]);
  9609. this._attemptCharCodeUntilFn(isNotWhitespace);
  9610. this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
  9611. this._requireCharCode($LBRACE);
  9612. this._endToken([]);
  9613. this._attemptCharCodeUntilFn(isNotWhitespace);
  9614. this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
  9615. };
  9616. _Tokenizer.prototype._consumeExpansionCaseEnd = function () {
  9617. this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
  9618. this._requireCharCode($RBRACE);
  9619. this._endToken([]);
  9620. this._attemptCharCodeUntilFn(isNotWhitespace);
  9621. this._expansionCaseStack.pop();
  9622. };
  9623. _Tokenizer.prototype._consumeExpansionFormEnd = function () {
  9624. this._beginToken(TokenType.EXPANSION_FORM_END);
  9625. this._requireCharCode($RBRACE);
  9626. this._endToken([]);
  9627. this._expansionCaseStack.pop();
  9628. };
  9629. _Tokenizer.prototype._consumeText = function () {
  9630. var start = this._cursor.clone();
  9631. this._beginToken(TokenType.TEXT, start);
  9632. var parts = [];
  9633. do {
  9634. if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
  9635. parts.push(this._interpolationConfig.start);
  9636. this._inInterpolation = true;
  9637. }
  9638. else if (this._interpolationConfig && this._inInterpolation &&
  9639. this._attemptStr(this._interpolationConfig.end)) {
  9640. parts.push(this._interpolationConfig.end);
  9641. this._inInterpolation = false;
  9642. }
  9643. else {
  9644. parts.push(this._readChar(true));
  9645. }
  9646. } while (!this._isTextEnd());
  9647. this._endToken([this._processCarriageReturns(parts.join(''))]);
  9648. };
  9649. _Tokenizer.prototype._isTextEnd = function () {
  9650. if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
  9651. return true;
  9652. }
  9653. if (this._tokenizeIcu && !this._inInterpolation) {
  9654. if (this.isExpansionFormStart()) {
  9655. // start of an expansion form
  9656. return true;
  9657. }
  9658. if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
  9659. // end of and expansion case
  9660. return true;
  9661. }
  9662. }
  9663. return false;
  9664. };
  9665. _Tokenizer.prototype._readUntil = function (char) {
  9666. var start = this._cursor.clone();
  9667. this._attemptUntilChar(char);
  9668. return this._cursor.getChars(start);
  9669. };
  9670. _Tokenizer.prototype._isInExpansionCase = function () {
  9671. return this._expansionCaseStack.length > 0 &&
  9672. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9673. TokenType.EXPANSION_CASE_EXP_START;
  9674. };
  9675. _Tokenizer.prototype._isInExpansionForm = function () {
  9676. return this._expansionCaseStack.length > 0 &&
  9677. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9678. TokenType.EXPANSION_FORM_START;
  9679. };
  9680. _Tokenizer.prototype.isExpansionFormStart = function () {
  9681. if (this._cursor.peek() !== $LBRACE) {
  9682. return false;
  9683. }
  9684. if (this._interpolationConfig) {
  9685. var start = this._cursor.clone();
  9686. var isInterpolation = this._attemptStr(this._interpolationConfig.start);
  9687. this._cursor = start;
  9688. return !isInterpolation;
  9689. }
  9690. return true;
  9691. };
  9692. return _Tokenizer;
  9693. }());
  9694. function isNotWhitespace(code) {
  9695. return !isWhitespace(code) || code === $EOF;
  9696. }
  9697. function isNameEnd(code) {
  9698. return isWhitespace(code) || code === $GT || code === $SLASH ||
  9699. code === $SQ || code === $DQ || code === $EQ;
  9700. }
  9701. function isPrefixEnd(code) {
  9702. return (code < $a || $z < code) && (code < $A || $Z < code) &&
  9703. (code < $0 || code > $9);
  9704. }
  9705. function isDigitEntityEnd(code) {
  9706. return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
  9707. }
  9708. function isNamedEntityEnd(code) {
  9709. return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
  9710. }
  9711. function isExpansionCaseStart(peek) {
  9712. return peek === $EQ || isAsciiLetter(peek) || isDigit(peek);
  9713. }
  9714. function compareCharCodeCaseInsensitive(code1, code2) {
  9715. return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
  9716. }
  9717. function toUpperCaseCharCode(code) {
  9718. return code >= $a && code <= $z ? code - $a + $A : code;
  9719. }
  9720. function mergeTextTokens(srcTokens) {
  9721. var dstTokens = [];
  9722. var lastDstToken = undefined;
  9723. for (var i = 0; i < srcTokens.length; i++) {
  9724. var token = srcTokens[i];
  9725. if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
  9726. lastDstToken.parts[0] += token.parts[0];
  9727. lastDstToken.sourceSpan.end = token.sourceSpan.end;
  9728. }
  9729. else {
  9730. lastDstToken = token;
  9731. dstTokens.push(lastDstToken);
  9732. }
  9733. }
  9734. return dstTokens;
  9735. }
  9736. var PlainCharacterCursor = /** @class */ (function () {
  9737. function PlainCharacterCursor(fileOrCursor, range) {
  9738. if (fileOrCursor instanceof PlainCharacterCursor) {
  9739. this.file = fileOrCursor.file;
  9740. this.input = fileOrCursor.input;
  9741. this.end = fileOrCursor.end;
  9742. this.state = __assign({}, fileOrCursor.state);
  9743. }
  9744. else {
  9745. if (!range) {
  9746. throw new Error('Programming error: the range argument must be provided with a file argument.');
  9747. }
  9748. this.file = fileOrCursor;
  9749. this.input = fileOrCursor.content;
  9750. this.end = range.endPos;
  9751. this.state = {
  9752. peek: -1,
  9753. offset: range.startPos,
  9754. line: range.startLine,
  9755. column: range.startCol,
  9756. };
  9757. }
  9758. }
  9759. PlainCharacterCursor.prototype.clone = function () { return new PlainCharacterCursor(this); };
  9760. PlainCharacterCursor.prototype.peek = function () { return this.state.peek; };
  9761. PlainCharacterCursor.prototype.charsLeft = function () { return this.end - this.state.offset; };
  9762. PlainCharacterCursor.prototype.diff = function (other) { return this.state.offset - other.state.offset; };
  9763. PlainCharacterCursor.prototype.advance = function () { this.advanceState(this.state); };
  9764. PlainCharacterCursor.prototype.init = function () { this.updatePeek(this.state); };
  9765. PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) {
  9766. start = start || this;
  9767. if (leadingTriviaCodePoints) {
  9768. start = start.clone();
  9769. while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
  9770. start.advance();
  9771. }
  9772. }
  9773. 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));
  9774. };
  9775. PlainCharacterCursor.prototype.getChars = function (start) {
  9776. return this.input.substring(start.state.offset, this.state.offset);
  9777. };
  9778. PlainCharacterCursor.prototype.charAt = function (pos) { return this.input.charCodeAt(pos); };
  9779. PlainCharacterCursor.prototype.advanceState = function (state) {
  9780. if (state.offset >= this.end) {
  9781. this.state = state;
  9782. throw new CursorError('Unexpected character "EOF"', this);
  9783. }
  9784. var currentChar = this.charAt(state.offset);
  9785. if (currentChar === $LF) {
  9786. state.line++;
  9787. state.column = 0;
  9788. }
  9789. else if (!isNewLine(currentChar)) {
  9790. state.column++;
  9791. }
  9792. state.offset++;
  9793. this.updatePeek(state);
  9794. };
  9795. PlainCharacterCursor.prototype.updatePeek = function (state) {
  9796. state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
  9797. };
  9798. return PlainCharacterCursor;
  9799. }());
  9800. var EscapedCharacterCursor = /** @class */ (function (_super) {
  9801. __extends(EscapedCharacterCursor, _super);
  9802. function EscapedCharacterCursor(fileOrCursor, range) {
  9803. var _this = this;
  9804. if (fileOrCursor instanceof EscapedCharacterCursor) {
  9805. _this = _super.call(this, fileOrCursor) || this;
  9806. _this.internalState = __assign({}, fileOrCursor.internalState);
  9807. }
  9808. else {
  9809. _this = _super.call(this, fileOrCursor, range) || this;
  9810. _this.internalState = _this.state;
  9811. }
  9812. return _this;
  9813. }
  9814. EscapedCharacterCursor.prototype.advance = function () {
  9815. this.state = this.internalState;
  9816. _super.prototype.advance.call(this);
  9817. this.processEscapeSequence();
  9818. };
  9819. EscapedCharacterCursor.prototype.init = function () {
  9820. _super.prototype.init.call(this);
  9821. this.processEscapeSequence();
  9822. };
  9823. EscapedCharacterCursor.prototype.clone = function () { return new EscapedCharacterCursor(this); };
  9824. EscapedCharacterCursor.prototype.getChars = function (start) {
  9825. var cursor = start.clone();
  9826. var chars = '';
  9827. while (cursor.internalState.offset < this.internalState.offset) {
  9828. chars += String.fromCodePoint(cursor.peek());
  9829. cursor.advance();
  9830. }
  9831. return chars;
  9832. };
  9833. /**
  9834. * Process the escape sequence that starts at the current position in the text.
  9835. *
  9836. * This method is called to ensure that `peek` has the unescaped value of escape sequences.
  9837. */
  9838. EscapedCharacterCursor.prototype.processEscapeSequence = function () {
  9839. var _this = this;
  9840. var peek = function () { return _this.internalState.peek; };
  9841. if (peek() === $BACKSLASH) {
  9842. // We have hit an escape sequence so we need the internal state to become independent
  9843. // of the external state.
  9844. this.internalState = __assign({}, this.state);
  9845. // Move past the backslash
  9846. this.advanceState(this.internalState);
  9847. // First check for standard control char sequences
  9848. if (peek() === $n) {
  9849. this.state.peek = $LF;
  9850. }
  9851. else if (peek() === $r) {
  9852. this.state.peek = $CR;
  9853. }
  9854. else if (peek() === $v) {
  9855. this.state.peek = $VTAB;
  9856. }
  9857. else if (peek() === $t) {
  9858. this.state.peek = $TAB;
  9859. }
  9860. else if (peek() === $b) {
  9861. this.state.peek = $BSPACE;
  9862. }
  9863. else if (peek() === $f) {
  9864. this.state.peek = $FF;
  9865. }
  9866. // Now consider more complex sequences
  9867. else if (peek() === $u) {
  9868. // Unicode code-point sequence
  9869. this.advanceState(this.internalState); // advance past the `u` char
  9870. if (peek() === $LBRACE) {
  9871. // Variable length Unicode, e.g. `\x{123}`
  9872. this.advanceState(this.internalState); // advance past the `{` char
  9873. // Advance past the variable number of hex digits until we hit a `}` char
  9874. var digitStart = this.clone();
  9875. var length_1 = 0;
  9876. while (peek() !== $RBRACE) {
  9877. this.advanceState(this.internalState);
  9878. length_1++;
  9879. }
  9880. this.state.peek = this.decodeHexDigits(digitStart, length_1);
  9881. }
  9882. else {
  9883. // Fixed length Unicode, e.g. `\u1234`
  9884. var digitStart = this.clone();
  9885. this.advanceState(this.internalState);
  9886. this.advanceState(this.internalState);
  9887. this.advanceState(this.internalState);
  9888. this.state.peek = this.decodeHexDigits(digitStart, 4);
  9889. }
  9890. }
  9891. else if (peek() === $x) {
  9892. // Hex char code, e.g. `\x2F`
  9893. this.advanceState(this.internalState); // advance past the `x` char
  9894. var digitStart = this.clone();
  9895. this.advanceState(this.internalState);
  9896. this.state.peek = this.decodeHexDigits(digitStart, 2);
  9897. }
  9898. else if (isOctalDigit(peek())) {
  9899. // Octal char code, e.g. `\012`,
  9900. var octal = '';
  9901. var length_2 = 0;
  9902. var previous = this.clone();
  9903. while (isOctalDigit(peek()) && length_2 < 3) {
  9904. previous = this.clone();
  9905. octal += String.fromCodePoint(peek());
  9906. this.advanceState(this.internalState);
  9907. length_2++;
  9908. }
  9909. this.state.peek = parseInt(octal, 8);
  9910. // Backup one char
  9911. this.internalState = previous.internalState;
  9912. }
  9913. else if (isNewLine(this.internalState.peek)) {
  9914. // Line continuation `\` followed by a new line
  9915. this.advanceState(this.internalState); // advance over the newline
  9916. this.state = this.internalState;
  9917. }
  9918. else {
  9919. // If none of the `if` blocks were executed then we just have an escaped normal character.
  9920. // In that case we just, effectively, skip the backslash from the character.
  9921. this.state.peek = this.internalState.peek;
  9922. }
  9923. }
  9924. };
  9925. EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) {
  9926. var hex = this.input.substr(start.internalState.offset, length);
  9927. var charCode = parseInt(hex, 16);
  9928. if (!isNaN(charCode)) {
  9929. return charCode;
  9930. }
  9931. else {
  9932. start.state = start.internalState;
  9933. throw new CursorError('Invalid hexadecimal escape sequence', start);
  9934. }
  9935. };
  9936. return EscapedCharacterCursor;
  9937. }(PlainCharacterCursor));
  9938. var CursorError = /** @class */ (function () {
  9939. function CursorError(msg, cursor) {
  9940. this.msg = msg;
  9941. this.cursor = cursor;
  9942. }
  9943. return CursorError;
  9944. }());
  9945. /**
  9946. * @license
  9947. * Copyright Google Inc. All Rights Reserved.
  9948. *
  9949. * Use of this source code is governed by an MIT-style license that can be
  9950. * found in the LICENSE file at https://angular.io/license
  9951. */
  9952. var TreeError = /** @class */ (function (_super) {
  9953. __extends(TreeError, _super);
  9954. function TreeError(elementName, span, msg) {
  9955. var _this = _super.call(this, span, msg) || this;
  9956. _this.elementName = elementName;
  9957. return _this;
  9958. }
  9959. TreeError.create = function (elementName, span, msg) {
  9960. return new TreeError(elementName, span, msg);
  9961. };
  9962. return TreeError;
  9963. }(ParseError));
  9964. var ParseTreeResult = /** @class */ (function () {
  9965. function ParseTreeResult(rootNodes, errors) {
  9966. this.rootNodes = rootNodes;
  9967. this.errors = errors;
  9968. }
  9969. return ParseTreeResult;
  9970. }());
  9971. var Parser = /** @class */ (function () {
  9972. function Parser(getTagDefinition) {
  9973. this.getTagDefinition = getTagDefinition;
  9974. }
  9975. Parser.prototype.parse = function (source, url, options) {
  9976. var tokensAndErrors = tokenize(source, url, this.getTagDefinition, options);
  9977. var treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
  9978. return new ParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors));
  9979. };
  9980. return Parser;
  9981. }());
  9982. var _TreeBuilder = /** @class */ (function () {
  9983. function _TreeBuilder(tokens, getTagDefinition) {
  9984. this.tokens = tokens;
  9985. this.getTagDefinition = getTagDefinition;
  9986. this._index = -1;
  9987. this._rootNodes = [];
  9988. this._errors = [];
  9989. this._elementStack = [];
  9990. this._advance();
  9991. }
  9992. _TreeBuilder.prototype.build = function () {
  9993. while (this._peek.type !== TokenType.EOF) {
  9994. if (this._peek.type === TokenType.TAG_OPEN_START) {
  9995. this._consumeStartTag(this._advance());
  9996. }
  9997. else if (this._peek.type === TokenType.TAG_CLOSE) {
  9998. this._consumeEndTag(this._advance());
  9999. }
  10000. else if (this._peek.type === TokenType.CDATA_START) {
  10001. this._closeVoidElement();
  10002. this._consumeCdata(this._advance());
  10003. }
  10004. else if (this._peek.type === TokenType.COMMENT_START) {
  10005. this._closeVoidElement();
  10006. this._consumeComment(this._advance());
  10007. }
  10008. else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
  10009. this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
  10010. this._closeVoidElement();
  10011. this._consumeText(this._advance());
  10012. }
  10013. else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
  10014. this._consumeExpansion(this._advance());
  10015. }
  10016. else {
  10017. // Skip all other tokens...
  10018. this._advance();
  10019. }
  10020. }
  10021. return new ParseTreeResult(this._rootNodes, this._errors);
  10022. };
  10023. _TreeBuilder.prototype._advance = function () {
  10024. var prev = this._peek;
  10025. if (this._index < this.tokens.length - 1) {
  10026. // Note: there is always an EOF token at the end
  10027. this._index++;
  10028. }
  10029. this._peek = this.tokens[this._index];
  10030. return prev;
  10031. };
  10032. _TreeBuilder.prototype._advanceIf = function (type) {
  10033. if (this._peek.type === type) {
  10034. return this._advance();
  10035. }
  10036. return null;
  10037. };
  10038. _TreeBuilder.prototype._consumeCdata = function (startToken) {
  10039. this._consumeText(this._advance());
  10040. this._advanceIf(TokenType.CDATA_END);
  10041. };
  10042. _TreeBuilder.prototype._consumeComment = function (token) {
  10043. var text = this._advanceIf(TokenType.RAW_TEXT);
  10044. this._advanceIf(TokenType.COMMENT_END);
  10045. var value = text != null ? text.parts[0].trim() : null;
  10046. this._addToParent(new Comment(value, token.sourceSpan));
  10047. };
  10048. _TreeBuilder.prototype._consumeExpansion = function (token) {
  10049. var switchValue = this._advance();
  10050. var type = this._advance();
  10051. var cases = [];
  10052. // read =
  10053. while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
  10054. var expCase = this._parseExpansionCase();
  10055. if (!expCase)
  10056. return; // error
  10057. cases.push(expCase);
  10058. }
  10059. // read the final }
  10060. if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
  10061. this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'."));
  10062. return;
  10063. }
  10064. var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
  10065. this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
  10066. this._advance();
  10067. };
  10068. _TreeBuilder.prototype._parseExpansionCase = function () {
  10069. var value = this._advance();
  10070. // read {
  10071. if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
  10072. this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'."));
  10073. return null;
  10074. }
  10075. // read until }
  10076. var start = this._advance();
  10077. var exp = this._collectExpansionExpTokens(start);
  10078. if (!exp)
  10079. return null;
  10080. var end = this._advance();
  10081. exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
  10082. // parse everything in between { and }
  10083. var parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
  10084. if (parsedExp.errors.length > 0) {
  10085. this._errors = this._errors.concat(parsedExp.errors);
  10086. return null;
  10087. }
  10088. var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
  10089. var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
  10090. return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
  10091. };
  10092. _TreeBuilder.prototype._collectExpansionExpTokens = function (start) {
  10093. var exp = [];
  10094. var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
  10095. while (true) {
  10096. if (this._peek.type === TokenType.EXPANSION_FORM_START ||
  10097. this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
  10098. expansionFormStack.push(this._peek.type);
  10099. }
  10100. if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
  10101. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
  10102. expansionFormStack.pop();
  10103. if (expansionFormStack.length == 0)
  10104. return exp;
  10105. }
  10106. else {
  10107. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  10108. return null;
  10109. }
  10110. }
  10111. if (this._peek.type === TokenType.EXPANSION_FORM_END) {
  10112. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
  10113. expansionFormStack.pop();
  10114. }
  10115. else {
  10116. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  10117. return null;
  10118. }
  10119. }
  10120. if (this._peek.type === TokenType.EOF) {
  10121. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  10122. return null;
  10123. }
  10124. exp.push(this._advance());
  10125. }
  10126. };
  10127. _TreeBuilder.prototype._consumeText = function (token) {
  10128. var text = token.parts[0];
  10129. if (text.length > 0 && text[0] == '\n') {
  10130. var parent_1 = this._getParentElement();
  10131. if (parent_1 != null && parent_1.children.length == 0 &&
  10132. this.getTagDefinition(parent_1.name).ignoreFirstLf) {
  10133. text = text.substring(1);
  10134. }
  10135. }
  10136. if (text.length > 0) {
  10137. this._addToParent(new Text$3(text, token.sourceSpan));
  10138. }
  10139. };
  10140. _TreeBuilder.prototype._closeVoidElement = function () {
  10141. var el = this._getParentElement();
  10142. if (el && this.getTagDefinition(el.name).isVoid) {
  10143. this._elementStack.pop();
  10144. }
  10145. };
  10146. _TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
  10147. var prefix = startTagToken.parts[0];
  10148. var name = startTagToken.parts[1];
  10149. var attrs = [];
  10150. while (this._peek.type === TokenType.ATTR_NAME) {
  10151. attrs.push(this._consumeAttr(this._advance()));
  10152. }
  10153. var fullName = this._getElementFullName(prefix, name, this._getParentElement());
  10154. var selfClosing = false;
  10155. // Note: There could have been a tokenizer error
  10156. // so that we don't get a token for the end tag...
  10157. if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
  10158. this._advance();
  10159. selfClosing = true;
  10160. var tagDef = this.getTagDefinition(fullName);
  10161. if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
  10162. this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
  10163. }
  10164. }
  10165. else if (this._peek.type === TokenType.TAG_OPEN_END) {
  10166. this._advance();
  10167. selfClosing = false;
  10168. }
  10169. var end = this._peek.sourceSpan.start;
  10170. var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
  10171. var el = new Element$1(fullName, attrs, [], span, span, undefined);
  10172. this._pushElement(el);
  10173. if (selfClosing) {
  10174. this._popElement(fullName);
  10175. el.endSourceSpan = span;
  10176. }
  10177. };
  10178. _TreeBuilder.prototype._pushElement = function (el) {
  10179. var parentEl = this._getParentElement();
  10180. if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
  10181. this._elementStack.pop();
  10182. }
  10183. this._addToParent(el);
  10184. this._elementStack.push(el);
  10185. };
  10186. _TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
  10187. var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
  10188. if (this._getParentElement()) {
  10189. this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
  10190. }
  10191. if (this.getTagDefinition(fullName).isVoid) {
  10192. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
  10193. }
  10194. else if (!this._popElement(fullName)) {
  10195. var errMsg = "Unexpected closing tag \"" + fullName + "\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags";
  10196. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
  10197. }
  10198. };
  10199. _TreeBuilder.prototype._popElement = function (fullName) {
  10200. for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
  10201. var el = this._elementStack[stackIndex];
  10202. if (el.name == fullName) {
  10203. this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
  10204. return true;
  10205. }
  10206. if (!this.getTagDefinition(el.name).closedByParent) {
  10207. return false;
  10208. }
  10209. }
  10210. return false;
  10211. };
  10212. _TreeBuilder.prototype._consumeAttr = function (attrName) {
  10213. var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
  10214. var end = attrName.sourceSpan.end;
  10215. var value = '';
  10216. var valueSpan = undefined;
  10217. if (this._peek.type === TokenType.ATTR_QUOTE) {
  10218. this._advance();
  10219. }
  10220. if (this._peek.type === TokenType.ATTR_VALUE) {
  10221. var valueToken = this._advance();
  10222. value = valueToken.parts[0];
  10223. end = valueToken.sourceSpan.end;
  10224. valueSpan = valueToken.sourceSpan;
  10225. }
  10226. if (this._peek.type === TokenType.ATTR_QUOTE) {
  10227. var quoteToken = this._advance();
  10228. end = quoteToken.sourceSpan.end;
  10229. }
  10230. return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan);
  10231. };
  10232. _TreeBuilder.prototype._getParentElement = function () {
  10233. return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
  10234. };
  10235. /**
  10236. * Returns the parent in the DOM and the container.
  10237. *
  10238. * `<ng-container>` elements are skipped as they are not rendered as DOM element.
  10239. */
  10240. _TreeBuilder.prototype._getParentElementSkippingContainers = function () {
  10241. var container = null;
  10242. for (var i = this._elementStack.length - 1; i >= 0; i--) {
  10243. if (!isNgContainer(this._elementStack[i].name)) {
  10244. return { parent: this._elementStack[i], container: container };
  10245. }
  10246. container = this._elementStack[i];
  10247. }
  10248. return { parent: null, container: container };
  10249. };
  10250. _TreeBuilder.prototype._addToParent = function (node) {
  10251. var parent = this._getParentElement();
  10252. if (parent != null) {
  10253. parent.children.push(node);
  10254. }
  10255. else {
  10256. this._rootNodes.push(node);
  10257. }
  10258. };
  10259. /**
  10260. * Insert a node between the parent and the container.
  10261. * When no container is given, the node is appended as a child of the parent.
  10262. * Also updates the element stack accordingly.
  10263. *
  10264. * @internal
  10265. */
  10266. _TreeBuilder.prototype._insertBeforeContainer = function (parent, container, node) {
  10267. if (!container) {
  10268. this._addToParent(node);
  10269. this._elementStack.push(node);
  10270. }
  10271. else {
  10272. if (parent) {
  10273. // replace the container with the new node in the children
  10274. var index = parent.children.indexOf(container);
  10275. parent.children[index] = node;
  10276. }
  10277. else {
  10278. this._rootNodes.push(node);
  10279. }
  10280. node.children.push(container);
  10281. this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
  10282. }
  10283. };
  10284. _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) {
  10285. if (prefix === '') {
  10286. prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
  10287. if (prefix === '' && parentElement != null) {
  10288. prefix = getNsPrefix(parentElement.name);
  10289. }
  10290. }
  10291. return mergeNsAndName(prefix, localName);
  10292. };
  10293. return _TreeBuilder;
  10294. }());
  10295. function lastOnStack(stack, element) {
  10296. return stack.length > 0 && stack[stack.length - 1] === element;
  10297. }
  10298. /**
  10299. * @license
  10300. * Copyright Google Inc. All Rights Reserved.
  10301. *
  10302. * Use of this source code is governed by an MIT-style license that can be
  10303. * found in the LICENSE file at https://angular.io/license
  10304. */
  10305. var HtmlParser = /** @class */ (function (_super) {
  10306. __extends(HtmlParser, _super);
  10307. function HtmlParser() {
  10308. return _super.call(this, getHtmlTagDefinition) || this;
  10309. }
  10310. HtmlParser.prototype.parse = function (source, url, options) {
  10311. return _super.prototype.parse.call(this, source, url, options);
  10312. };
  10313. return HtmlParser;
  10314. }(Parser));
  10315. /**
  10316. * @license
  10317. * Copyright Google Inc. All Rights Reserved.
  10318. *
  10319. * Use of this source code is governed by an MIT-style license that can be
  10320. * found in the LICENSE file at https://angular.io/license
  10321. */
  10322. var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
  10323. var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
  10324. // Equivalent to \s with \u00a0 (non-breaking space) excluded.
  10325. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  10326. var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
  10327. var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]");
  10328. var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g');
  10329. function hasPreserveWhitespacesAttr(attrs) {
  10330. return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; });
  10331. }
  10332. /**
  10333. * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
  10334. * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
  10335. * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
  10336. * and later on replaced by a space. We are re-implementing the same idea here.
  10337. */
  10338. function replaceNgsp(value) {
  10339. // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
  10340. return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
  10341. }
  10342. /**
  10343. * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
  10344. * - consider spaces, tabs and new lines as whitespace characters;
  10345. * - drop text nodes consisting of whitespace characters only;
  10346. * - for all other text nodes replace consecutive whitespace characters with one space;
  10347. * - convert &ngsp; pseudo-entity to a single space;
  10348. *
  10349. * Removal and trimming of whitespaces have positive performance impact (less code to generate
  10350. * while compiling templates, faster view creation). At the same time it can be "destructive"
  10351. * in some cases (whitespaces can influence layout). Because of the potential of breaking layout
  10352. * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
  10353. * whitespace removal. The default option for whitespace removal will be revisited in Angular 6
  10354. * and might be changed to "on" by default.
  10355. */
  10356. var WhitespaceVisitor = /** @class */ (function () {
  10357. function WhitespaceVisitor() {
  10358. }
  10359. WhitespaceVisitor.prototype.visitElement = function (element, context) {
  10360. if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
  10361. // don't descent into elements where we need to preserve whitespaces
  10362. // but still visit all attributes to eliminate one used as a market to preserve WS
  10363. return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  10364. }
  10365. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  10366. };
  10367. WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) {
  10368. return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
  10369. };
  10370. WhitespaceVisitor.prototype.visitText = function (text, context) {
  10371. var isNotBlank = text.value.match(NO_WS_REGEXP);
  10372. if (isNotBlank) {
  10373. return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
  10374. }
  10375. return null;
  10376. };
  10377. WhitespaceVisitor.prototype.visitComment = function (comment, context) { return comment; };
  10378. WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
  10379. WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  10380. return WhitespaceVisitor;
  10381. }());
  10382. function removeWhitespaces(htmlAstWithErrors) {
  10383. return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
  10384. }
  10385. /**
  10386. * @license
  10387. * Copyright Google Inc. All Rights Reserved.
  10388. *
  10389. * Use of this source code is governed by an MIT-style license that can be
  10390. * found in the LICENSE file at https://angular.io/license
  10391. */
  10392. // http://cldr.unicode.org/index/cldr-spec/plural-rules
  10393. var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
  10394. /**
  10395. * Expands special forms into elements.
  10396. *
  10397. * For example,
  10398. *
  10399. * ```
  10400. * { messages.length, plural,
  10401. * =0 {zero}
  10402. * =1 {one}
  10403. * other {more than one}
  10404. * }
  10405. * ```
  10406. *
  10407. * will be expanded into
  10408. *
  10409. * ```
  10410. * <ng-container [ngPlural]="messages.length">
  10411. * <ng-template ngPluralCase="=0">zero</ng-template>
  10412. * <ng-template ngPluralCase="=1">one</ng-template>
  10413. * <ng-template ngPluralCase="other">more than one</ng-template>
  10414. * </ng-container>
  10415. * ```
  10416. */
  10417. function expandNodes(nodes) {
  10418. var expander = new _Expander();
  10419. return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
  10420. }
  10421. var ExpansionResult = /** @class */ (function () {
  10422. function ExpansionResult(nodes, expanded, errors) {
  10423. this.nodes = nodes;
  10424. this.expanded = expanded;
  10425. this.errors = errors;
  10426. }
  10427. return ExpansionResult;
  10428. }());
  10429. var ExpansionError = /** @class */ (function (_super) {
  10430. __extends(ExpansionError, _super);
  10431. function ExpansionError(span, errorMsg) {
  10432. return _super.call(this, span, errorMsg) || this;
  10433. }
  10434. return ExpansionError;
  10435. }(ParseError));
  10436. /**
  10437. * Expand expansion forms (plural, select) to directives
  10438. *
  10439. * @internal
  10440. */
  10441. var _Expander = /** @class */ (function () {
  10442. function _Expander() {
  10443. this.isExpanded = false;
  10444. this.errors = [];
  10445. }
  10446. _Expander.prototype.visitElement = function (element, context) {
  10447. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
  10448. };
  10449. _Expander.prototype.visitAttribute = function (attribute, context) { return attribute; };
  10450. _Expander.prototype.visitText = function (text, context) { return text; };
  10451. _Expander.prototype.visitComment = function (comment, context) { return comment; };
  10452. _Expander.prototype.visitExpansion = function (icu, context) {
  10453. this.isExpanded = true;
  10454. return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
  10455. _expandDefaultForm(icu, this.errors);
  10456. };
  10457. _Expander.prototype.visitExpansionCase = function (icuCase, context) {
  10458. throw new Error('Should not be reached');
  10459. };
  10460. return _Expander;
  10461. }());
  10462. // Plural forms are expanded to `NgPlural` and `NgPluralCase`s
  10463. function _expandPluralForm(ast, errors) {
  10464. var children = ast.cases.map(function (c) {
  10465. if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
  10466. errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=<number>\" or one of " + PLURAL_CASES.join(", ")));
  10467. }
  10468. var expansionResult = expandNodes(c.expression);
  10469. errors.push.apply(errors, __spread(expansionResult.errors));
  10470. return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10471. });
  10472. var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan);
  10473. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  10474. }
  10475. // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
  10476. function _expandDefaultForm(ast, errors) {
  10477. var children = ast.cases.map(function (c) {
  10478. var expansionResult = expandNodes(c.expression);
  10479. errors.push.apply(errors, __spread(expansionResult.errors));
  10480. if (c.value === 'other') {
  10481. // other is the default case when no values match
  10482. return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10483. }
  10484. return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10485. });
  10486. var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan);
  10487. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  10488. }
  10489. /**
  10490. * @license
  10491. * Copyright Google Inc. All Rights Reserved.
  10492. *
  10493. * Use of this source code is governed by an MIT-style license that can be
  10494. * found in the LICENSE file at https://angular.io/license
  10495. */
  10496. var _a;
  10497. /**
  10498. * A segment of text within the template.
  10499. */
  10500. var TextAst = /** @class */ (function () {
  10501. function TextAst(value, ngContentIndex, sourceSpan) {
  10502. this.value = value;
  10503. this.ngContentIndex = ngContentIndex;
  10504. this.sourceSpan = sourceSpan;
  10505. }
  10506. TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  10507. return TextAst;
  10508. }());
  10509. /**
  10510. * A bound expression within the text of a template.
  10511. */
  10512. var BoundTextAst = /** @class */ (function () {
  10513. function BoundTextAst(value, ngContentIndex, sourceSpan) {
  10514. this.value = value;
  10515. this.ngContentIndex = ngContentIndex;
  10516. this.sourceSpan = sourceSpan;
  10517. }
  10518. BoundTextAst.prototype.visit = function (visitor, context) {
  10519. return visitor.visitBoundText(this, context);
  10520. };
  10521. return BoundTextAst;
  10522. }());
  10523. /**
  10524. * A plain attribute on an element.
  10525. */
  10526. var AttrAst = /** @class */ (function () {
  10527. function AttrAst(name, value, sourceSpan) {
  10528. this.name = name;
  10529. this.value = value;
  10530. this.sourceSpan = sourceSpan;
  10531. }
  10532. AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
  10533. return AttrAst;
  10534. }());
  10535. var BoundPropertyMapping = (_a = {},
  10536. _a[4 /* Animation */] = 4 /* Animation */,
  10537. _a[1 /* Attribute */] = 1 /* Attribute */,
  10538. _a[2 /* Class */] = 2 /* Class */,
  10539. _a[0 /* Property */] = 0 /* Property */,
  10540. _a[3 /* Style */] = 3 /* Style */,
  10541. _a);
  10542. /**
  10543. * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
  10544. * `[@trigger]="stateExp"`)
  10545. */
  10546. var BoundElementPropertyAst = /** @class */ (function () {
  10547. function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) {
  10548. this.name = name;
  10549. this.type = type;
  10550. this.securityContext = securityContext;
  10551. this.value = value;
  10552. this.unit = unit;
  10553. this.sourceSpan = sourceSpan;
  10554. this.isAnimation = this.type === 4 /* Animation */;
  10555. }
  10556. BoundElementPropertyAst.fromBoundProperty = function (prop) {
  10557. var type = BoundPropertyMapping[prop.type];
  10558. return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
  10559. };
  10560. BoundElementPropertyAst.prototype.visit = function (visitor, context) {
  10561. return visitor.visitElementProperty(this, context);
  10562. };
  10563. return BoundElementPropertyAst;
  10564. }());
  10565. /**
  10566. * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
  10567. * `(@trigger.phase)="callback($event)"`).
  10568. */
  10569. var BoundEventAst = /** @class */ (function () {
  10570. function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) {
  10571. this.name = name;
  10572. this.target = target;
  10573. this.phase = phase;
  10574. this.handler = handler;
  10575. this.sourceSpan = sourceSpan;
  10576. this.handlerSpan = handlerSpan;
  10577. this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
  10578. this.isAnimation = !!this.phase;
  10579. }
  10580. BoundEventAst.calcFullName = function (name, target, phase) {
  10581. if (target) {
  10582. return target + ":" + name;
  10583. }
  10584. if (phase) {
  10585. return "@" + name + "." + phase;
  10586. }
  10587. return name;
  10588. };
  10589. BoundEventAst.fromParsedEvent = function (event) {
  10590. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  10591. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  10592. return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
  10593. };
  10594. BoundEventAst.prototype.visit = function (visitor, context) {
  10595. return visitor.visitEvent(this, context);
  10596. };
  10597. return BoundEventAst;
  10598. }());
  10599. /**
  10600. * A reference declaration on an element (e.g. `let someName="expression"`).
  10601. */
  10602. var ReferenceAst = /** @class */ (function () {
  10603. function ReferenceAst(name, value, originalValue, sourceSpan) {
  10604. this.name = name;
  10605. this.value = value;
  10606. this.originalValue = originalValue;
  10607. this.sourceSpan = sourceSpan;
  10608. }
  10609. ReferenceAst.prototype.visit = function (visitor, context) {
  10610. return visitor.visitReference(this, context);
  10611. };
  10612. return ReferenceAst;
  10613. }());
  10614. /**
  10615. * A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
  10616. */
  10617. var VariableAst = /** @class */ (function () {
  10618. function VariableAst(name, value, sourceSpan) {
  10619. this.name = name;
  10620. this.value = value;
  10621. this.sourceSpan = sourceSpan;
  10622. }
  10623. VariableAst.fromParsedVariable = function (v) {
  10624. return new VariableAst(v.name, v.value, v.sourceSpan);
  10625. };
  10626. VariableAst.prototype.visit = function (visitor, context) {
  10627. return visitor.visitVariable(this, context);
  10628. };
  10629. return VariableAst;
  10630. }());
  10631. /**
  10632. * An element declaration in a template.
  10633. */
  10634. var ElementAst = /** @class */ (function () {
  10635. function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
  10636. this.name = name;
  10637. this.attrs = attrs;
  10638. this.inputs = inputs;
  10639. this.outputs = outputs;
  10640. this.references = references;
  10641. this.directives = directives;
  10642. this.providers = providers;
  10643. this.hasViewContainer = hasViewContainer;
  10644. this.queryMatches = queryMatches;
  10645. this.children = children;
  10646. this.ngContentIndex = ngContentIndex;
  10647. this.sourceSpan = sourceSpan;
  10648. this.endSourceSpan = endSourceSpan;
  10649. }
  10650. ElementAst.prototype.visit = function (visitor, context) {
  10651. return visitor.visitElement(this, context);
  10652. };
  10653. return ElementAst;
  10654. }());
  10655. /**
  10656. * A `<ng-template>` element included in an Angular template.
  10657. */
  10658. var EmbeddedTemplateAst = /** @class */ (function () {
  10659. function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
  10660. this.attrs = attrs;
  10661. this.outputs = outputs;
  10662. this.references = references;
  10663. this.variables = variables;
  10664. this.directives = directives;
  10665. this.providers = providers;
  10666. this.hasViewContainer = hasViewContainer;
  10667. this.queryMatches = queryMatches;
  10668. this.children = children;
  10669. this.ngContentIndex = ngContentIndex;
  10670. this.sourceSpan = sourceSpan;
  10671. }
  10672. EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
  10673. return visitor.visitEmbeddedTemplate(this, context);
  10674. };
  10675. return EmbeddedTemplateAst;
  10676. }());
  10677. /**
  10678. * A directive property with a bound value (e.g. `*ngIf="condition").
  10679. */
  10680. var BoundDirectivePropertyAst = /** @class */ (function () {
  10681. function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
  10682. this.directiveName = directiveName;
  10683. this.templateName = templateName;
  10684. this.value = value;
  10685. this.sourceSpan = sourceSpan;
  10686. }
  10687. BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
  10688. return visitor.visitDirectiveProperty(this, context);
  10689. };
  10690. return BoundDirectivePropertyAst;
  10691. }());
  10692. /**
  10693. * A directive declared on an element.
  10694. */
  10695. var DirectiveAst = /** @class */ (function () {
  10696. function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
  10697. this.directive = directive;
  10698. this.inputs = inputs;
  10699. this.hostProperties = hostProperties;
  10700. this.hostEvents = hostEvents;
  10701. this.contentQueryStartId = contentQueryStartId;
  10702. this.sourceSpan = sourceSpan;
  10703. }
  10704. DirectiveAst.prototype.visit = function (visitor, context) {
  10705. return visitor.visitDirective(this, context);
  10706. };
  10707. return DirectiveAst;
  10708. }());
  10709. /**
  10710. * A provider declared on an element
  10711. */
  10712. var ProviderAst = /** @class */ (function () {
  10713. function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
  10714. this.token = token;
  10715. this.multiProvider = multiProvider;
  10716. this.eager = eager;
  10717. this.providers = providers;
  10718. this.providerType = providerType;
  10719. this.lifecycleHooks = lifecycleHooks;
  10720. this.sourceSpan = sourceSpan;
  10721. this.isModule = isModule;
  10722. }
  10723. ProviderAst.prototype.visit = function (visitor, context) {
  10724. // No visit method in the visitor for now...
  10725. return null;
  10726. };
  10727. return ProviderAst;
  10728. }());
  10729. var ProviderAstType;
  10730. (function (ProviderAstType) {
  10731. ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
  10732. ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
  10733. ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
  10734. ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
  10735. ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
  10736. })(ProviderAstType || (ProviderAstType = {}));
  10737. /**
  10738. * Position where content is to be projected (instance of `<ng-content>` in a template).
  10739. */
  10740. var NgContentAst = /** @class */ (function () {
  10741. function NgContentAst(index, ngContentIndex, sourceSpan) {
  10742. this.index = index;
  10743. this.ngContentIndex = ngContentIndex;
  10744. this.sourceSpan = sourceSpan;
  10745. }
  10746. NgContentAst.prototype.visit = function (visitor, context) {
  10747. return visitor.visitNgContent(this, context);
  10748. };
  10749. return NgContentAst;
  10750. }());
  10751. /**
  10752. * A visitor that accepts each node but doesn't do anything. It is intended to be used
  10753. * as the base class for a visitor that is only interested in a subset of the node types.
  10754. */
  10755. var NullTemplateVisitor = /** @class */ (function () {
  10756. function NullTemplateVisitor() {
  10757. }
  10758. NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { };
  10759. NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { };
  10760. NullTemplateVisitor.prototype.visitElement = function (ast, context) { };
  10761. NullTemplateVisitor.prototype.visitReference = function (ast, context) { };
  10762. NullTemplateVisitor.prototype.visitVariable = function (ast, context) { };
  10763. NullTemplateVisitor.prototype.visitEvent = function (ast, context) { };
  10764. NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { };
  10765. NullTemplateVisitor.prototype.visitAttr = function (ast, context) { };
  10766. NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { };
  10767. NullTemplateVisitor.prototype.visitText = function (ast, context) { };
  10768. NullTemplateVisitor.prototype.visitDirective = function (ast, context) { };
  10769. NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { };
  10770. return NullTemplateVisitor;
  10771. }());
  10772. /**
  10773. * Base class that can be used to build a visitor that visits each node
  10774. * in an template ast recursively.
  10775. */
  10776. var RecursiveTemplateAstVisitor = /** @class */ (function (_super) {
  10777. __extends(RecursiveTemplateAstVisitor, _super);
  10778. function RecursiveTemplateAstVisitor() {
  10779. return _super.call(this) || this;
  10780. }
  10781. // Nodes with children
  10782. RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
  10783. return this.visitChildren(context, function (visit) {
  10784. visit(ast.attrs);
  10785. visit(ast.references);
  10786. visit(ast.variables);
  10787. visit(ast.directives);
  10788. visit(ast.providers);
  10789. visit(ast.children);
  10790. });
  10791. };
  10792. RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) {
  10793. return this.visitChildren(context, function (visit) {
  10794. visit(ast.attrs);
  10795. visit(ast.inputs);
  10796. visit(ast.outputs);
  10797. visit(ast.references);
  10798. visit(ast.directives);
  10799. visit(ast.providers);
  10800. visit(ast.children);
  10801. });
  10802. };
  10803. RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) {
  10804. return this.visitChildren(context, function (visit) {
  10805. visit(ast.inputs);
  10806. visit(ast.hostProperties);
  10807. visit(ast.hostEvents);
  10808. });
  10809. };
  10810. RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) {
  10811. var results = [];
  10812. var t = this;
  10813. function visit(children) {
  10814. if (children && children.length)
  10815. results.push(templateVisitAll(t, children, context));
  10816. }
  10817. cb(visit);
  10818. return [].concat.apply([], results);
  10819. };
  10820. return RecursiveTemplateAstVisitor;
  10821. }(NullTemplateVisitor));
  10822. /**
  10823. * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
  10824. */
  10825. function templateVisitAll(visitor, asts, context) {
  10826. if (context === void 0) { context = null; }
  10827. var result = [];
  10828. var visit = visitor.visit ?
  10829. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  10830. function (ast) { return ast.visit(visitor, context); };
  10831. asts.forEach(function (ast) {
  10832. var astResult = visit(ast);
  10833. if (astResult) {
  10834. result.push(astResult);
  10835. }
  10836. });
  10837. return result;
  10838. }
  10839. /**
  10840. * @license
  10841. * Copyright Google Inc. All Rights Reserved.
  10842. *
  10843. * Use of this source code is governed by an MIT-style license that can be
  10844. * found in the LICENSE file at https://angular.io/license
  10845. */
  10846. var ProviderError = /** @class */ (function (_super) {
  10847. __extends(ProviderError, _super);
  10848. function ProviderError(message, span) {
  10849. return _super.call(this, span, message) || this;
  10850. }
  10851. return ProviderError;
  10852. }(ParseError));
  10853. var ProviderViewContext = /** @class */ (function () {
  10854. function ProviderViewContext(reflector, component) {
  10855. var _this = this;
  10856. this.reflector = reflector;
  10857. this.component = component;
  10858. this.errors = [];
  10859. this.viewQueries = _getViewQueries(component);
  10860. this.viewProviders = new Map();
  10861. component.viewProviders.forEach(function (provider) {
  10862. if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
  10863. _this.viewProviders.set(tokenReference(provider.token), true);
  10864. }
  10865. });
  10866. }
  10867. return ProviderViewContext;
  10868. }());
  10869. var ProviderElementContext = /** @class */ (function () {
  10870. function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
  10871. var _this = this;
  10872. this.viewContext = viewContext;
  10873. this._parent = _parent;
  10874. this._isViewRoot = _isViewRoot;
  10875. this._directiveAsts = _directiveAsts;
  10876. this._sourceSpan = _sourceSpan;
  10877. this._transformedProviders = new Map();
  10878. this._seenProviders = new Map();
  10879. this._queriedTokens = new Map();
  10880. this.transformedHasViewContainer = false;
  10881. this._attrs = {};
  10882. attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
  10883. var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
  10884. this._allProviders =
  10885. _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
  10886. this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
  10887. Array.from(this._allProviders.values()).forEach(function (provider) {
  10888. _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
  10889. });
  10890. if (isTemplate) {
  10891. var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
  10892. this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
  10893. }
  10894. refs.forEach(function (refAst) {
  10895. var defaultQueryValue = refAst.value ||
  10896. createTokenForExternalReference(_this.viewContext.reflector, Identifiers.ElementRef);
  10897. _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
  10898. });
  10899. if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {
  10900. this.transformedHasViewContainer = true;
  10901. }
  10902. // create the providers that we know are eager first
  10903. Array.from(this._allProviders.values()).forEach(function (provider) {
  10904. var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
  10905. if (eager) {
  10906. _this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
  10907. }
  10908. });
  10909. }
  10910. ProviderElementContext.prototype.afterElement = function () {
  10911. var _this = this;
  10912. // collect lazy providers
  10913. Array.from(this._allProviders.values()).forEach(function (provider) {
  10914. _this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
  10915. });
  10916. };
  10917. Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
  10918. get: function () {
  10919. // Note: Maps keep their insertion order.
  10920. var lazyProviders = [];
  10921. var eagerProviders = [];
  10922. this._transformedProviders.forEach(function (provider) {
  10923. if (provider.eager) {
  10924. eagerProviders.push(provider);
  10925. }
  10926. else {
  10927. lazyProviders.push(provider);
  10928. }
  10929. });
  10930. return lazyProviders.concat(eagerProviders);
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
  10936. get: function () {
  10937. var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
  10938. var sortedDirectives = this._directiveAsts.slice();
  10939. sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
  10940. sortedProviderTypes.indexOf(dir2.directive.type); });
  10941. return sortedDirectives;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
  10947. get: function () {
  10948. var allMatches = [];
  10949. this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, __spread(matches)); });
  10950. return allMatches;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
  10956. this._getQueriesFor(token).forEach(function (query) {
  10957. var queryValue = query.meta.read || defaultValue;
  10958. var tokenRef = tokenReference(queryValue);
  10959. var queryMatches = queryReadTokens.get(tokenRef);
  10960. if (!queryMatches) {
  10961. queryMatches = [];
  10962. queryReadTokens.set(tokenRef, queryMatches);
  10963. }
  10964. queryMatches.push({ queryId: query.queryId, value: queryValue });
  10965. });
  10966. };
  10967. ProviderElementContext.prototype._getQueriesFor = function (token) {
  10968. var result = [];
  10969. var currentEl = this;
  10970. var distance = 0;
  10971. var queries;
  10972. while (currentEl !== null) {
  10973. queries = currentEl._contentQueries.get(tokenReference(token));
  10974. if (queries) {
  10975. result.push.apply(result, __spread(queries.filter(function (query) { return query.meta.descendants || distance <= 1; })));
  10976. }
  10977. if (currentEl._directiveAsts.length > 0) {
  10978. distance++;
  10979. }
  10980. currentEl = currentEl._parent;
  10981. }
  10982. queries = this.viewContext.viewQueries.get(tokenReference(token));
  10983. if (queries) {
  10984. result.push.apply(result, __spread(queries));
  10985. }
  10986. return result;
  10987. };
  10988. ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
  10989. var _this = this;
  10990. var resolvedProvider = this._allProviders.get(tokenReference(token));
  10991. if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
  10992. requestingProviderType === ProviderAstType.PublicService) &&
  10993. resolvedProvider.providerType === ProviderAstType.PrivateService) ||
  10994. ((requestingProviderType === ProviderAstType.PrivateService ||
  10995. requestingProviderType === ProviderAstType.PublicService) &&
  10996. resolvedProvider.providerType === ProviderAstType.Builtin)) {
  10997. return null;
  10998. }
  10999. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  11000. if (transformedProviderAst) {
  11001. return transformedProviderAst;
  11002. }
  11003. if (this._seenProviders.get(tokenReference(token)) != null) {
  11004. this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
  11005. return null;
  11006. }
  11007. this._seenProviders.set(tokenReference(token), true);
  11008. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  11009. var transformedUseValue = provider.useValue;
  11010. var transformedUseExisting = provider.useExisting;
  11011. var transformedDeps = undefined;
  11012. if (provider.useExisting != null) {
  11013. var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
  11014. if (existingDiDep.token != null) {
  11015. transformedUseExisting = existingDiDep.token;
  11016. }
  11017. else {
  11018. transformedUseExisting = null;
  11019. transformedUseValue = existingDiDep.value;
  11020. }
  11021. }
  11022. else if (provider.useFactory) {
  11023. var deps = provider.deps || provider.useFactory.diDeps;
  11024. transformedDeps =
  11025. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  11026. }
  11027. else if (provider.useClass) {
  11028. var deps = provider.deps || provider.useClass.diDeps;
  11029. transformedDeps =
  11030. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  11031. }
  11032. return _transformProvider(provider, {
  11033. useExisting: transformedUseExisting,
  11034. useValue: transformedUseValue,
  11035. deps: transformedDeps
  11036. });
  11037. });
  11038. transformedProviderAst =
  11039. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  11040. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  11041. return transformedProviderAst;
  11042. };
  11043. ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
  11044. if (eager === void 0) { eager = false; }
  11045. if (dep.isAttribute) {
  11046. var attrValue = this._attrs[dep.token.value];
  11047. return { isValue: true, value: attrValue == null ? null : attrValue };
  11048. }
  11049. if (dep.token != null) {
  11050. // access builtints
  11051. if ((requestingProviderType === ProviderAstType.Directive ||
  11052. requestingProviderType === ProviderAstType.Component)) {
  11053. if (tokenReference(dep.token) ===
  11054. this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||
  11055. tokenReference(dep.token) ===
  11056. this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||
  11057. tokenReference(dep.token) ===
  11058. this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) ||
  11059. tokenReference(dep.token) ===
  11060. this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  11061. return dep;
  11062. }
  11063. if (tokenReference(dep.token) ===
  11064. this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  11065. this.transformedHasViewContainer = true;
  11066. }
  11067. }
  11068. // access the injector
  11069. if (tokenReference(dep.token) ===
  11070. this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {
  11071. return dep;
  11072. }
  11073. // access providers
  11074. if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
  11075. return dep;
  11076. }
  11077. }
  11078. return null;
  11079. };
  11080. ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
  11081. if (eager === void 0) { eager = false; }
  11082. var currElement = this;
  11083. var currEager = eager;
  11084. var result = null;
  11085. if (!dep.isSkipSelf) {
  11086. result = this._getLocalDependency(requestingProviderType, dep, eager);
  11087. }
  11088. if (dep.isSelf) {
  11089. if (!result && dep.isOptional) {
  11090. result = { isValue: true, value: null };
  11091. }
  11092. }
  11093. else {
  11094. // check parent elements
  11095. while (!result && currElement._parent) {
  11096. var prevElement = currElement;
  11097. currElement = currElement._parent;
  11098. if (prevElement._isViewRoot) {
  11099. currEager = false;
  11100. }
  11101. result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);
  11102. }
  11103. // check @Host restriction
  11104. if (!result) {
  11105. if (!dep.isHost || this.viewContext.component.isHost ||
  11106. this.viewContext.component.type.reference === tokenReference(dep.token) ||
  11107. this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
  11108. result = dep;
  11109. }
  11110. else {
  11111. result = dep.isOptional ? { isValue: true, value: null } : null;
  11112. }
  11113. }
  11114. }
  11115. if (!result) {
  11116. this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan));
  11117. }
  11118. return result;
  11119. };
  11120. return ProviderElementContext;
  11121. }());
  11122. var NgModuleProviderAnalyzer = /** @class */ (function () {
  11123. function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) {
  11124. var _this = this;
  11125. this.reflector = reflector;
  11126. this._transformedProviders = new Map();
  11127. this._seenProviders = new Map();
  11128. this._errors = [];
  11129. this._allProviders = new Map();
  11130. ngModule.transitiveModule.modules.forEach(function (ngModuleType) {
  11131. var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
  11132. _resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true);
  11133. });
  11134. _resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
  11135. /* isModule */ false);
  11136. }
  11137. NgModuleProviderAnalyzer.prototype.parse = function () {
  11138. var _this = this;
  11139. Array.from(this._allProviders.values()).forEach(function (provider) {
  11140. _this._getOrCreateLocalProvider(provider.token, provider.eager);
  11141. });
  11142. if (this._errors.length > 0) {
  11143. var errorString = this._errors.join('\n');
  11144. throw new Error("Provider parse errors:\n" + errorString);
  11145. }
  11146. // Note: Maps keep their insertion order.
  11147. var lazyProviders = [];
  11148. var eagerProviders = [];
  11149. this._transformedProviders.forEach(function (provider) {
  11150. if (provider.eager) {
  11151. eagerProviders.push(provider);
  11152. }
  11153. else {
  11154. lazyProviders.push(provider);
  11155. }
  11156. });
  11157. return lazyProviders.concat(eagerProviders);
  11158. };
  11159. NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) {
  11160. var _this = this;
  11161. var resolvedProvider = this._allProviders.get(tokenReference(token));
  11162. if (!resolvedProvider) {
  11163. return null;
  11164. }
  11165. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  11166. if (transformedProviderAst) {
  11167. return transformedProviderAst;
  11168. }
  11169. if (this._seenProviders.get(tokenReference(token)) != null) {
  11170. this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan));
  11171. return null;
  11172. }
  11173. this._seenProviders.set(tokenReference(token), true);
  11174. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  11175. var transformedUseValue = provider.useValue;
  11176. var transformedUseExisting = provider.useExisting;
  11177. var transformedDeps = undefined;
  11178. if (provider.useExisting != null) {
  11179. var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
  11180. if (existingDiDep.token != null) {
  11181. transformedUseExisting = existingDiDep.token;
  11182. }
  11183. else {
  11184. transformedUseExisting = null;
  11185. transformedUseValue = existingDiDep.value;
  11186. }
  11187. }
  11188. else if (provider.useFactory) {
  11189. var deps = provider.deps || provider.useFactory.diDeps;
  11190. transformedDeps =
  11191. deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
  11192. }
  11193. else if (provider.useClass) {
  11194. var deps = provider.deps || provider.useClass.diDeps;
  11195. transformedDeps =
  11196. deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
  11197. }
  11198. return _transformProvider(provider, {
  11199. useExisting: transformedUseExisting,
  11200. useValue: transformedUseValue,
  11201. deps: transformedDeps
  11202. });
  11203. });
  11204. transformedProviderAst =
  11205. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  11206. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  11207. return transformedProviderAst;
  11208. };
  11209. NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) {
  11210. if (eager === void 0) { eager = false; }
  11211. if (!dep.isSkipSelf && dep.token != null) {
  11212. // access the injector
  11213. if (tokenReference(dep.token) ===
  11214. this.reflector.resolveExternalReference(Identifiers.Injector) ||
  11215. tokenReference(dep.token) ===
  11216. this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) ;
  11217. else if (this._getOrCreateLocalProvider(dep.token, eager) != null) ;
  11218. }
  11219. return dep;
  11220. };
  11221. return NgModuleProviderAnalyzer;
  11222. }());
  11223. function _transformProvider(provider, _a) {
  11224. var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
  11225. return {
  11226. token: provider.token,
  11227. useClass: provider.useClass,
  11228. useExisting: useExisting,
  11229. useFactory: provider.useFactory,
  11230. useValue: useValue,
  11231. deps: deps,
  11232. multi: provider.multi
  11233. };
  11234. }
  11235. function _transformProviderAst(provider, _a) {
  11236. var eager = _a.eager, providers = _a.providers;
  11237. return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
  11238. }
  11239. function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
  11240. var providersByToken = new Map();
  11241. directives.forEach(function (directive) {
  11242. var dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
  11243. _resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  11244. });
  11245. // Note: directives need to be able to overwrite providers of a component!
  11246. var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
  11247. directivesWithComponentFirst.forEach(function (directive) {
  11248. _resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  11249. _resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  11250. });
  11251. return providersByToken;
  11252. }
  11253. function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
  11254. providers.forEach(function (provider) {
  11255. var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
  11256. if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
  11257. targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
  11258. }
  11259. if (!resolvedProvider) {
  11260. var lifecycleHooks = provider.token.identifier &&
  11261. provider.token.identifier.lifecycleHooks ?
  11262. provider.token.identifier.lifecycleHooks :
  11263. [];
  11264. var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
  11265. resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
  11266. targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
  11267. }
  11268. else {
  11269. if (!provider.multi) {
  11270. resolvedProvider.providers.length = 0;
  11271. }
  11272. resolvedProvider.providers.push(provider);
  11273. }
  11274. });
  11275. }
  11276. function _getViewQueries(component) {
  11277. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  11278. var viewQueryId = 1;
  11279. var viewQueries = new Map();
  11280. if (component.viewQueries) {
  11281. component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
  11282. }
  11283. return viewQueries;
  11284. }
  11285. function _getContentQueries(contentQueryStartId, directives) {
  11286. var contentQueryId = contentQueryStartId;
  11287. var contentQueries = new Map();
  11288. directives.forEach(function (directive, directiveIndex) {
  11289. if (directive.queries) {
  11290. directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
  11291. }
  11292. });
  11293. return contentQueries;
  11294. }
  11295. function _addQueryToTokenMap(map, query) {
  11296. query.meta.selectors.forEach(function (token) {
  11297. var entry = map.get(tokenReference(token));
  11298. if (!entry) {
  11299. entry = [];
  11300. map.set(tokenReference(token), entry);
  11301. }
  11302. entry.push(query);
  11303. });
  11304. }
  11305. /**
  11306. * @license
  11307. * Copyright Google Inc. All Rights Reserved.
  11308. *
  11309. * Use of this source code is governed by an MIT-style license that can be
  11310. * found in the LICENSE file at https://angular.io/license
  11311. */
  11312. var StyleWithImports = /** @class */ (function () {
  11313. function StyleWithImports(style, styleUrls) {
  11314. this.style = style;
  11315. this.styleUrls = styleUrls;
  11316. }
  11317. return StyleWithImports;
  11318. }());
  11319. function isStyleUrlResolvable(url) {
  11320. if (url == null || url.length === 0 || url[0] == '/')
  11321. return false;
  11322. var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
  11323. return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
  11324. }
  11325. /**
  11326. * Rewrites stylesheets by resolving and removing the @import urls that
  11327. * are either relative or don't have a `package:` scheme
  11328. */
  11329. function extractStyleUrls(resolver, baseUrl, cssText) {
  11330. var foundUrls = [];
  11331. var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
  11332. .replace(CSS_IMPORT_REGEXP, function () {
  11333. var m = [];
  11334. for (var _i = 0; _i < arguments.length; _i++) {
  11335. m[_i] = arguments[_i];
  11336. }
  11337. var url = m[1] || m[2];
  11338. if (!isStyleUrlResolvable(url)) {
  11339. // Do not attempt to resolve non-package absolute URLs with URI
  11340. // scheme
  11341. return m[0];
  11342. }
  11343. foundUrls.push(resolver.resolve(baseUrl, url));
  11344. return '';
  11345. });
  11346. return new StyleWithImports(modifiedCssText, foundUrls);
  11347. }
  11348. var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
  11349. var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
  11350. var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
  11351. /**
  11352. * @license
  11353. * Copyright Google Inc. All Rights Reserved.
  11354. *
  11355. * Use of this source code is governed by an MIT-style license that can be
  11356. * found in the LICENSE file at https://angular.io/license
  11357. */
  11358. var PROPERTY_PARTS_SEPARATOR = '.';
  11359. var ATTRIBUTE_PREFIX = 'attr';
  11360. var CLASS_PREFIX = 'class';
  11361. var STYLE_PREFIX = 'style';
  11362. var ANIMATE_PROP_PREFIX = 'animate-';
  11363. /**
  11364. * Parses bindings in templates and in the directive host area.
  11365. */
  11366. var BindingParser = /** @class */ (function () {
  11367. function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
  11368. this._exprParser = _exprParser;
  11369. this._interpolationConfig = _interpolationConfig;
  11370. this._schemaRegistry = _schemaRegistry;
  11371. this.errors = errors;
  11372. this.pipesByName = null;
  11373. this._usedPipes = new Map();
  11374. // When the `pipes` parameter is `null`, do not check for used pipes
  11375. // This is used in IVY when we might not know the available pipes at compile time
  11376. if (pipes) {
  11377. var pipesByName_1 = new Map();
  11378. pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); });
  11379. this.pipesByName = pipesByName_1;
  11380. }
  11381. }
  11382. Object.defineProperty(BindingParser.prototype, "interpolationConfig", {
  11383. get: function () { return this._interpolationConfig; },
  11384. enumerable: true,
  11385. configurable: true
  11386. });
  11387. BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); };
  11388. BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) {
  11389. var _this = this;
  11390. if (dirMeta.hostProperties) {
  11391. var boundProps_1 = [];
  11392. Object.keys(dirMeta.hostProperties).forEach(function (propName) {
  11393. var expression = dirMeta.hostProperties[propName];
  11394. if (typeof expression === 'string') {
  11395. _this.parsePropertyBinding(propName, expression, true, sourceSpan, [], boundProps_1);
  11396. }
  11397. else {
  11398. _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  11399. }
  11400. });
  11401. return boundProps_1;
  11402. }
  11403. return null;
  11404. };
  11405. BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) {
  11406. var _this = this;
  11407. var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
  11408. return boundProps &&
  11409. boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); });
  11410. };
  11411. BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) {
  11412. var _this = this;
  11413. if (dirMeta.hostListeners) {
  11414. var targetEvents_1 = [];
  11415. Object.keys(dirMeta.hostListeners).forEach(function (propName) {
  11416. var expression = dirMeta.hostListeners[propName];
  11417. if (typeof expression === 'string') {
  11418. // TODO: pass a more accurate handlerSpan for this event.
  11419. _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1);
  11420. }
  11421. else {
  11422. _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  11423. }
  11424. });
  11425. return targetEvents_1;
  11426. }
  11427. return null;
  11428. };
  11429. BindingParser.prototype.parseInterpolation = function (value, sourceSpan) {
  11430. var sourceInfo = sourceSpan.start.toString();
  11431. try {
  11432. var ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig);
  11433. if (ast)
  11434. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11435. this._checkPipes(ast, sourceSpan);
  11436. return ast;
  11437. }
  11438. catch (e) {
  11439. this._reportError("" + e, sourceSpan);
  11440. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11441. }
  11442. };
  11443. // Parse an inline template binding. ie `<tag *tplKey="<tplValue>">`
  11444. BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, targetMatchableAttrs, targetProps, targetVars) {
  11445. var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan);
  11446. for (var i = 0; i < bindings.length; i++) {
  11447. var binding = bindings[i];
  11448. if (binding.keyIsVar) {
  11449. targetVars.push(new ParsedVariable(binding.key, binding.name, sourceSpan));
  11450. }
  11451. else if (binding.expression) {
  11452. this._parsePropertyAst(binding.key, binding.expression, sourceSpan, targetMatchableAttrs, targetProps);
  11453. }
  11454. else {
  11455. targetMatchableAttrs.push([binding.key, '']);
  11456. this.parseLiteralAttr(binding.key, null, sourceSpan, targetMatchableAttrs, targetProps);
  11457. }
  11458. }
  11459. };
  11460. BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan) {
  11461. var _this = this;
  11462. var sourceInfo = sourceSpan.start.toString();
  11463. try {
  11464. var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo);
  11465. this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
  11466. bindingsResult.templateBindings.forEach(function (binding) {
  11467. if (binding.expression) {
  11468. _this._checkPipes(binding.expression, sourceSpan);
  11469. }
  11470. });
  11471. bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); });
  11472. return bindingsResult.templateBindings;
  11473. }
  11474. catch (e) {
  11475. this._reportError("" + e, sourceSpan);
  11476. return [];
  11477. }
  11478. };
  11479. BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  11480. if (isAnimationLabel(name)) {
  11481. name = name.substring(1);
  11482. if (value) {
  11483. this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." +
  11484. " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, ParseErrorLevel.ERROR);
  11485. }
  11486. this._parseAnimation(name, value, sourceSpan, targetMatchableAttrs, targetProps);
  11487. }
  11488. else {
  11489. targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), ParsedPropertyType.LITERAL_ATTR, sourceSpan));
  11490. }
  11491. };
  11492. BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, targetMatchableAttrs, targetProps) {
  11493. var isAnimationProp = false;
  11494. if (name.startsWith(ANIMATE_PROP_PREFIX)) {
  11495. isAnimationProp = true;
  11496. name = name.substring(ANIMATE_PROP_PREFIX.length);
  11497. }
  11498. else if (isAnimationLabel(name)) {
  11499. isAnimationProp = true;
  11500. name = name.substring(1);
  11501. }
  11502. if (isAnimationProp) {
  11503. this._parseAnimation(name, expression, sourceSpan, targetMatchableAttrs, targetProps);
  11504. }
  11505. else {
  11506. this._parsePropertyAst(name, this._parseBinding(expression, isHost, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps);
  11507. }
  11508. };
  11509. BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  11510. var expr = this.parseInterpolation(value, sourceSpan);
  11511. if (expr) {
  11512. this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
  11513. return true;
  11514. }
  11515. return false;
  11516. };
  11517. BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, targetMatchableAttrs, targetProps) {
  11518. targetMatchableAttrs.push([name, ast.source]);
  11519. targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.DEFAULT, sourceSpan));
  11520. };
  11521. BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, targetMatchableAttrs, targetProps) {
  11522. // This will occur when a @trigger is not paired with an expression.
  11523. // For animations it is valid to not have an expression since */void
  11524. // states will be applied by angular when the element is attached/detached
  11525. var ast = this._parseBinding(expression || 'undefined', false, sourceSpan);
  11526. targetMatchableAttrs.push([name, ast.source]);
  11527. targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan));
  11528. };
  11529. BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan) {
  11530. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
  11531. try {
  11532. var ast = isHostBinding ?
  11533. this._exprParser.parseSimpleBinding(value, sourceInfo, this._interpolationConfig) :
  11534. this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig);
  11535. if (ast)
  11536. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11537. this._checkPipes(ast, sourceSpan);
  11538. return ast;
  11539. }
  11540. catch (e) {
  11541. this._reportError("" + e, sourceSpan);
  11542. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11543. }
  11544. };
  11545. BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) {
  11546. if (skipValidation === void 0) { skipValidation = false; }
  11547. if (mapPropertyName === void 0) { mapPropertyName = true; }
  11548. if (boundProp.isAnimation) {
  11549. return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan);
  11550. }
  11551. var unit = null;
  11552. var bindingType = undefined;
  11553. var boundPropertyName = null;
  11554. var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  11555. var securityContexts = undefined;
  11556. // Check for special cases (prefix style, attr, class)
  11557. if (parts.length > 1) {
  11558. if (parts[0] == ATTRIBUTE_PREFIX) {
  11559. boundPropertyName = parts[1];
  11560. if (!skipValidation) {
  11561. this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
  11562. }
  11563. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
  11564. var nsSeparatorIdx = boundPropertyName.indexOf(':');
  11565. if (nsSeparatorIdx > -1) {
  11566. var ns = boundPropertyName.substring(0, nsSeparatorIdx);
  11567. var name_1 = boundPropertyName.substring(nsSeparatorIdx + 1);
  11568. boundPropertyName = mergeNsAndName(ns, name_1);
  11569. }
  11570. bindingType = 1 /* Attribute */;
  11571. }
  11572. else if (parts[0] == CLASS_PREFIX) {
  11573. boundPropertyName = parts[1];
  11574. bindingType = 2 /* Class */;
  11575. securityContexts = [SecurityContext.NONE];
  11576. }
  11577. else if (parts[0] == STYLE_PREFIX) {
  11578. unit = parts.length > 2 ? parts[2] : null;
  11579. boundPropertyName = parts[1];
  11580. bindingType = 3 /* Style */;
  11581. securityContexts = [SecurityContext.STYLE];
  11582. }
  11583. }
  11584. // If not a special case, use the full property name
  11585. if (boundPropertyName === null) {
  11586. var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
  11587. boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
  11588. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
  11589. bindingType = 0 /* Property */;
  11590. if (!skipValidation) {
  11591. this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
  11592. }
  11593. }
  11594. return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan);
  11595. };
  11596. BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  11597. if (isAnimationLabel(name)) {
  11598. name = name.substr(1);
  11599. this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents);
  11600. }
  11601. else {
  11602. this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents);
  11603. }
  11604. };
  11605. BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) {
  11606. var prop = this._schemaRegistry.getMappedPropName(propName);
  11607. return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
  11608. };
  11609. BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents) {
  11610. var matches = splitAtPeriod(name, [name, '']);
  11611. var eventName = matches[0];
  11612. var phase = matches[1].toLowerCase();
  11613. if (phase) {
  11614. switch (phase) {
  11615. case 'start':
  11616. case 'done':
  11617. var ast = this._parseAction(expression, handlerSpan);
  11618. targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan));
  11619. break;
  11620. default:
  11621. this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan);
  11622. break;
  11623. }
  11624. }
  11625. else {
  11626. this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan);
  11627. }
  11628. };
  11629. BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  11630. // long format: 'target: eventName'
  11631. var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1];
  11632. var ast = this._parseAction(expression, handlerSpan);
  11633. targetMatchableAttrs.push([name, ast.source]);
  11634. targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan));
  11635. // Don't detect directives for event names for now,
  11636. // so don't add the event name to the matchableAttrs
  11637. };
  11638. BindingParser.prototype._parseAction = function (value, sourceSpan) {
  11639. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
  11640. try {
  11641. var ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig);
  11642. if (ast) {
  11643. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11644. }
  11645. if (!ast || ast.ast instanceof EmptyExpr) {
  11646. this._reportError("Empty expressions are not allowed", sourceSpan);
  11647. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11648. }
  11649. this._checkPipes(ast, sourceSpan);
  11650. return ast;
  11651. }
  11652. catch (e) {
  11653. this._reportError("" + e, sourceSpan);
  11654. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11655. }
  11656. };
  11657. BindingParser.prototype._reportError = function (message, sourceSpan, level) {
  11658. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  11659. this.errors.push(new ParseError(sourceSpan, message, level));
  11660. };
  11661. BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) {
  11662. var e_1, _a;
  11663. try {
  11664. for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) {
  11665. var error = errors_1_1.value;
  11666. this._reportError(error.message, sourceSpan);
  11667. }
  11668. }
  11669. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  11670. finally {
  11671. try {
  11672. if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1);
  11673. }
  11674. finally { if (e_1) throw e_1.error; }
  11675. }
  11676. };
  11677. // Make sure all the used pipes are known in `this.pipesByName`
  11678. BindingParser.prototype._checkPipes = function (ast, sourceSpan) {
  11679. var _this = this;
  11680. if (ast && this.pipesByName) {
  11681. var collector = new PipeCollector();
  11682. ast.visit(collector);
  11683. collector.pipes.forEach(function (ast, pipeName) {
  11684. var pipeMeta = _this.pipesByName.get(pipeName);
  11685. if (!pipeMeta) {
  11686. _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
  11687. }
  11688. else {
  11689. _this._usedPipes.set(pipeName, pipeMeta);
  11690. }
  11691. });
  11692. }
  11693. };
  11694. /**
  11695. * @param propName the name of the property / attribute
  11696. * @param sourceSpan
  11697. * @param isAttr true when binding to an attribute
  11698. */
  11699. BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) {
  11700. var report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
  11701. this._schemaRegistry.validateProperty(propName);
  11702. if (report.error) {
  11703. this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR);
  11704. }
  11705. };
  11706. return BindingParser;
  11707. }());
  11708. var PipeCollector = /** @class */ (function (_super) {
  11709. __extends(PipeCollector, _super);
  11710. function PipeCollector() {
  11711. var _this = _super !== null && _super.apply(this, arguments) || this;
  11712. _this.pipes = new Map();
  11713. return _this;
  11714. }
  11715. PipeCollector.prototype.visitPipe = function (ast, context) {
  11716. this.pipes.set(ast.name, ast);
  11717. ast.exp.visit(this);
  11718. this.visitAll(ast.args, context);
  11719. return null;
  11720. };
  11721. return PipeCollector;
  11722. }(RecursiveAstVisitor$1));
  11723. function isAnimationLabel(name) {
  11724. return name[0] == '@';
  11725. }
  11726. function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
  11727. var ctxs = [];
  11728. CssSelector.parse(selector).forEach(function (selector) {
  11729. var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
  11730. var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); })
  11731. .map(function (selector) { return selector.element; }));
  11732. var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); });
  11733. ctxs.push.apply(ctxs, __spread(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); })));
  11734. });
  11735. return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
  11736. }
  11737. /**
  11738. * @license
  11739. * Copyright Google Inc. All Rights Reserved.
  11740. *
  11741. * Use of this source code is governed by an MIT-style license that can be
  11742. * found in the LICENSE file at https://angular.io/license
  11743. */
  11744. var NG_CONTENT_SELECT_ATTR = 'select';
  11745. var LINK_ELEMENT = 'link';
  11746. var LINK_STYLE_REL_ATTR = 'rel';
  11747. var LINK_STYLE_HREF_ATTR = 'href';
  11748. var LINK_STYLE_REL_VALUE = 'stylesheet';
  11749. var STYLE_ELEMENT = 'style';
  11750. var SCRIPT_ELEMENT = 'script';
  11751. var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
  11752. var NG_PROJECT_AS = 'ngProjectAs';
  11753. function preparseElement(ast) {
  11754. var selectAttr = null;
  11755. var hrefAttr = null;
  11756. var relAttr = null;
  11757. var nonBindable = false;
  11758. var projectAs = '';
  11759. ast.attrs.forEach(function (attr) {
  11760. var lcAttrName = attr.name.toLowerCase();
  11761. if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
  11762. selectAttr = attr.value;
  11763. }
  11764. else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
  11765. hrefAttr = attr.value;
  11766. }
  11767. else if (lcAttrName == LINK_STYLE_REL_ATTR) {
  11768. relAttr = attr.value;
  11769. }
  11770. else if (attr.name == NG_NON_BINDABLE_ATTR) {
  11771. nonBindable = true;
  11772. }
  11773. else if (attr.name == NG_PROJECT_AS) {
  11774. if (attr.value.length > 0) {
  11775. projectAs = attr.value;
  11776. }
  11777. }
  11778. });
  11779. selectAttr = normalizeNgContentSelect(selectAttr);
  11780. var nodeName = ast.name.toLowerCase();
  11781. var type = PreparsedElementType.OTHER;
  11782. if (isNgContent(nodeName)) {
  11783. type = PreparsedElementType.NG_CONTENT;
  11784. }
  11785. else if (nodeName == STYLE_ELEMENT) {
  11786. type = PreparsedElementType.STYLE;
  11787. }
  11788. else if (nodeName == SCRIPT_ELEMENT) {
  11789. type = PreparsedElementType.SCRIPT;
  11790. }
  11791. else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
  11792. type = PreparsedElementType.STYLESHEET;
  11793. }
  11794. return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
  11795. }
  11796. var PreparsedElementType;
  11797. (function (PreparsedElementType) {
  11798. PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
  11799. PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
  11800. PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
  11801. PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
  11802. PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
  11803. })(PreparsedElementType || (PreparsedElementType = {}));
  11804. var PreparsedElement = /** @class */ (function () {
  11805. function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) {
  11806. this.type = type;
  11807. this.selectAttr = selectAttr;
  11808. this.hrefAttr = hrefAttr;
  11809. this.nonBindable = nonBindable;
  11810. this.projectAs = projectAs;
  11811. }
  11812. return PreparsedElement;
  11813. }());
  11814. function normalizeNgContentSelect(selectAttr) {
  11815. if (selectAttr === null || selectAttr.length === 0) {
  11816. return '*';
  11817. }
  11818. return selectAttr;
  11819. }
  11820. /**
  11821. * @license
  11822. * Copyright Google Inc. All Rights Reserved.
  11823. *
  11824. * Use of this source code is governed by an MIT-style license that can be
  11825. * found in the LICENSE file at https://angular.io/license
  11826. */
  11827. var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  11828. // Group 1 = "bind-"
  11829. var KW_BIND_IDX = 1;
  11830. // Group 2 = "let-"
  11831. var KW_LET_IDX = 2;
  11832. // Group 3 = "ref-/#"
  11833. var KW_REF_IDX = 3;
  11834. // Group 4 = "on-"
  11835. var KW_ON_IDX = 4;
  11836. // Group 5 = "bindon-"
  11837. var KW_BINDON_IDX = 5;
  11838. // Group 6 = "@"
  11839. var KW_AT_IDX = 6;
  11840. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  11841. var IDENT_KW_IDX = 7;
  11842. // Group 8 = identifier inside [()]
  11843. var IDENT_BANANA_BOX_IDX = 8;
  11844. // Group 9 = identifier inside []
  11845. var IDENT_PROPERTY_IDX = 9;
  11846. // Group 10 = identifier inside ()
  11847. var IDENT_EVENT_IDX = 10;
  11848. var TEMPLATE_ATTR_PREFIX = '*';
  11849. var CLASS_ATTR = 'class';
  11850. var _TEXT_CSS_SELECTOR;
  11851. function TEXT_CSS_SELECTOR() {
  11852. if (!_TEXT_CSS_SELECTOR) {
  11853. _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
  11854. }
  11855. return _TEXT_CSS_SELECTOR;
  11856. }
  11857. var TemplateParseError = /** @class */ (function (_super) {
  11858. __extends(TemplateParseError, _super);
  11859. function TemplateParseError(message, span, level) {
  11860. return _super.call(this, span, message, level) || this;
  11861. }
  11862. return TemplateParseError;
  11863. }(ParseError));
  11864. var TemplateParseResult = /** @class */ (function () {
  11865. function TemplateParseResult(templateAst, usedPipes, errors) {
  11866. this.templateAst = templateAst;
  11867. this.usedPipes = usedPipes;
  11868. this.errors = errors;
  11869. }
  11870. return TemplateParseResult;
  11871. }());
  11872. var TemplateParser = /** @class */ (function () {
  11873. function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
  11874. this._config = _config;
  11875. this._reflector = _reflector;
  11876. this._exprParser = _exprParser;
  11877. this._schemaRegistry = _schemaRegistry;
  11878. this._htmlParser = _htmlParser;
  11879. this._console = _console;
  11880. this.transforms = transforms;
  11881. }
  11882. Object.defineProperty(TemplateParser.prototype, "expressionParser", {
  11883. get: function () { return this._exprParser; },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11888. var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
  11889. var warnings = result.errors.filter(function (error) { return error.level === ParseErrorLevel.WARNING; });
  11890. var errors = result.errors.filter(function (error) { return error.level === ParseErrorLevel.ERROR; });
  11891. if (warnings.length > 0) {
  11892. this._console.warn("Template parse warnings:\n" + warnings.join('\n'));
  11893. }
  11894. if (errors.length > 0) {
  11895. var errorString = errors.join('\n');
  11896. throw syntaxError("Template parse errors:\n" + errorString, errors);
  11897. }
  11898. return { template: result.templateAst, pipes: result.usedPipes };
  11899. };
  11900. TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11901. var htmlParseResult = typeof template === 'string' ?
  11902. this._htmlParser.parse(template, templateUrl, {
  11903. tokenizeExpansionForms: true,
  11904. interpolationConfig: this.getInterpolationConfig(component)
  11905. }) :
  11906. template;
  11907. if (!preserveWhitespaces) {
  11908. htmlParseResult = removeWhitespaces(htmlParseResult);
  11909. }
  11910. return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
  11911. };
  11912. TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) {
  11913. var result;
  11914. var errors = htmlAstWithErrors.errors;
  11915. var usedPipes = [];
  11916. if (htmlAstWithErrors.rootNodes.length > 0) {
  11917. var uniqDirectives = removeSummaryDuplicates(directives);
  11918. var uniqPipes = removeSummaryDuplicates(pipes);
  11919. var providerViewContext = new ProviderViewContext(this._reflector, component);
  11920. var interpolationConfig = undefined;
  11921. if (component.template && component.template.interpolation) {
  11922. interpolationConfig = {
  11923. start: component.template.interpolation[0],
  11924. end: component.template.interpolation[1]
  11925. };
  11926. }
  11927. var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
  11928. var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
  11929. result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
  11930. errors.push.apply(errors, __spread(providerViewContext.errors));
  11931. usedPipes.push.apply(usedPipes, __spread(bindingParser.getUsedPipes()));
  11932. }
  11933. else {
  11934. result = [];
  11935. }
  11936. this._assertNoReferenceDuplicationOnTemplate(result, errors);
  11937. if (errors.length > 0) {
  11938. return new TemplateParseResult(result, usedPipes, errors);
  11939. }
  11940. if (this.transforms) {
  11941. this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); });
  11942. }
  11943. return new TemplateParseResult(result, usedPipes, errors);
  11944. };
  11945. TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) {
  11946. if (forced === void 0) { forced = false; }
  11947. var errors = htmlAstWithErrors.errors;
  11948. if (errors.length == 0 || forced) {
  11949. // Transform ICU messages to angular directives
  11950. var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
  11951. errors.push.apply(errors, __spread(expandedHtmlAst.errors));
  11952. htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
  11953. }
  11954. return htmlAstWithErrors;
  11955. };
  11956. TemplateParser.prototype.getInterpolationConfig = function (component) {
  11957. if (component.template) {
  11958. return InterpolationConfig.fromArray(component.template.interpolation);
  11959. }
  11960. return undefined;
  11961. };
  11962. /** @internal */
  11963. TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) {
  11964. var existingReferences = [];
  11965. result.filter(function (element) { return !!element.references; })
  11966. .forEach(function (element) { return element.references.forEach(function (reference) {
  11967. var name = reference.name;
  11968. if (existingReferences.indexOf(name) < 0) {
  11969. existingReferences.push(name);
  11970. }
  11971. else {
  11972. var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, ParseErrorLevel.ERROR);
  11973. errors.push(error);
  11974. }
  11975. }); });
  11976. };
  11977. return TemplateParser;
  11978. }());
  11979. var TemplateParseVisitor = /** @class */ (function () {
  11980. function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
  11981. var _this = this;
  11982. this.reflector = reflector;
  11983. this.config = config;
  11984. this.providerViewContext = providerViewContext;
  11985. this._bindingParser = _bindingParser;
  11986. this._schemaRegistry = _schemaRegistry;
  11987. this._schemas = _schemas;
  11988. this._targetErrors = _targetErrors;
  11989. this.selectorMatcher = new SelectorMatcher();
  11990. this.directivesIndex = new Map();
  11991. this.ngContentCount = 0;
  11992. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  11993. this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
  11994. directives.forEach(function (directive, index) {
  11995. var selector = CssSelector.parse(directive.selector);
  11996. _this.selectorMatcher.addSelectables(selector, directive);
  11997. _this.directivesIndex.set(directive, index);
  11998. });
  11999. }
  12000. TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; };
  12001. TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; };
  12002. TemplateParseVisitor.prototype.visitText = function (text, parent) {
  12003. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  12004. var valueNoNgsp = replaceNgsp(text.value);
  12005. var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
  12006. return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
  12007. new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
  12008. };
  12009. TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) {
  12010. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  12011. };
  12012. TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; };
  12013. TemplateParseVisitor.prototype.visitElement = function (element, parent) {
  12014. var _this = this;
  12015. var queryStartIndex = this.contentQueryStartId;
  12016. var elName = element.name;
  12017. var preparsedElement = preparseElement(element);
  12018. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  12019. preparsedElement.type === PreparsedElementType.STYLE) {
  12020. // Skipping <script> for security reasons
  12021. // Skipping <style> as we already processed them
  12022. // in the StyleCompiler
  12023. return null;
  12024. }
  12025. if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  12026. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  12027. // Skipping stylesheets with either relative urls or package scheme as we already processed
  12028. // them in the StyleCompiler
  12029. return null;
  12030. }
  12031. var matchableAttrs = [];
  12032. var elementOrDirectiveProps = [];
  12033. var elementOrDirectiveRefs = [];
  12034. var elementVars = [];
  12035. var events = [];
  12036. var templateElementOrDirectiveProps = [];
  12037. var templateMatchableAttrs = [];
  12038. var templateElementVars = [];
  12039. var hasInlineTemplates = false;
  12040. var attrs = [];
  12041. var isTemplateElement = isNgTemplate(element.name);
  12042. element.attrs.forEach(function (attr) {
  12043. var parsedVariables = [];
  12044. var hasBinding = _this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
  12045. elementVars.push.apply(elementVars, __spread(parsedVariables.map(function (v) { return VariableAst.fromParsedVariable(v); })));
  12046. var templateValue;
  12047. var templateKey;
  12048. var normalizedName = _this._normalizeAttributeName(attr.name);
  12049. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
  12050. templateValue = attr.value;
  12051. templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
  12052. }
  12053. var hasTemplateBinding = templateValue != null;
  12054. if (hasTemplateBinding) {
  12055. if (hasInlineTemplates) {
  12056. _this._reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attr.sourceSpan);
  12057. }
  12058. hasInlineTemplates = true;
  12059. var parsedVariables_1 = [];
  12060. _this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables_1);
  12061. templateElementVars.push.apply(templateElementVars, __spread(parsedVariables_1.map(function (v) { return VariableAst.fromParsedVariable(v); })));
  12062. }
  12063. if (!hasBinding && !hasTemplateBinding) {
  12064. // don't include the bindings as attributes as well in the AST
  12065. attrs.push(_this.visitAttribute(attr, null));
  12066. matchableAttrs.push([attr.name, attr.value]);
  12067. }
  12068. });
  12069. var elementCssSelector = createElementCssSelector(elName, matchableAttrs);
  12070. var _a = this._parseDirectives(this.selectorMatcher, elementCssSelector), directiveMetas = _a.directives, matchElement = _a.matchElement;
  12071. var references = [];
  12072. var boundDirectivePropNames = new Set();
  12073. var directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
  12074. var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
  12075. var isViewRoot = parent.isTemplateElement || hasInlineTemplates;
  12076. var providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
  12077. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
  12078. providerContext.afterElement();
  12079. // Override the actual selector when the `ngProjectAs` attribute is provided
  12080. var projectionSelector = preparsedElement.projectAs != '' ?
  12081. CssSelector.parse(preparsedElement.projectAs)[0] :
  12082. elementCssSelector;
  12083. var ngContentIndex = parent.findNgContentIndex(projectionSelector);
  12084. var parsedElement;
  12085. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  12086. // `<ng-content>` element
  12087. if (element.children && !element.children.every(_isEmptyTextNode)) {
  12088. this._reportError("<ng-content> element cannot have content.", element.sourceSpan);
  12089. }
  12090. parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  12091. }
  12092. else if (isTemplateElement) {
  12093. // `<ng-template>` element
  12094. this._assertAllEventsPublishedByDirectives(directiveAsts, events);
  12095. this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
  12096. parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  12097. }
  12098. else {
  12099. // element other than `<ng-content>` and `<ng-template>`
  12100. this._assertElementExists(matchElement, element);
  12101. this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
  12102. var ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
  12103. parsedElement = new ElementAst(elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex_1, element.sourceSpan, element.endSourceSpan || null);
  12104. }
  12105. if (hasInlineTemplates) {
  12106. // The element as a *-attribute
  12107. var templateQueryStartIndex = this.contentQueryStartId;
  12108. var templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
  12109. var directives = this._parseDirectives(this.selectorMatcher, templateSelector).directives;
  12110. var templateBoundDirectivePropNames = new Set();
  12111. var templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
  12112. var templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
  12113. this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
  12114. var templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
  12115. templateProviderContext.afterElement();
  12116. parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
  12117. }
  12118. return parsedElement;
  12119. };
  12120. TemplateParseVisitor.prototype._parseAttr = function (isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
  12121. var name = this._normalizeAttributeName(attr.name);
  12122. var value = attr.value;
  12123. var srcSpan = attr.sourceSpan;
  12124. var boundEvents = [];
  12125. var bindParts = name.match(BIND_NAME_REGEXP);
  12126. var hasBinding = false;
  12127. if (bindParts !== null) {
  12128. hasBinding = true;
  12129. if (bindParts[KW_BIND_IDX] != null) {
  12130. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12131. }
  12132. else if (bindParts[KW_LET_IDX]) {
  12133. if (isTemplateElement) {
  12134. var identifier = bindParts[IDENT_KW_IDX];
  12135. this._parseVariable(identifier, value, srcSpan, targetVars);
  12136. }
  12137. else {
  12138. this._reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  12139. }
  12140. }
  12141. else if (bindParts[KW_REF_IDX]) {
  12142. var identifier = bindParts[IDENT_KW_IDX];
  12143. this._parseReference(identifier, value, srcSpan, targetRefs);
  12144. }
  12145. else if (bindParts[KW_ON_IDX]) {
  12146. this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12147. }
  12148. else if (bindParts[KW_BINDON_IDX]) {
  12149. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12150. this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12151. }
  12152. else if (bindParts[KW_AT_IDX]) {
  12153. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  12154. }
  12155. else if (bindParts[IDENT_BANANA_BOX_IDX]) {
  12156. this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12157. this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12158. }
  12159. else if (bindParts[IDENT_PROPERTY_IDX]) {
  12160. this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12161. }
  12162. else if (bindParts[IDENT_EVENT_IDX]) {
  12163. this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12164. }
  12165. }
  12166. else {
  12167. hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, targetMatchableAttrs, targetProps);
  12168. }
  12169. if (!hasBinding) {
  12170. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  12171. }
  12172. targetEvents.push.apply(targetEvents, __spread(boundEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); })));
  12173. return hasBinding;
  12174. };
  12175. TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
  12176. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  12177. };
  12178. TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
  12179. if (identifier.indexOf('-') > -1) {
  12180. this._reportError("\"-\" is not allowed in variable names", sourceSpan);
  12181. }
  12182. targetVars.push(new VariableAst(identifier, value, sourceSpan));
  12183. };
  12184. TemplateParseVisitor.prototype._parseReference = function (identifier, value, sourceSpan, targetRefs) {
  12185. if (identifier.indexOf('-') > -1) {
  12186. this._reportError("\"-\" is not allowed in reference names", sourceSpan);
  12187. }
  12188. targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
  12189. };
  12190. TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
  12191. this._bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
  12192. };
  12193. TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
  12194. var _this = this;
  12195. // Need to sort the directives so that we get consistent results throughout,
  12196. // as selectorMatcher uses Maps inside.
  12197. // Also deduplicate directives as they might match more than one time!
  12198. var directives = new Array(this.directivesIndex.size);
  12199. // Whether any directive selector matches on the element name
  12200. var matchElement = false;
  12201. selectorMatcher.match(elementCssSelector, function (selector, directive) {
  12202. directives[_this.directivesIndex.get(directive)] = directive;
  12203. matchElement = matchElement || selector.hasElementSelector();
  12204. });
  12205. return {
  12206. directives: directives.filter(function (dir) { return !!dir; }),
  12207. matchElement: matchElement,
  12208. };
  12209. };
  12210. TemplateParseVisitor.prototype._createDirectiveAsts = function (isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
  12211. var _this = this;
  12212. var matchedReferences = new Set();
  12213. var component = null;
  12214. var directiveAsts = directives.map(function (directive) {
  12215. var sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, "Directive " + identifierName(directive.type));
  12216. if (directive.isComponent) {
  12217. component = directive;
  12218. }
  12219. var directiveProperties = [];
  12220. var boundProperties = _this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
  12221. var hostProperties = boundProperties.map(function (prop) { return BoundElementPropertyAst.fromBoundProperty(prop); });
  12222. // Note: We need to check the host properties here as well,
  12223. // as we don't know the element name in the DirectiveWrapperCompiler yet.
  12224. hostProperties = _this._checkPropertiesInSchema(elementName, hostProperties);
  12225. var parsedEvents = _this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
  12226. _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
  12227. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  12228. if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
  12229. (elOrDirRef.isReferenceToDirective(directive))) {
  12230. targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
  12231. matchedReferences.add(elOrDirRef.name);
  12232. }
  12233. });
  12234. var hostEvents = parsedEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); });
  12235. var contentQueryStartId = _this.contentQueryStartId;
  12236. _this.contentQueryStartId += directive.queries.length;
  12237. return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
  12238. });
  12239. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  12240. if (elOrDirRef.value.length > 0) {
  12241. if (!matchedReferences.has(elOrDirRef.name)) {
  12242. _this._reportError("There is no directive with \"exportAs\" set to \"" + elOrDirRef.value + "\"", elOrDirRef.sourceSpan);
  12243. }
  12244. }
  12245. else if (!component) {
  12246. var refToken = null;
  12247. if (isTemplateElement) {
  12248. refToken = createTokenForExternalReference(_this.reflector, Identifiers.TemplateRef);
  12249. }
  12250. targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
  12251. }
  12252. });
  12253. return directiveAsts;
  12254. };
  12255. TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
  12256. if (directiveProperties) {
  12257. var boundPropsByName_1 = new Map();
  12258. boundProps.forEach(function (boundProp) {
  12259. var prevValue = boundPropsByName_1.get(boundProp.name);
  12260. if (!prevValue || prevValue.isLiteral) {
  12261. // give [a]="b" a higher precedence than a="b" on the same element
  12262. boundPropsByName_1.set(boundProp.name, boundProp);
  12263. }
  12264. });
  12265. Object.keys(directiveProperties).forEach(function (dirProp) {
  12266. var elProp = directiveProperties[dirProp];
  12267. var boundProp = boundPropsByName_1.get(elProp);
  12268. // Bindings are optional, so this binding only needs to be set up if an expression is given.
  12269. if (boundProp) {
  12270. targetBoundDirectivePropNames.add(boundProp.name);
  12271. if (!isEmptyExpression(boundProp.expression)) {
  12272. targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
  12273. }
  12274. }
  12275. });
  12276. }
  12277. };
  12278. TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, boundDirectivePropNames) {
  12279. var _this = this;
  12280. var boundElementProps = [];
  12281. props.forEach(function (prop) {
  12282. if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
  12283. var boundProp = _this._bindingParser.createBoundElementProperty(elementName, prop);
  12284. boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
  12285. }
  12286. });
  12287. return this._checkPropertiesInSchema(elementName, boundElementProps);
  12288. };
  12289. TemplateParseVisitor.prototype._findComponentDirectives = function (directives) {
  12290. return directives.filter(function (directive) { return directive.directive.isComponent; });
  12291. };
  12292. TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
  12293. return this._findComponentDirectives(directives)
  12294. .map(function (directive) { return identifierName(directive.directive.type); });
  12295. };
  12296. TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
  12297. var componentTypeNames = this._findComponentDirectiveNames(directives);
  12298. if (componentTypeNames.length > 1) {
  12299. this._reportError("More than one component matched on this element.\n" +
  12300. "Make sure that only one component's selector can match a given element.\n" +
  12301. ("Conflicting components: " + componentTypeNames.join(',')), sourceSpan);
  12302. }
  12303. };
  12304. /**
  12305. * Make sure that non-angular tags conform to the schemas.
  12306. *
  12307. * Note: An element is considered an angular tag when at least one directive selector matches the
  12308. * tag name.
  12309. *
  12310. * @param matchElement Whether any directive has matched on the tag name
  12311. * @param element the html element
  12312. */
  12313. TemplateParseVisitor.prototype._assertElementExists = function (matchElement, element) {
  12314. var elName = element.name.replace(/^:xhtml:/, '');
  12315. if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
  12316. var errorMsg = "'" + elName + "' is not a known element:\n";
  12317. errorMsg +=
  12318. "1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n";
  12319. if (elName.indexOf('-') > -1) {
  12320. errorMsg +=
  12321. "2. If '" + elName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.";
  12322. }
  12323. else {
  12324. errorMsg +=
  12325. "2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12326. }
  12327. this._reportError(errorMsg, element.sourceSpan);
  12328. }
  12329. };
  12330. TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
  12331. var _this = this;
  12332. var componentTypeNames = this._findComponentDirectiveNames(directives);
  12333. if (componentTypeNames.length > 0) {
  12334. this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
  12335. }
  12336. elementProps.forEach(function (prop) {
  12337. _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);
  12338. });
  12339. };
  12340. TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
  12341. var _this = this;
  12342. var allDirectiveEvents = new Set();
  12343. directives.forEach(function (directive) {
  12344. Object.keys(directive.directive.outputs).forEach(function (k) {
  12345. var eventName = directive.directive.outputs[k];
  12346. allDirectiveEvents.add(eventName);
  12347. });
  12348. });
  12349. events.forEach(function (event) {
  12350. if (event.target != null || !allDirectiveEvents.has(event.name)) {
  12351. _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);
  12352. }
  12353. });
  12354. };
  12355. TemplateParseVisitor.prototype._checkPropertiesInSchema = function (elementName, boundProps) {
  12356. var _this = this;
  12357. // Note: We can't filter out empty expressions before this method,
  12358. // as we still want to validate them!
  12359. return boundProps.filter(function (boundProp) {
  12360. if (boundProp.type === 0 /* Property */ &&
  12361. !_this._schemaRegistry.hasProperty(elementName, boundProp.name, _this._schemas)) {
  12362. var errorMsg = "Can't bind to '" + boundProp.name + "' since it isn't a known property of '" + elementName + "'.";
  12363. if (elementName.startsWith('ng-')) {
  12364. errorMsg +=
  12365. "\n1. If '" + boundProp.name + "' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component." +
  12366. "\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12367. }
  12368. else if (elementName.indexOf('-') > -1) {
  12369. errorMsg +=
  12370. "\n1. If '" + elementName + "' is an Angular component and it has '" + boundProp.name + "' input, then verify that it is part of this module." +
  12371. ("\n2. If '" + elementName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.") +
  12372. "\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12373. }
  12374. _this._reportError(errorMsg, boundProp.sourceSpan);
  12375. }
  12376. return !isEmptyExpression(boundProp.value);
  12377. });
  12378. };
  12379. TemplateParseVisitor.prototype._reportError = function (message, sourceSpan, level) {
  12380. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  12381. this._targetErrors.push(new ParseError(sourceSpan, message, level));
  12382. };
  12383. return TemplateParseVisitor;
  12384. }());
  12385. var NonBindableVisitor = /** @class */ (function () {
  12386. function NonBindableVisitor() {
  12387. }
  12388. NonBindableVisitor.prototype.visitElement = function (ast, parent) {
  12389. var preparsedElement = preparseElement(ast);
  12390. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  12391. preparsedElement.type === PreparsedElementType.STYLE ||
  12392. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  12393. // Skipping <script> for security reasons
  12394. // Skipping <style> and stylesheets as we already processed them
  12395. // in the StyleCompiler
  12396. return null;
  12397. }
  12398. var attrNameAndValues = ast.attrs.map(function (attr) { return [attr.name, attr.value]; });
  12399. var selector = createElementCssSelector(ast.name, attrNameAndValues);
  12400. var ngContentIndex = parent.findNgContentIndex(selector);
  12401. var children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
  12402. return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
  12403. };
  12404. NonBindableVisitor.prototype.visitComment = function (comment, context) { return null; };
  12405. NonBindableVisitor.prototype.visitAttribute = function (attribute, context) {
  12406. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  12407. };
  12408. NonBindableVisitor.prototype.visitText = function (text, parent) {
  12409. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  12410. return new TextAst(text.value, ngContentIndex, text.sourceSpan);
  12411. };
  12412. NonBindableVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
  12413. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  12414. return NonBindableVisitor;
  12415. }());
  12416. /**
  12417. * A reference to an element or directive in a template. E.g., the reference in this template:
  12418. *
  12419. * <div #myMenu="coolMenu">
  12420. *
  12421. * would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
  12422. */
  12423. var ElementOrDirectiveRef = /** @class */ (function () {
  12424. function ElementOrDirectiveRef(name, value, sourceSpan) {
  12425. this.name = name;
  12426. this.value = value;
  12427. this.sourceSpan = sourceSpan;
  12428. }
  12429. /** Gets whether this is a reference to the given directive. */
  12430. ElementOrDirectiveRef.prototype.isReferenceToDirective = function (directive) {
  12431. return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
  12432. };
  12433. return ElementOrDirectiveRef;
  12434. }());
  12435. /** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
  12436. function splitExportAs(exportAs) {
  12437. return exportAs ? exportAs.split(',').map(function (e) { return e.trim(); }) : [];
  12438. }
  12439. function splitClasses(classAttrValue) {
  12440. return classAttrValue.trim().split(/\s+/g);
  12441. }
  12442. var ElementContext = /** @class */ (function () {
  12443. function ElementContext(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
  12444. this.isTemplateElement = isTemplateElement;
  12445. this._ngContentIndexMatcher = _ngContentIndexMatcher;
  12446. this._wildcardNgContentIndex = _wildcardNgContentIndex;
  12447. this.providerContext = providerContext;
  12448. }
  12449. ElementContext.create = function (isTemplateElement, directives, providerContext) {
  12450. var matcher = new SelectorMatcher();
  12451. var wildcardNgContentIndex = null;
  12452. var component = directives.find(function (directive) { return directive.directive.isComponent; });
  12453. if (component) {
  12454. var ngContentSelectors = component.directive.template.ngContentSelectors;
  12455. for (var i = 0; i < ngContentSelectors.length; i++) {
  12456. var selector = ngContentSelectors[i];
  12457. if (selector === '*') {
  12458. wildcardNgContentIndex = i;
  12459. }
  12460. else {
  12461. matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
  12462. }
  12463. }
  12464. }
  12465. return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
  12466. };
  12467. ElementContext.prototype.findNgContentIndex = function (selector) {
  12468. var ngContentIndices = [];
  12469. this._ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) { ngContentIndices.push(ngContentIndex); });
  12470. ngContentIndices.sort();
  12471. if (this._wildcardNgContentIndex != null) {
  12472. ngContentIndices.push(this._wildcardNgContentIndex);
  12473. }
  12474. return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
  12475. };
  12476. return ElementContext;
  12477. }());
  12478. function createElementCssSelector(elementName, attributes) {
  12479. var cssSelector = new CssSelector();
  12480. var elNameNoNs = splitNsName(elementName)[1];
  12481. cssSelector.setElement(elNameNoNs);
  12482. for (var i = 0; i < attributes.length; i++) {
  12483. var attrName = attributes[i][0];
  12484. var attrNameNoNs = splitNsName(attrName)[1];
  12485. var attrValue = attributes[i][1];
  12486. cssSelector.addAttribute(attrNameNoNs, attrValue);
  12487. if (attrName.toLowerCase() == CLASS_ATTR) {
  12488. var classes = splitClasses(attrValue);
  12489. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  12490. }
  12491. }
  12492. return cssSelector;
  12493. }
  12494. var EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
  12495. var NON_BINDABLE_VISITOR = new NonBindableVisitor();
  12496. function _isEmptyTextNode(node) {
  12497. return node instanceof Text$3 && node.value.trim().length == 0;
  12498. }
  12499. function removeSummaryDuplicates(items) {
  12500. var map = new Map();
  12501. items.forEach(function (item) {
  12502. if (!map.get(item.type.reference)) {
  12503. map.set(item.type.reference, item);
  12504. }
  12505. });
  12506. return Array.from(map.values());
  12507. }
  12508. function isEmptyExpression(ast) {
  12509. if (ast instanceof ASTWithSource) {
  12510. ast = ast.ast;
  12511. }
  12512. return ast instanceof EmptyExpr;
  12513. }
  12514. /**
  12515. * @license
  12516. * Copyright Google Inc. All Rights Reserved.
  12517. *
  12518. * Use of this source code is governed by an MIT-style license that can be
  12519. * found in the LICENSE file at https://angular.io/license
  12520. */
  12521. /**
  12522. * Parses string representation of a style and converts it into object literal.
  12523. *
  12524. * @param value string representation of style as used in the `style` attribute in HTML.
  12525. * Example: `color: red; height: auto`.
  12526. * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
  12527. * 'auto']`
  12528. */
  12529. function parse(value) {
  12530. // we use a string array here instead of a string map
  12531. // because a string-map is not guaranteed to retain the
  12532. // order of the entries whereas a string array can be
  12533. // construted in a [key, value, key, value] format.
  12534. var styles = [];
  12535. var i = 0;
  12536. var parenDepth = 0;
  12537. var quote = 0 /* QuoteNone */;
  12538. var valueStart = 0;
  12539. var propStart = 0;
  12540. var currentProp = null;
  12541. var valueHasQuotes = false;
  12542. while (i < value.length) {
  12543. var token = value.charCodeAt(i++);
  12544. switch (token) {
  12545. case 40 /* OpenParen */:
  12546. parenDepth++;
  12547. break;
  12548. case 41 /* CloseParen */:
  12549. parenDepth--;
  12550. break;
  12551. case 39 /* QuoteSingle */:
  12552. // valueStart needs to be there since prop values don't
  12553. // have quotes in CSS
  12554. valueHasQuotes = valueHasQuotes || valueStart > 0;
  12555. if (quote === 0 /* QuoteNone */) {
  12556. quote = 39 /* QuoteSingle */;
  12557. }
  12558. else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  12559. quote = 0 /* QuoteNone */;
  12560. }
  12561. break;
  12562. case 34 /* QuoteDouble */:
  12563. // same logic as above
  12564. valueHasQuotes = valueHasQuotes || valueStart > 0;
  12565. if (quote === 0 /* QuoteNone */) {
  12566. quote = 34 /* QuoteDouble */;
  12567. }
  12568. else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  12569. quote = 0 /* QuoteNone */;
  12570. }
  12571. break;
  12572. case 58 /* Colon */:
  12573. if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  12574. currentProp = hyphenate(value.substring(propStart, i - 1).trim());
  12575. valueStart = i;
  12576. }
  12577. break;
  12578. case 59 /* Semicolon */:
  12579. if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  12580. var styleVal = value.substring(valueStart, i - 1).trim();
  12581. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  12582. propStart = i;
  12583. valueStart = 0;
  12584. currentProp = null;
  12585. valueHasQuotes = false;
  12586. }
  12587. break;
  12588. }
  12589. }
  12590. if (currentProp && valueStart) {
  12591. var styleVal = value.substr(valueStart).trim();
  12592. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  12593. }
  12594. return styles;
  12595. }
  12596. function stripUnnecessaryQuotes(value) {
  12597. var qS = value.charCodeAt(0);
  12598. var qE = value.charCodeAt(value.length - 1);
  12599. if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
  12600. var tempValue = value.substring(1, value.length - 1);
  12601. // special case to avoid using a multi-quoted string that was just chomped
  12602. // (e.g. `font-family: "Verdana", "sans-serif"`)
  12603. if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
  12604. value = tempValue;
  12605. }
  12606. }
  12607. return value;
  12608. }
  12609. function hyphenate(value) {
  12610. return value.replace(/[a-z][A-Z]/g, function (v) {
  12611. return v.charAt(0) + '-' + v.charAt(1);
  12612. }).toLowerCase();
  12613. }
  12614. /**
  12615. * @license
  12616. * Copyright Google Inc. All Rights Reserved.
  12617. *
  12618. * Use of this source code is governed by an MIT-style license that can be
  12619. * found in the LICENSE file at https://angular.io/license
  12620. */
  12621. var _stylingMode = 0;
  12622. function compilerIsNewStylingInUse() {
  12623. return _stylingMode > 0 /* UseOld */;
  12624. }
  12625. var IMPORTANT_FLAG = '!important';
  12626. /**
  12627. * Produces creation/update instructions for all styling bindings (class and style)
  12628. *
  12629. * It also produces the creation instruction to register all initial styling values
  12630. * (which are all the static class="..." and style="..." attribute values that exist
  12631. * on an element within a template).
  12632. *
  12633. * The builder class below handles producing instructions for the following cases:
  12634. *
  12635. * - Static style/class attributes (style="..." and class="...")
  12636. * - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
  12637. * - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
  12638. *
  12639. * Due to the complex relationship of all of these cases, the instructions generated
  12640. * for these attributes/properties/bindings must be done so in the correct order. The
  12641. * order which these must be generated is as follows:
  12642. *
  12643. * if (createMode) {
  12644. * styling(...)
  12645. * }
  12646. * if (updateMode) {
  12647. * styleMap(...)
  12648. * classMap(...)
  12649. * styleProp(...)
  12650. * classProp(...)
  12651. * stylingApp(...)
  12652. * }
  12653. *
  12654. * The creation/update methods within the builder class produce these instructions.
  12655. */
  12656. var StylingBuilder = /** @class */ (function () {
  12657. function StylingBuilder(_elementIndexExpr, _directiveExpr) {
  12658. this._elementIndexExpr = _elementIndexExpr;
  12659. this._directiveExpr = _directiveExpr;
  12660. /** Whether or not there are any static styling values present */
  12661. this._hasInitialValues = false;
  12662. /**
  12663. * Whether or not there are any styling bindings present
  12664. * (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
  12665. */
  12666. this.hasBindings = false;
  12667. /** the input for [class] (if it exists) */
  12668. this._classMapInput = null;
  12669. /** the input for [style] (if it exists) */
  12670. this._styleMapInput = null;
  12671. /** an array of each [style.prop] input */
  12672. this._singleStyleInputs = null;
  12673. /** an array of each [class.name] input */
  12674. this._singleClassInputs = null;
  12675. this._lastStylingInput = null;
  12676. this._firstStylingInput = null;
  12677. // maps are used instead of hash maps because a Map will
  12678. // retain the ordering of the keys
  12679. /**
  12680. * Represents the location of each style binding in the template
  12681. * (e.g. `<div [style.width]="w" [style.height]="h">` implies
  12682. * that `width=0` and `height=1`)
  12683. */
  12684. this._stylesIndex = new Map();
  12685. /**
  12686. * Represents the location of each class binding in the template
  12687. * (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
  12688. * that `big=0` and `hidden=1`)
  12689. */
  12690. this._classesIndex = new Map();
  12691. this._initialStyleValues = [];
  12692. this._initialClassValues = [];
  12693. // certain style properties ALWAYS need sanitization
  12694. // this is checked each time new styles are encountered
  12695. this._useDefaultSanitizer = false;
  12696. }
  12697. /**
  12698. * Registers a given input to the styling builder to be later used when producing AOT code.
  12699. *
  12700. * The code below will only accept the input if it is somehow tied to styling (whether it be
  12701. * style/class bindings or static style/class attributes).
  12702. */
  12703. StylingBuilder.prototype.registerBoundInput = function (input) {
  12704. // [attr.style] or [attr.class] are skipped in the code below,
  12705. // they should not be treated as styling-based bindings since
  12706. // they are intended to be written directly to the attr and
  12707. // will therefore skip all style/class resolution that is present
  12708. // with style="", [style]="" and [style.prop]="", class="",
  12709. // [class.prop]="". [class]="" assignments
  12710. var binding = null;
  12711. var name = input.name;
  12712. switch (input.type) {
  12713. case 0 /* Property */:
  12714. binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
  12715. break;
  12716. case 3 /* Style */:
  12717. binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
  12718. break;
  12719. case 2 /* Class */:
  12720. binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
  12721. break;
  12722. }
  12723. return binding ? true : false;
  12724. };
  12725. StylingBuilder.prototype.registerInputBasedOnName = function (name, expression, sourceSpan) {
  12726. var binding = null;
  12727. var nameToMatch = name.substring(0, 5); // class | style
  12728. var isStyle = nameToMatch === 'style';
  12729. var isClass = isStyle ? false : (nameToMatch === 'class');
  12730. if (isStyle || isClass) {
  12731. var isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
  12732. var property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
  12733. if (isStyle) {
  12734. binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
  12735. }
  12736. else {
  12737. binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
  12738. }
  12739. }
  12740. return binding;
  12741. };
  12742. StylingBuilder.prototype.registerStyleInput = function (name, isMapBased, value, sourceSpan, unit) {
  12743. if (isEmptyExpression(value)) {
  12744. return null;
  12745. }
  12746. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag, bindingUnit = _a.unit;
  12747. var entry = {
  12748. name: property,
  12749. unit: unit || bindingUnit, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag
  12750. };
  12751. if (isMapBased) {
  12752. this._useDefaultSanitizer = true;
  12753. this._styleMapInput = entry;
  12754. }
  12755. else {
  12756. (this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
  12757. this._useDefaultSanitizer = this._useDefaultSanitizer || isStyleSanitizable(name);
  12758. registerIntoMap(this._stylesIndex, property);
  12759. }
  12760. this._lastStylingInput = entry;
  12761. this._firstStylingInput = this._firstStylingInput || entry;
  12762. this.hasBindings = true;
  12763. return entry;
  12764. };
  12765. StylingBuilder.prototype.registerClassInput = function (name, isMapBased, value, sourceSpan) {
  12766. if (isEmptyExpression(value)) {
  12767. return null;
  12768. }
  12769. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag;
  12770. var entry = { name: property, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag, unit: null };
  12771. if (isMapBased) {
  12772. this._classMapInput = entry;
  12773. }
  12774. else {
  12775. (this._singleClassInputs = this._singleClassInputs || []).push(entry);
  12776. registerIntoMap(this._classesIndex, property);
  12777. }
  12778. this._lastStylingInput = entry;
  12779. this._firstStylingInput = this._firstStylingInput || entry;
  12780. this.hasBindings = true;
  12781. return entry;
  12782. };
  12783. /**
  12784. * Registers the element's static style string value to the builder.
  12785. *
  12786. * @param value the style string (e.g. `width:100px; height:200px;`)
  12787. */
  12788. StylingBuilder.prototype.registerStyleAttr = function (value) {
  12789. this._initialStyleValues = parse(value);
  12790. this._hasInitialValues = true;
  12791. };
  12792. /**
  12793. * Registers the element's static class string value to the builder.
  12794. *
  12795. * @param value the className string (e.g. `disabled gold zoom`)
  12796. */
  12797. StylingBuilder.prototype.registerClassAttr = function (value) {
  12798. this._initialClassValues = value.trim().split(/\s+/g);
  12799. this._hasInitialValues = true;
  12800. };
  12801. /**
  12802. * Appends all styling-related expressions to the provided attrs array.
  12803. *
  12804. * @param attrs an existing array where each of the styling expressions
  12805. * will be inserted into.
  12806. */
  12807. StylingBuilder.prototype.populateInitialStylingAttrs = function (attrs) {
  12808. // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
  12809. if (this._initialClassValues.length) {
  12810. attrs.push(literal(1 /* Classes */));
  12811. for (var i = 0; i < this._initialClassValues.length; i++) {
  12812. attrs.push(literal(this._initialClassValues[i]));
  12813. }
  12814. }
  12815. // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
  12816. if (this._initialStyleValues.length) {
  12817. attrs.push(literal(2 /* Styles */));
  12818. for (var i = 0; i < this._initialStyleValues.length; i += 2) {
  12819. attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
  12820. }
  12821. }
  12822. };
  12823. /**
  12824. * Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
  12825. *
  12826. * The instruction generation code below is used for producing the AOT statement code which is
  12827. * responsible for registering initial styles (within a directive hostBindings' creation block),
  12828. * as well as any of the provided attribute values, to the directive host element.
  12829. */
  12830. StylingBuilder.prototype.buildHostAttrsInstruction = function (sourceSpan, attrs, constantPool) {
  12831. var _this = this;
  12832. if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
  12833. return {
  12834. sourceSpan: sourceSpan,
  12835. reference: Identifiers$1.elementHostAttrs,
  12836. allocateBindingSlots: 0,
  12837. buildParams: function () {
  12838. // params => elementHostAttrs(attrs)
  12839. _this.populateInitialStylingAttrs(attrs);
  12840. var attrArray = !attrs.some(function (attr) { return attr instanceof WrappedNodeExpr; }) ?
  12841. getConstantLiteralFromArray(constantPool, attrs) :
  12842. literalArr(attrs);
  12843. return [attrArray];
  12844. }
  12845. };
  12846. }
  12847. return null;
  12848. };
  12849. /**
  12850. * Builds an instruction with all the expressions and parameters for `styling`.
  12851. *
  12852. * The instruction generation code below is used for producing the AOT statement code which is
  12853. * responsible for registering style/class bindings to an element.
  12854. */
  12855. StylingBuilder.prototype.buildStylingInstruction = function (sourceSpan, constantPool) {
  12856. var _this = this;
  12857. if (this.hasBindings) {
  12858. return {
  12859. sourceSpan: sourceSpan,
  12860. allocateBindingSlots: 0,
  12861. reference: Identifiers$1.styling,
  12862. buildParams: function () {
  12863. // a string array of every style-based binding
  12864. var styleBindingProps = _this._singleStyleInputs ? _this._singleStyleInputs.map(function (i) { return literal(i.name); }) : [];
  12865. // a string array of every class-based binding
  12866. var classBindingNames = _this._singleClassInputs ? _this._singleClassInputs.map(function (i) { return literal(i.name); }) : [];
  12867. // to salvage space in the AOT generated code, there is no point in passing
  12868. // in `null` into a param if any follow-up params are not used. Therefore,
  12869. // only when a trailing param is used then it will be filled with nulls in between
  12870. // (otherwise a shorter amount of params will be filled). The code below helps
  12871. // determine how many params are required in the expression code.
  12872. //
  12873. // min params => styling()
  12874. // max params => styling(classBindings, styleBindings, sanitizer)
  12875. //
  12876. var params = [];
  12877. var expectedNumberOfArgs = 0;
  12878. if (_this._useDefaultSanitizer) {
  12879. expectedNumberOfArgs = 3;
  12880. }
  12881. else if (styleBindingProps.length) {
  12882. expectedNumberOfArgs = 2;
  12883. }
  12884. else if (classBindingNames.length) {
  12885. expectedNumberOfArgs = 1;
  12886. }
  12887. addParam(params, classBindingNames.length > 0, getConstantLiteralFromArray(constantPool, classBindingNames), 1, expectedNumberOfArgs);
  12888. addParam(params, styleBindingProps.length > 0, getConstantLiteralFromArray(constantPool, styleBindingProps), 2, expectedNumberOfArgs);
  12889. addParam(params, _this._useDefaultSanitizer, importExpr(Identifiers$1.defaultStyleSanitizer), 3, expectedNumberOfArgs);
  12890. return params;
  12891. }
  12892. };
  12893. }
  12894. return null;
  12895. };
  12896. /**
  12897. * Builds an instruction with all the expressions and parameters for `classMap`.
  12898. *
  12899. * The instruction data will contain all expressions for `classMap` to function
  12900. * which includes the `[class]` expression params.
  12901. */
  12902. StylingBuilder.prototype.buildClassMapInstruction = function (valueConverter) {
  12903. if (this._classMapInput) {
  12904. return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
  12905. }
  12906. return null;
  12907. };
  12908. /**
  12909. * Builds an instruction with all the expressions and parameters for `styleMap`.
  12910. *
  12911. * The instruction data will contain all expressions for `styleMap` to function
  12912. * which includes the `[style]` expression params.
  12913. */
  12914. StylingBuilder.prototype.buildStyleMapInstruction = function (valueConverter) {
  12915. if (this._styleMapInput) {
  12916. return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
  12917. }
  12918. return null;
  12919. };
  12920. StylingBuilder.prototype._buildMapBasedInstruction = function (valueConverter, isClassBased, stylingInput) {
  12921. var totalBindingSlotsRequired = 0;
  12922. if (compilerIsNewStylingInUse()) {
  12923. // the old implementation does not reserve slot values for
  12924. // binding entries. The new one does.
  12925. totalBindingSlotsRequired++;
  12926. }
  12927. // these values must be outside of the update block so that they can
  12928. // be evaluated (the AST visit call) during creation time so that any
  12929. // pipes can be picked up in time before the template is built
  12930. var mapValue = stylingInput.value.visit(valueConverter);
  12931. if (mapValue instanceof Interpolation) {
  12932. totalBindingSlotsRequired += mapValue.expressions.length;
  12933. }
  12934. var reference = isClassBased ? Identifiers$1.classMap : Identifiers$1.styleMap;
  12935. return {
  12936. sourceSpan: stylingInput.sourceSpan,
  12937. reference: reference,
  12938. allocateBindingSlots: totalBindingSlotsRequired,
  12939. buildParams: function (convertFn) { return [convertFn(mapValue)]; }
  12940. };
  12941. };
  12942. StylingBuilder.prototype._buildSingleInputs = function (reference, inputs, mapIndex, allowUnits, valueConverter) {
  12943. var totalBindingSlotsRequired = 0;
  12944. return inputs.map(function (input) {
  12945. var bindingIndex = mapIndex.get(input.name);
  12946. var value = input.value.visit(valueConverter);
  12947. totalBindingSlotsRequired += (value instanceof Interpolation) ? value.expressions.length : 0;
  12948. if (compilerIsNewStylingInUse()) {
  12949. // the old implementation does not reserve slot values for
  12950. // binding entries. The new one does.
  12951. totalBindingSlotsRequired++;
  12952. }
  12953. return {
  12954. sourceSpan: input.sourceSpan,
  12955. allocateBindingSlots: totalBindingSlotsRequired, reference: reference,
  12956. buildParams: function (convertFn) {
  12957. // min params => stylingProp(elmIndex, bindingIndex, value)
  12958. // max params => stylingProp(elmIndex, bindingIndex, value, overrideFlag)
  12959. var params = [];
  12960. params.push(literal(bindingIndex));
  12961. params.push(convertFn(value));
  12962. if (allowUnits) {
  12963. if (input.unit) {
  12964. params.push(literal(input.unit));
  12965. }
  12966. else if (input.hasOverrideFlag) {
  12967. params.push(NULL_EXPR);
  12968. }
  12969. }
  12970. if (input.hasOverrideFlag) {
  12971. params.push(literal(true));
  12972. }
  12973. return params;
  12974. }
  12975. };
  12976. });
  12977. };
  12978. StylingBuilder.prototype._buildClassInputs = function (valueConverter) {
  12979. if (this._singleClassInputs) {
  12980. return this._buildSingleInputs(Identifiers$1.classProp, this._singleClassInputs, this._classesIndex, false, valueConverter);
  12981. }
  12982. return [];
  12983. };
  12984. StylingBuilder.prototype._buildStyleInputs = function (valueConverter) {
  12985. if (this._singleStyleInputs) {
  12986. return this._buildSingleInputs(Identifiers$1.styleProp, this._singleStyleInputs, this._stylesIndex, true, valueConverter);
  12987. }
  12988. return [];
  12989. };
  12990. StylingBuilder.prototype._buildApplyFn = function () {
  12991. return {
  12992. sourceSpan: this._lastStylingInput ? this._lastStylingInput.sourceSpan : null,
  12993. reference: Identifiers$1.stylingApply,
  12994. allocateBindingSlots: 0,
  12995. buildParams: function () { return []; }
  12996. };
  12997. };
  12998. StylingBuilder.prototype._buildSanitizerFn = function () {
  12999. return {
  13000. sourceSpan: this._firstStylingInput ? this._firstStylingInput.sourceSpan : null,
  13001. reference: Identifiers$1.styleSanitizer,
  13002. allocateBindingSlots: 0,
  13003. buildParams: function () { return [importExpr(Identifiers$1.defaultStyleSanitizer)]; }
  13004. };
  13005. };
  13006. /**
  13007. * Constructs all instructions which contain the expressions that will be placed
  13008. * into the update block of a template function or a directive hostBindings function.
  13009. */
  13010. StylingBuilder.prototype.buildUpdateLevelInstructions = function (valueConverter) {
  13011. var instructions = [];
  13012. if (this.hasBindings) {
  13013. if (compilerIsNewStylingInUse() && this._useDefaultSanitizer) {
  13014. instructions.push(this._buildSanitizerFn());
  13015. }
  13016. var styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
  13017. if (styleMapInstruction) {
  13018. instructions.push(styleMapInstruction);
  13019. }
  13020. var classMapInstruction = this.buildClassMapInstruction(valueConverter);
  13021. if (classMapInstruction) {
  13022. instructions.push(classMapInstruction);
  13023. }
  13024. instructions.push.apply(instructions, __spread(this._buildStyleInputs(valueConverter)));
  13025. instructions.push.apply(instructions, __spread(this._buildClassInputs(valueConverter)));
  13026. instructions.push(this._buildApplyFn());
  13027. }
  13028. return instructions;
  13029. };
  13030. return StylingBuilder;
  13031. }());
  13032. function registerIntoMap(map, key) {
  13033. if (!map.has(key)) {
  13034. map.set(key, map.size);
  13035. }
  13036. }
  13037. function isStyleSanitizable(prop) {
  13038. // Note that browsers support both the dash case and
  13039. // camel case property names when setting through JS.
  13040. return prop === 'background-image' || prop === 'backgroundImage' || prop === 'background' ||
  13041. prop === 'border-image' || prop === 'borderImage' || prop === 'filter' ||
  13042. prop === 'list-style' || prop === 'listStyle' || prop === 'list-style-image' ||
  13043. prop === 'listStyleImage' || prop === 'clip-path' || prop === 'clipPath';
  13044. }
  13045. /**
  13046. * Simple helper function to either provide the constant literal that will house the value
  13047. * here or a null value if the provided values are empty.
  13048. */
  13049. function getConstantLiteralFromArray(constantPool, values) {
  13050. return values.length ? constantPool.getConstLiteral(literalArr(values), true) : NULL_EXPR;
  13051. }
  13052. /**
  13053. * Simple helper function that adds a parameter or does nothing at all depending on the provided
  13054. * predicate and totalExpectedArgs values
  13055. */
  13056. function addParam(params, predicate, value, argNumber, totalExpectedArgs) {
  13057. if (predicate && value) {
  13058. params.push(value);
  13059. }
  13060. else if (argNumber < totalExpectedArgs) {
  13061. params.push(NULL_EXPR);
  13062. }
  13063. }
  13064. function parseProperty(name) {
  13065. var hasOverrideFlag = false;
  13066. var overrideIndex = name.indexOf(IMPORTANT_FLAG);
  13067. if (overrideIndex !== -1) {
  13068. name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
  13069. hasOverrideFlag = true;
  13070. }
  13071. var unit = '';
  13072. var property = name;
  13073. var unitIndex = name.lastIndexOf('.');
  13074. if (unitIndex > 0) {
  13075. unit = name.substr(unitIndex + 1);
  13076. property = name.substring(0, unitIndex);
  13077. }
  13078. return { property: property, unit: unit, hasOverrideFlag: hasOverrideFlag };
  13079. }
  13080. /**
  13081. * @license
  13082. * Copyright Google Inc. All Rights Reserved.
  13083. *
  13084. * Use of this source code is governed by an MIT-style license that can be
  13085. * found in the LICENSE file at https://angular.io/license
  13086. */
  13087. var TokenType$1;
  13088. (function (TokenType) {
  13089. TokenType[TokenType["Character"] = 0] = "Character";
  13090. TokenType[TokenType["Identifier"] = 1] = "Identifier";
  13091. TokenType[TokenType["Keyword"] = 2] = "Keyword";
  13092. TokenType[TokenType["String"] = 3] = "String";
  13093. TokenType[TokenType["Operator"] = 4] = "Operator";
  13094. TokenType[TokenType["Number"] = 5] = "Number";
  13095. TokenType[TokenType["Error"] = 6] = "Error";
  13096. })(TokenType$1 || (TokenType$1 = {}));
  13097. var KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
  13098. var Lexer = /** @class */ (function () {
  13099. function Lexer() {
  13100. }
  13101. Lexer.prototype.tokenize = function (text) {
  13102. var scanner = new _Scanner(text);
  13103. var tokens = [];
  13104. var token = scanner.scanToken();
  13105. while (token != null) {
  13106. tokens.push(token);
  13107. token = scanner.scanToken();
  13108. }
  13109. return tokens;
  13110. };
  13111. return Lexer;
  13112. }());
  13113. var Token$1 = /** @class */ (function () {
  13114. function Token(index, type, numValue, strValue) {
  13115. this.index = index;
  13116. this.type = type;
  13117. this.numValue = numValue;
  13118. this.strValue = strValue;
  13119. }
  13120. Token.prototype.isCharacter = function (code) {
  13121. return this.type == TokenType$1.Character && this.numValue == code;
  13122. };
  13123. Token.prototype.isNumber = function () { return this.type == TokenType$1.Number; };
  13124. Token.prototype.isString = function () { return this.type == TokenType$1.String; };
  13125. Token.prototype.isOperator = function (operator) {
  13126. return this.type == TokenType$1.Operator && this.strValue == operator;
  13127. };
  13128. Token.prototype.isIdentifier = function () { return this.type == TokenType$1.Identifier; };
  13129. Token.prototype.isKeyword = function () { return this.type == TokenType$1.Keyword; };
  13130. Token.prototype.isKeywordLet = function () { return this.type == TokenType$1.Keyword && this.strValue == 'let'; };
  13131. Token.prototype.isKeywordAs = function () { return this.type == TokenType$1.Keyword && this.strValue == 'as'; };
  13132. Token.prototype.isKeywordNull = function () { return this.type == TokenType$1.Keyword && this.strValue == 'null'; };
  13133. Token.prototype.isKeywordUndefined = function () {
  13134. return this.type == TokenType$1.Keyword && this.strValue == 'undefined';
  13135. };
  13136. Token.prototype.isKeywordTrue = function () { return this.type == TokenType$1.Keyword && this.strValue == 'true'; };
  13137. Token.prototype.isKeywordFalse = function () { return this.type == TokenType$1.Keyword && this.strValue == 'false'; };
  13138. Token.prototype.isKeywordThis = function () { return this.type == TokenType$1.Keyword && this.strValue == 'this'; };
  13139. Token.prototype.isError = function () { return this.type == TokenType$1.Error; };
  13140. Token.prototype.toNumber = function () { return this.type == TokenType$1.Number ? this.numValue : -1; };
  13141. Token.prototype.toString = function () {
  13142. switch (this.type) {
  13143. case TokenType$1.Character:
  13144. case TokenType$1.Identifier:
  13145. case TokenType$1.Keyword:
  13146. case TokenType$1.Operator:
  13147. case TokenType$1.String:
  13148. case TokenType$1.Error:
  13149. return this.strValue;
  13150. case TokenType$1.Number:
  13151. return this.numValue.toString();
  13152. default:
  13153. return null;
  13154. }
  13155. };
  13156. return Token;
  13157. }());
  13158. function newCharacterToken(index, code) {
  13159. return new Token$1(index, TokenType$1.Character, code, String.fromCharCode(code));
  13160. }
  13161. function newIdentifierToken(index, text) {
  13162. return new Token$1(index, TokenType$1.Identifier, 0, text);
  13163. }
  13164. function newKeywordToken(index, text) {
  13165. return new Token$1(index, TokenType$1.Keyword, 0, text);
  13166. }
  13167. function newOperatorToken(index, text) {
  13168. return new Token$1(index, TokenType$1.Operator, 0, text);
  13169. }
  13170. function newStringToken(index, text) {
  13171. return new Token$1(index, TokenType$1.String, 0, text);
  13172. }
  13173. function newNumberToken(index, n) {
  13174. return new Token$1(index, TokenType$1.Number, n, '');
  13175. }
  13176. function newErrorToken(index, message) {
  13177. return new Token$1(index, TokenType$1.Error, 0, message);
  13178. }
  13179. var EOF = new Token$1(-1, TokenType$1.Character, 0, '');
  13180. var _Scanner = /** @class */ (function () {
  13181. function _Scanner(input) {
  13182. this.input = input;
  13183. this.peek = 0;
  13184. this.index = -1;
  13185. this.length = input.length;
  13186. this.advance();
  13187. }
  13188. _Scanner.prototype.advance = function () {
  13189. this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
  13190. };
  13191. _Scanner.prototype.scanToken = function () {
  13192. var input = this.input, length = this.length;
  13193. var peek = this.peek, index = this.index;
  13194. // Skip whitespace.
  13195. while (peek <= $SPACE) {
  13196. if (++index >= length) {
  13197. peek = $EOF;
  13198. break;
  13199. }
  13200. else {
  13201. peek = input.charCodeAt(index);
  13202. }
  13203. }
  13204. this.peek = peek;
  13205. this.index = index;
  13206. if (index >= length) {
  13207. return null;
  13208. }
  13209. // Handle identifiers and numbers.
  13210. if (isIdentifierStart(peek))
  13211. return this.scanIdentifier();
  13212. if (isDigit(peek))
  13213. return this.scanNumber(index);
  13214. var start = index;
  13215. switch (peek) {
  13216. case $PERIOD:
  13217. this.advance();
  13218. return isDigit(this.peek) ? this.scanNumber(start) :
  13219. newCharacterToken(start, $PERIOD);
  13220. case $LPAREN:
  13221. case $RPAREN:
  13222. case $LBRACE:
  13223. case $RBRACE:
  13224. case $LBRACKET:
  13225. case $RBRACKET:
  13226. case $COMMA:
  13227. case $COLON:
  13228. case $SEMICOLON:
  13229. return this.scanCharacter(start, peek);
  13230. case $SQ:
  13231. case $DQ:
  13232. return this.scanString();
  13233. case $HASH:
  13234. case $PLUS:
  13235. case $MINUS:
  13236. case $STAR:
  13237. case $SLASH:
  13238. case $PERCENT:
  13239. case $CARET:
  13240. return this.scanOperator(start, String.fromCharCode(peek));
  13241. case $QUESTION:
  13242. return this.scanComplexOperator(start, '?', $PERIOD, '.');
  13243. case $LT:
  13244. case $GT:
  13245. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
  13246. case $BANG:
  13247. case $EQ:
  13248. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
  13249. case $AMPERSAND:
  13250. return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
  13251. case $BAR:
  13252. return this.scanComplexOperator(start, '|', $BAR, '|');
  13253. case $NBSP:
  13254. while (isWhitespace(this.peek))
  13255. this.advance();
  13256. return this.scanToken();
  13257. }
  13258. this.advance();
  13259. return this.error("Unexpected character [" + String.fromCharCode(peek) + "]", 0);
  13260. };
  13261. _Scanner.prototype.scanCharacter = function (start, code) {
  13262. this.advance();
  13263. return newCharacterToken(start, code);
  13264. };
  13265. _Scanner.prototype.scanOperator = function (start, str) {
  13266. this.advance();
  13267. return newOperatorToken(start, str);
  13268. };
  13269. /**
  13270. * Tokenize a 2/3 char long operator
  13271. *
  13272. * @param start start index in the expression
  13273. * @param one first symbol (always part of the operator)
  13274. * @param twoCode code point for the second symbol
  13275. * @param two second symbol (part of the operator when the second code point matches)
  13276. * @param threeCode code point for the third symbol
  13277. * @param three third symbol (part of the operator when provided and matches source expression)
  13278. */
  13279. _Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
  13280. this.advance();
  13281. var str = one;
  13282. if (this.peek == twoCode) {
  13283. this.advance();
  13284. str += two;
  13285. }
  13286. if (threeCode != null && this.peek == threeCode) {
  13287. this.advance();
  13288. str += three;
  13289. }
  13290. return newOperatorToken(start, str);
  13291. };
  13292. _Scanner.prototype.scanIdentifier = function () {
  13293. var start = this.index;
  13294. this.advance();
  13295. while (isIdentifierPart(this.peek))
  13296. this.advance();
  13297. var str = this.input.substring(start, this.index);
  13298. return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
  13299. newIdentifierToken(start, str);
  13300. };
  13301. _Scanner.prototype.scanNumber = function (start) {
  13302. var simple = (this.index === start);
  13303. this.advance(); // Skip initial digit.
  13304. while (true) {
  13305. if (isDigit(this.peek)) ;
  13306. else if (this.peek == $PERIOD) {
  13307. simple = false;
  13308. }
  13309. else if (isExponentStart(this.peek)) {
  13310. this.advance();
  13311. if (isExponentSign(this.peek))
  13312. this.advance();
  13313. if (!isDigit(this.peek))
  13314. return this.error('Invalid exponent', -1);
  13315. simple = false;
  13316. }
  13317. else {
  13318. break;
  13319. }
  13320. this.advance();
  13321. }
  13322. var str = this.input.substring(start, this.index);
  13323. var value = simple ? parseIntAutoRadix(str) : parseFloat(str);
  13324. return newNumberToken(start, value);
  13325. };
  13326. _Scanner.prototype.scanString = function () {
  13327. var start = this.index;
  13328. var quote = this.peek;
  13329. this.advance(); // Skip initial quote.
  13330. var buffer = '';
  13331. var marker = this.index;
  13332. var input = this.input;
  13333. while (this.peek != quote) {
  13334. if (this.peek == $BACKSLASH) {
  13335. buffer += input.substring(marker, this.index);
  13336. this.advance();
  13337. var unescapedCode = void 0;
  13338. // Workaround for TS2.1-introduced type strictness
  13339. this.peek = this.peek;
  13340. if (this.peek == $u) {
  13341. // 4 character hex code for unicode character.
  13342. var hex = input.substring(this.index + 1, this.index + 5);
  13343. if (/^[0-9a-f]+$/i.test(hex)) {
  13344. unescapedCode = parseInt(hex, 16);
  13345. }
  13346. else {
  13347. return this.error("Invalid unicode escape [\\u" + hex + "]", 0);
  13348. }
  13349. for (var i = 0; i < 5; i++) {
  13350. this.advance();
  13351. }
  13352. }
  13353. else {
  13354. unescapedCode = unescape(this.peek);
  13355. this.advance();
  13356. }
  13357. buffer += String.fromCharCode(unescapedCode);
  13358. marker = this.index;
  13359. }
  13360. else if (this.peek == $EOF) {
  13361. return this.error('Unterminated quote', 0);
  13362. }
  13363. else {
  13364. this.advance();
  13365. }
  13366. }
  13367. var last = input.substring(marker, this.index);
  13368. this.advance(); // Skip terminating quote.
  13369. return newStringToken(start, buffer + last);
  13370. };
  13371. _Scanner.prototype.error = function (message, offset) {
  13372. var position = this.index + offset;
  13373. return newErrorToken(position, "Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
  13374. };
  13375. return _Scanner;
  13376. }());
  13377. function isIdentifierStart(code) {
  13378. return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
  13379. (code == $_) || (code == $$);
  13380. }
  13381. function isIdentifier(input) {
  13382. if (input.length == 0)
  13383. return false;
  13384. var scanner = new _Scanner(input);
  13385. if (!isIdentifierStart(scanner.peek))
  13386. return false;
  13387. scanner.advance();
  13388. while (scanner.peek !== $EOF) {
  13389. if (!isIdentifierPart(scanner.peek))
  13390. return false;
  13391. scanner.advance();
  13392. }
  13393. return true;
  13394. }
  13395. function isIdentifierPart(code) {
  13396. return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
  13397. (code == $$);
  13398. }
  13399. function isExponentStart(code) {
  13400. return code == $e || code == $E;
  13401. }
  13402. function isExponentSign(code) {
  13403. return code == $MINUS || code == $PLUS;
  13404. }
  13405. function isQuote(code) {
  13406. return code === $SQ || code === $DQ || code === $BT;
  13407. }
  13408. function unescape(code) {
  13409. switch (code) {
  13410. case $n:
  13411. return $LF;
  13412. case $f:
  13413. return $FF;
  13414. case $r:
  13415. return $CR;
  13416. case $t:
  13417. return $TAB;
  13418. case $v:
  13419. return $VTAB;
  13420. default:
  13421. return code;
  13422. }
  13423. }
  13424. function parseIntAutoRadix(text) {
  13425. var result = parseInt(text);
  13426. if (isNaN(result)) {
  13427. throw new Error('Invalid integer literal when parsing ' + text);
  13428. }
  13429. return result;
  13430. }
  13431. /**
  13432. * @license
  13433. * Copyright Google Inc. All Rights Reserved.
  13434. *
  13435. * Use of this source code is governed by an MIT-style license that can be
  13436. * found in the LICENSE file at https://angular.io/license
  13437. */
  13438. var SplitInterpolation = /** @class */ (function () {
  13439. function SplitInterpolation(strings, expressions, offsets) {
  13440. this.strings = strings;
  13441. this.expressions = expressions;
  13442. this.offsets = offsets;
  13443. }
  13444. return SplitInterpolation;
  13445. }());
  13446. var TemplateBindingParseResult = /** @class */ (function () {
  13447. function TemplateBindingParseResult(templateBindings, warnings, errors) {
  13448. this.templateBindings = templateBindings;
  13449. this.warnings = warnings;
  13450. this.errors = errors;
  13451. }
  13452. return TemplateBindingParseResult;
  13453. }());
  13454. function _createInterpolateRegExp(config) {
  13455. var pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
  13456. return new RegExp(pattern, 'g');
  13457. }
  13458. var Parser$1 = /** @class */ (function () {
  13459. function Parser(_lexer) {
  13460. this._lexer = _lexer;
  13461. this.errors = [];
  13462. }
  13463. Parser.prototype.parseAction = function (input, location, interpolationConfig) {
  13464. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13465. this._checkNoInterpolation(input, location, interpolationConfig);
  13466. var sourceToLex = this._stripComments(input);
  13467. var tokens = this._lexer.tokenize(this._stripComments(input));
  13468. var ast = new _ParseAST(input, location, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
  13469. .parseChain();
  13470. return new ASTWithSource(ast, input, location, this.errors);
  13471. };
  13472. Parser.prototype.parseBinding = function (input, location, interpolationConfig) {
  13473. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13474. var ast = this._parseBindingAst(input, location, interpolationConfig);
  13475. return new ASTWithSource(ast, input, location, this.errors);
  13476. };
  13477. Parser.prototype.parseSimpleBinding = function (input, location, interpolationConfig) {
  13478. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13479. var ast = this._parseBindingAst(input, location, interpolationConfig);
  13480. var errors = SimpleExpressionChecker.check(ast);
  13481. if (errors.length > 0) {
  13482. this._reportError("Host binding expression cannot contain " + errors.join(' '), input, location);
  13483. }
  13484. return new ASTWithSource(ast, input, location, this.errors);
  13485. };
  13486. Parser.prototype._reportError = function (message, input, errLocation, ctxLocation) {
  13487. this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
  13488. };
  13489. Parser.prototype._parseBindingAst = function (input, location, interpolationConfig) {
  13490. // Quotes expressions use 3rd-party expression language. We don't want to use
  13491. // our lexer or parser for that, so we check for that ahead of time.
  13492. var quote = this._parseQuote(input, location);
  13493. if (quote != null) {
  13494. return quote;
  13495. }
  13496. this._checkNoInterpolation(input, location, interpolationConfig);
  13497. var sourceToLex = this._stripComments(input);
  13498. var tokens = this._lexer.tokenize(sourceToLex);
  13499. return new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
  13500. .parseChain();
  13501. };
  13502. Parser.prototype._parseQuote = function (input, location) {
  13503. if (input == null)
  13504. return null;
  13505. var prefixSeparatorIndex = input.indexOf(':');
  13506. if (prefixSeparatorIndex == -1)
  13507. return null;
  13508. var prefix = input.substring(0, prefixSeparatorIndex).trim();
  13509. if (!isIdentifier(prefix))
  13510. return null;
  13511. var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
  13512. return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
  13513. };
  13514. Parser.prototype.parseTemplateBindings = function (tplKey, tplValue, location) {
  13515. var tokens = this._lexer.tokenize(tplValue);
  13516. return new _ParseAST(tplValue, location, tokens, tplValue.length, false, this.errors, 0)
  13517. .parseTemplateBindings(tplKey);
  13518. };
  13519. Parser.prototype.parseInterpolation = function (input, location, interpolationConfig) {
  13520. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13521. var split = this.splitInterpolation(input, location, interpolationConfig);
  13522. if (split == null)
  13523. return null;
  13524. var expressions = [];
  13525. for (var i = 0; i < split.expressions.length; ++i) {
  13526. var expressionText = split.expressions[i];
  13527. var sourceToLex = this._stripComments(expressionText);
  13528. var tokens = this._lexer.tokenize(sourceToLex);
  13529. var ast = new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, split.offsets[i] + (expressionText.length - sourceToLex.length))
  13530. .parseChain();
  13531. expressions.push(ast);
  13532. }
  13533. return new ASTWithSource(new Interpolation(new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions), input, location, this.errors);
  13534. };
  13535. Parser.prototype.splitInterpolation = function (input, location, interpolationConfig) {
  13536. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13537. var regexp = _createInterpolateRegExp(interpolationConfig);
  13538. var parts = input.split(regexp);
  13539. if (parts.length <= 1) {
  13540. return null;
  13541. }
  13542. var strings = [];
  13543. var expressions = [];
  13544. var offsets = [];
  13545. var offset = 0;
  13546. for (var i = 0; i < parts.length; i++) {
  13547. var part = parts[i];
  13548. if (i % 2 === 0) {
  13549. // fixed string
  13550. strings.push(part);
  13551. offset += part.length;
  13552. }
  13553. else if (part.trim().length > 0) {
  13554. offset += interpolationConfig.start.length;
  13555. expressions.push(part);
  13556. offsets.push(offset);
  13557. offset += part.length + interpolationConfig.end.length;
  13558. }
  13559. else {
  13560. this._reportError('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i, interpolationConfig) + " in", location);
  13561. expressions.push('$implict');
  13562. offsets.push(offset);
  13563. }
  13564. }
  13565. return new SplitInterpolation(strings, expressions, offsets);
  13566. };
  13567. Parser.prototype.wrapLiteralPrimitive = function (input, location) {
  13568. return new ASTWithSource(new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input, location, this.errors);
  13569. };
  13570. Parser.prototype._stripComments = function (input) {
  13571. var i = this._commentStart(input);
  13572. return i != null ? input.substring(0, i).trim() : input;
  13573. };
  13574. Parser.prototype._commentStart = function (input) {
  13575. var outerQuote = null;
  13576. for (var i = 0; i < input.length - 1; i++) {
  13577. var char = input.charCodeAt(i);
  13578. var nextChar = input.charCodeAt(i + 1);
  13579. if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
  13580. return i;
  13581. if (outerQuote === char) {
  13582. outerQuote = null;
  13583. }
  13584. else if (outerQuote == null && isQuote(char)) {
  13585. outerQuote = char;
  13586. }
  13587. }
  13588. return null;
  13589. };
  13590. Parser.prototype._checkNoInterpolation = function (input, location, interpolationConfig) {
  13591. var regexp = _createInterpolateRegExp(interpolationConfig);
  13592. var parts = input.split(regexp);
  13593. if (parts.length > 1) {
  13594. this._reportError("Got interpolation (" + interpolationConfig.start + interpolationConfig.end + ") where expression was expected", input, "at column " + this._findInterpolationErrorColumn(parts, 1, interpolationConfig) + " in", location);
  13595. }
  13596. };
  13597. Parser.prototype._findInterpolationErrorColumn = function (parts, partInErrIdx, interpolationConfig) {
  13598. var errLocation = '';
  13599. for (var j = 0; j < partInErrIdx; j++) {
  13600. errLocation += j % 2 === 0 ?
  13601. parts[j] :
  13602. "" + interpolationConfig.start + parts[j] + interpolationConfig.end;
  13603. }
  13604. return errLocation.length;
  13605. };
  13606. return Parser;
  13607. }());
  13608. var _ParseAST = /** @class */ (function () {
  13609. function _ParseAST(input, location, tokens, inputLength, parseAction, errors, offset) {
  13610. this.input = input;
  13611. this.location = location;
  13612. this.tokens = tokens;
  13613. this.inputLength = inputLength;
  13614. this.parseAction = parseAction;
  13615. this.errors = errors;
  13616. this.offset = offset;
  13617. this.rparensExpected = 0;
  13618. this.rbracketsExpected = 0;
  13619. this.rbracesExpected = 0;
  13620. this.index = 0;
  13621. }
  13622. _ParseAST.prototype.peek = function (offset) {
  13623. var i = this.index + offset;
  13624. return i < this.tokens.length ? this.tokens[i] : EOF;
  13625. };
  13626. Object.defineProperty(_ParseAST.prototype, "next", {
  13627. get: function () { return this.peek(0); },
  13628. enumerable: true,
  13629. configurable: true
  13630. });
  13631. Object.defineProperty(_ParseAST.prototype, "inputIndex", {
  13632. get: function () {
  13633. return (this.index < this.tokens.length) ? this.next.index + this.offset :
  13634. this.inputLength + this.offset;
  13635. },
  13636. enumerable: true,
  13637. configurable: true
  13638. });
  13639. _ParseAST.prototype.span = function (start) { return new ParseSpan(start, this.inputIndex); };
  13640. _ParseAST.prototype.advance = function () { this.index++; };
  13641. _ParseAST.prototype.optionalCharacter = function (code) {
  13642. if (this.next.isCharacter(code)) {
  13643. this.advance();
  13644. return true;
  13645. }
  13646. else {
  13647. return false;
  13648. }
  13649. };
  13650. _ParseAST.prototype.peekKeywordLet = function () { return this.next.isKeywordLet(); };
  13651. _ParseAST.prototype.peekKeywordAs = function () { return this.next.isKeywordAs(); };
  13652. _ParseAST.prototype.expectCharacter = function (code) {
  13653. if (this.optionalCharacter(code))
  13654. return;
  13655. this.error("Missing expected " + String.fromCharCode(code));
  13656. };
  13657. _ParseAST.prototype.optionalOperator = function (op) {
  13658. if (this.next.isOperator(op)) {
  13659. this.advance();
  13660. return true;
  13661. }
  13662. else {
  13663. return false;
  13664. }
  13665. };
  13666. _ParseAST.prototype.expectOperator = function (operator) {
  13667. if (this.optionalOperator(operator))
  13668. return;
  13669. this.error("Missing expected operator " + operator);
  13670. };
  13671. _ParseAST.prototype.expectIdentifierOrKeyword = function () {
  13672. var n = this.next;
  13673. if (!n.isIdentifier() && !n.isKeyword()) {
  13674. this.error("Unexpected token " + n + ", expected identifier or keyword");
  13675. return '';
  13676. }
  13677. this.advance();
  13678. return n.toString();
  13679. };
  13680. _ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
  13681. var n = this.next;
  13682. if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
  13683. this.error("Unexpected token " + n + ", expected identifier, keyword, or string");
  13684. return '';
  13685. }
  13686. this.advance();
  13687. return n.toString();
  13688. };
  13689. _ParseAST.prototype.parseChain = function () {
  13690. var exprs = [];
  13691. var start = this.inputIndex;
  13692. while (this.index < this.tokens.length) {
  13693. var expr = this.parsePipe();
  13694. exprs.push(expr);
  13695. if (this.optionalCharacter($SEMICOLON)) {
  13696. if (!this.parseAction) {
  13697. this.error('Binding expression cannot contain chained expression');
  13698. }
  13699. while (this.optionalCharacter($SEMICOLON)) {
  13700. } // read all semicolons
  13701. }
  13702. else if (this.index < this.tokens.length) {
  13703. this.error("Unexpected token '" + this.next + "'");
  13704. }
  13705. }
  13706. if (exprs.length == 0)
  13707. return new EmptyExpr(this.span(start));
  13708. if (exprs.length == 1)
  13709. return exprs[0];
  13710. return new Chain(this.span(start), exprs);
  13711. };
  13712. _ParseAST.prototype.parsePipe = function () {
  13713. var result = this.parseExpression();
  13714. if (this.optionalOperator('|')) {
  13715. if (this.parseAction) {
  13716. this.error('Cannot have a pipe in an action expression');
  13717. }
  13718. do {
  13719. var name_1 = this.expectIdentifierOrKeyword();
  13720. var args = [];
  13721. while (this.optionalCharacter($COLON)) {
  13722. args.push(this.parseExpression());
  13723. }
  13724. result = new BindingPipe(this.span(result.span.start), result, name_1, args);
  13725. } while (this.optionalOperator('|'));
  13726. }
  13727. return result;
  13728. };
  13729. _ParseAST.prototype.parseExpression = function () { return this.parseConditional(); };
  13730. _ParseAST.prototype.parseConditional = function () {
  13731. var start = this.inputIndex;
  13732. var result = this.parseLogicalOr();
  13733. if (this.optionalOperator('?')) {
  13734. var yes = this.parsePipe();
  13735. var no = void 0;
  13736. if (!this.optionalCharacter($COLON)) {
  13737. var end = this.inputIndex;
  13738. var expression = this.input.substring(start, end);
  13739. this.error("Conditional expression " + expression + " requires all 3 expressions");
  13740. no = new EmptyExpr(this.span(start));
  13741. }
  13742. else {
  13743. no = this.parsePipe();
  13744. }
  13745. return new Conditional(this.span(start), result, yes, no);
  13746. }
  13747. else {
  13748. return result;
  13749. }
  13750. };
  13751. _ParseAST.prototype.parseLogicalOr = function () {
  13752. // '||'
  13753. var result = this.parseLogicalAnd();
  13754. while (this.optionalOperator('||')) {
  13755. var right = this.parseLogicalAnd();
  13756. result = new Binary(this.span(result.span.start), '||', result, right);
  13757. }
  13758. return result;
  13759. };
  13760. _ParseAST.prototype.parseLogicalAnd = function () {
  13761. // '&&'
  13762. var result = this.parseEquality();
  13763. while (this.optionalOperator('&&')) {
  13764. var right = this.parseEquality();
  13765. result = new Binary(this.span(result.span.start), '&&', result, right);
  13766. }
  13767. return result;
  13768. };
  13769. _ParseAST.prototype.parseEquality = function () {
  13770. // '==','!=','===','!=='
  13771. var result = this.parseRelational();
  13772. while (this.next.type == TokenType$1.Operator) {
  13773. var operator = this.next.strValue;
  13774. switch (operator) {
  13775. case '==':
  13776. case '===':
  13777. case '!=':
  13778. case '!==':
  13779. this.advance();
  13780. var right = this.parseRelational();
  13781. result = new Binary(this.span(result.span.start), operator, result, right);
  13782. continue;
  13783. }
  13784. break;
  13785. }
  13786. return result;
  13787. };
  13788. _ParseAST.prototype.parseRelational = function () {
  13789. // '<', '>', '<=', '>='
  13790. var result = this.parseAdditive();
  13791. while (this.next.type == TokenType$1.Operator) {
  13792. var operator = this.next.strValue;
  13793. switch (operator) {
  13794. case '<':
  13795. case '>':
  13796. case '<=':
  13797. case '>=':
  13798. this.advance();
  13799. var right = this.parseAdditive();
  13800. result = new Binary(this.span(result.span.start), operator, result, right);
  13801. continue;
  13802. }
  13803. break;
  13804. }
  13805. return result;
  13806. };
  13807. _ParseAST.prototype.parseAdditive = function () {
  13808. // '+', '-'
  13809. var result = this.parseMultiplicative();
  13810. while (this.next.type == TokenType$1.Operator) {
  13811. var operator = this.next.strValue;
  13812. switch (operator) {
  13813. case '+':
  13814. case '-':
  13815. this.advance();
  13816. var right = this.parseMultiplicative();
  13817. result = new Binary(this.span(result.span.start), operator, result, right);
  13818. continue;
  13819. }
  13820. break;
  13821. }
  13822. return result;
  13823. };
  13824. _ParseAST.prototype.parseMultiplicative = function () {
  13825. // '*', '%', '/'
  13826. var result = this.parsePrefix();
  13827. while (this.next.type == TokenType$1.Operator) {
  13828. var operator = this.next.strValue;
  13829. switch (operator) {
  13830. case '*':
  13831. case '%':
  13832. case '/':
  13833. this.advance();
  13834. var right = this.parsePrefix();
  13835. result = new Binary(this.span(result.span.start), operator, result, right);
  13836. continue;
  13837. }
  13838. break;
  13839. }
  13840. return result;
  13841. };
  13842. _ParseAST.prototype.parsePrefix = function () {
  13843. if (this.next.type == TokenType$1.Operator) {
  13844. var start = this.inputIndex;
  13845. var operator = this.next.strValue;
  13846. var result = void 0;
  13847. switch (operator) {
  13848. case '+':
  13849. this.advance();
  13850. result = this.parsePrefix();
  13851. return new Binary(this.span(start), '-', result, new LiteralPrimitive(new ParseSpan(start, start), 0));
  13852. case '-':
  13853. this.advance();
  13854. result = this.parsePrefix();
  13855. return new Binary(this.span(start), operator, new LiteralPrimitive(new ParseSpan(start, start), 0), result);
  13856. case '!':
  13857. this.advance();
  13858. result = this.parsePrefix();
  13859. return new PrefixNot(this.span(start), result);
  13860. }
  13861. }
  13862. return this.parseCallChain();
  13863. };
  13864. _ParseAST.prototype.parseCallChain = function () {
  13865. var result = this.parsePrimary();
  13866. while (true) {
  13867. if (this.optionalCharacter($PERIOD)) {
  13868. result = this.parseAccessMemberOrMethodCall(result, false);
  13869. }
  13870. else if (this.optionalOperator('?.')) {
  13871. result = this.parseAccessMemberOrMethodCall(result, true);
  13872. }
  13873. else if (this.optionalCharacter($LBRACKET)) {
  13874. this.rbracketsExpected++;
  13875. var key = this.parsePipe();
  13876. this.rbracketsExpected--;
  13877. this.expectCharacter($RBRACKET);
  13878. if (this.optionalOperator('=')) {
  13879. var value = this.parseConditional();
  13880. result = new KeyedWrite(this.span(result.span.start), result, key, value);
  13881. }
  13882. else {
  13883. result = new KeyedRead(this.span(result.span.start), result, key);
  13884. }
  13885. }
  13886. else if (this.optionalCharacter($LPAREN)) {
  13887. this.rparensExpected++;
  13888. var args = this.parseCallArguments();
  13889. this.rparensExpected--;
  13890. this.expectCharacter($RPAREN);
  13891. result = new FunctionCall(this.span(result.span.start), result, args);
  13892. }
  13893. else if (this.optionalOperator('!')) {
  13894. result = new NonNullAssert(this.span(result.span.start), result);
  13895. }
  13896. else {
  13897. return result;
  13898. }
  13899. }
  13900. };
  13901. _ParseAST.prototype.parsePrimary = function () {
  13902. var start = this.inputIndex;
  13903. if (this.optionalCharacter($LPAREN)) {
  13904. this.rparensExpected++;
  13905. var result = this.parsePipe();
  13906. this.rparensExpected--;
  13907. this.expectCharacter($RPAREN);
  13908. return result;
  13909. }
  13910. else if (this.next.isKeywordNull()) {
  13911. this.advance();
  13912. return new LiteralPrimitive(this.span(start), null);
  13913. }
  13914. else if (this.next.isKeywordUndefined()) {
  13915. this.advance();
  13916. return new LiteralPrimitive(this.span(start), void 0);
  13917. }
  13918. else if (this.next.isKeywordTrue()) {
  13919. this.advance();
  13920. return new LiteralPrimitive(this.span(start), true);
  13921. }
  13922. else if (this.next.isKeywordFalse()) {
  13923. this.advance();
  13924. return new LiteralPrimitive(this.span(start), false);
  13925. }
  13926. else if (this.next.isKeywordThis()) {
  13927. this.advance();
  13928. return new ImplicitReceiver(this.span(start));
  13929. }
  13930. else if (this.optionalCharacter($LBRACKET)) {
  13931. this.rbracketsExpected++;
  13932. var elements = this.parseExpressionList($RBRACKET);
  13933. this.rbracketsExpected--;
  13934. this.expectCharacter($RBRACKET);
  13935. return new LiteralArray(this.span(start), elements);
  13936. }
  13937. else if (this.next.isCharacter($LBRACE)) {
  13938. return this.parseLiteralMap();
  13939. }
  13940. else if (this.next.isIdentifier()) {
  13941. return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start)), false);
  13942. }
  13943. else if (this.next.isNumber()) {
  13944. var value = this.next.toNumber();
  13945. this.advance();
  13946. return new LiteralPrimitive(this.span(start), value);
  13947. }
  13948. else if (this.next.isString()) {
  13949. var literalValue = this.next.toString();
  13950. this.advance();
  13951. return new LiteralPrimitive(this.span(start), literalValue);
  13952. }
  13953. else if (this.index >= this.tokens.length) {
  13954. this.error("Unexpected end of expression: " + this.input);
  13955. return new EmptyExpr(this.span(start));
  13956. }
  13957. else {
  13958. this.error("Unexpected token " + this.next);
  13959. return new EmptyExpr(this.span(start));
  13960. }
  13961. };
  13962. _ParseAST.prototype.parseExpressionList = function (terminator) {
  13963. var result = [];
  13964. if (!this.next.isCharacter(terminator)) {
  13965. do {
  13966. result.push(this.parsePipe());
  13967. } while (this.optionalCharacter($COMMA));
  13968. }
  13969. return result;
  13970. };
  13971. _ParseAST.prototype.parseLiteralMap = function () {
  13972. var keys = [];
  13973. var values = [];
  13974. var start = this.inputIndex;
  13975. this.expectCharacter($LBRACE);
  13976. if (!this.optionalCharacter($RBRACE)) {
  13977. this.rbracesExpected++;
  13978. do {
  13979. var quoted = this.next.isString();
  13980. var key = this.expectIdentifierOrKeywordOrString();
  13981. keys.push({ key: key, quoted: quoted });
  13982. this.expectCharacter($COLON);
  13983. values.push(this.parsePipe());
  13984. } while (this.optionalCharacter($COMMA));
  13985. this.rbracesExpected--;
  13986. this.expectCharacter($RBRACE);
  13987. }
  13988. return new LiteralMap(this.span(start), keys, values);
  13989. };
  13990. _ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, isSafe) {
  13991. if (isSafe === void 0) { isSafe = false; }
  13992. var start = receiver.span.start;
  13993. var id = this.expectIdentifierOrKeyword();
  13994. if (this.optionalCharacter($LPAREN)) {
  13995. this.rparensExpected++;
  13996. var args = this.parseCallArguments();
  13997. this.expectCharacter($RPAREN);
  13998. this.rparensExpected--;
  13999. var span = this.span(start);
  14000. return isSafe ? new SafeMethodCall(span, receiver, id, args) :
  14001. new MethodCall(span, receiver, id, args);
  14002. }
  14003. else {
  14004. if (isSafe) {
  14005. if (this.optionalOperator('=')) {
  14006. this.error('The \'?.\' operator cannot be used in the assignment');
  14007. return new EmptyExpr(this.span(start));
  14008. }
  14009. else {
  14010. return new SafePropertyRead(this.span(start), receiver, id);
  14011. }
  14012. }
  14013. else {
  14014. if (this.optionalOperator('=')) {
  14015. if (!this.parseAction) {
  14016. this.error('Bindings cannot contain assignments');
  14017. return new EmptyExpr(this.span(start));
  14018. }
  14019. var value = this.parseConditional();
  14020. return new PropertyWrite(this.span(start), receiver, id, value);
  14021. }
  14022. else {
  14023. return new PropertyRead(this.span(start), receiver, id);
  14024. }
  14025. }
  14026. }
  14027. };
  14028. _ParseAST.prototype.parseCallArguments = function () {
  14029. if (this.next.isCharacter($RPAREN))
  14030. return [];
  14031. var positionals = [];
  14032. do {
  14033. positionals.push(this.parsePipe());
  14034. } while (this.optionalCharacter($COMMA));
  14035. return positionals;
  14036. };
  14037. /**
  14038. * An identifier, a keyword, a string with an optional `-` in between.
  14039. */
  14040. _ParseAST.prototype.expectTemplateBindingKey = function () {
  14041. var result = '';
  14042. var operatorFound = false;
  14043. do {
  14044. result += this.expectIdentifierOrKeywordOrString();
  14045. operatorFound = this.optionalOperator('-');
  14046. if (operatorFound) {
  14047. result += '-';
  14048. }
  14049. } while (operatorFound);
  14050. return result.toString();
  14051. };
  14052. // Parses the AST for `<some-tag *tplKey=AST>`
  14053. _ParseAST.prototype.parseTemplateBindings = function (tplKey) {
  14054. var firstBinding = true;
  14055. var bindings = [];
  14056. var warnings = [];
  14057. do {
  14058. var start = this.inputIndex;
  14059. var rawKey = void 0;
  14060. var key = void 0;
  14061. var isVar = false;
  14062. if (firstBinding) {
  14063. rawKey = key = tplKey;
  14064. firstBinding = false;
  14065. }
  14066. else {
  14067. isVar = this.peekKeywordLet();
  14068. if (isVar)
  14069. this.advance();
  14070. rawKey = this.expectTemplateBindingKey();
  14071. key = isVar ? rawKey : tplKey + rawKey[0].toUpperCase() + rawKey.substring(1);
  14072. this.optionalCharacter($COLON);
  14073. }
  14074. var name_2 = null;
  14075. var expression = null;
  14076. if (isVar) {
  14077. if (this.optionalOperator('=')) {
  14078. name_2 = this.expectTemplateBindingKey();
  14079. }
  14080. else {
  14081. name_2 = '\$implicit';
  14082. }
  14083. }
  14084. else if (this.peekKeywordAs()) {
  14085. this.advance(); // consume `as`
  14086. name_2 = rawKey;
  14087. key = this.expectTemplateBindingKey(); // read local var name
  14088. isVar = true;
  14089. }
  14090. else if (this.next !== EOF && !this.peekKeywordLet()) {
  14091. var start_1 = this.inputIndex;
  14092. var ast = this.parsePipe();
  14093. var source = this.input.substring(start_1 - this.offset, this.inputIndex - this.offset);
  14094. expression = new ASTWithSource(ast, source, this.location, this.errors);
  14095. }
  14096. bindings.push(new TemplateBinding(this.span(start), key, isVar, name_2, expression));
  14097. if (this.peekKeywordAs() && !isVar) {
  14098. var letStart = this.inputIndex;
  14099. this.advance(); // consume `as`
  14100. var letName = this.expectTemplateBindingKey(); // read local var name
  14101. bindings.push(new TemplateBinding(this.span(letStart), letName, true, key, null));
  14102. }
  14103. if (!this.optionalCharacter($SEMICOLON)) {
  14104. this.optionalCharacter($COMMA);
  14105. }
  14106. } while (this.index < this.tokens.length);
  14107. return new TemplateBindingParseResult(bindings, warnings, this.errors);
  14108. };
  14109. _ParseAST.prototype.error = function (message, index) {
  14110. if (index === void 0) { index = null; }
  14111. this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
  14112. this.skip();
  14113. };
  14114. _ParseAST.prototype.locationText = function (index) {
  14115. if (index === void 0) { index = null; }
  14116. if (index == null)
  14117. index = this.index;
  14118. return (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
  14119. "at the end of the expression";
  14120. };
  14121. // Error recovery should skip tokens until it encounters a recovery point. skip() treats
  14122. // the end of input and a ';' as unconditionally a recovery point. It also treats ')',
  14123. // '}' and ']' as conditional recovery points if one of calling productions is expecting
  14124. // one of these symbols. This allows skip() to recover from errors such as '(a.) + 1' allowing
  14125. // more of the AST to be retained (it doesn't skip any tokens as the ')' is retained because
  14126. // of the '(' begins an '(' <expr> ')' production). The recovery points of grouping symbols
  14127. // must be conditional as they must be skipped if none of the calling productions are not
  14128. // expecting the closing token else we will never make progress in the case of an
  14129. // extraneous group closing symbol (such as a stray ')'). This is not the case for ';' because
  14130. // parseChain() is always the root production and it expects a ';'.
  14131. // If a production expects one of these token it increments the corresponding nesting count,
  14132. // and then decrements it just prior to checking if the token is in the input.
  14133. _ParseAST.prototype.skip = function () {
  14134. var n = this.next;
  14135. while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
  14136. (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
  14137. (this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
  14138. (this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET))) {
  14139. if (this.next.isError()) {
  14140. this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
  14141. }
  14142. this.advance();
  14143. n = this.next;
  14144. }
  14145. };
  14146. return _ParseAST;
  14147. }());
  14148. var SimpleExpressionChecker = /** @class */ (function () {
  14149. function SimpleExpressionChecker() {
  14150. this.errors = [];
  14151. }
  14152. SimpleExpressionChecker.check = function (ast) {
  14153. var s = new SimpleExpressionChecker();
  14154. ast.visit(s);
  14155. return s.errors;
  14156. };
  14157. SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast, context) { };
  14158. SimpleExpressionChecker.prototype.visitInterpolation = function (ast, context) { };
  14159. SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast, context) { };
  14160. SimpleExpressionChecker.prototype.visitPropertyRead = function (ast, context) { };
  14161. SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast, context) { };
  14162. SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast, context) { };
  14163. SimpleExpressionChecker.prototype.visitMethodCall = function (ast, context) { };
  14164. SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast, context) { };
  14165. SimpleExpressionChecker.prototype.visitFunctionCall = function (ast, context) { };
  14166. SimpleExpressionChecker.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions); };
  14167. SimpleExpressionChecker.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values); };
  14168. SimpleExpressionChecker.prototype.visitBinary = function (ast, context) { };
  14169. SimpleExpressionChecker.prototype.visitPrefixNot = function (ast, context) { };
  14170. SimpleExpressionChecker.prototype.visitNonNullAssert = function (ast, context) { };
  14171. SimpleExpressionChecker.prototype.visitConditional = function (ast, context) { };
  14172. SimpleExpressionChecker.prototype.visitPipe = function (ast, context) { this.errors.push('pipes'); };
  14173. SimpleExpressionChecker.prototype.visitKeyedRead = function (ast, context) { };
  14174. SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast, context) { };
  14175. SimpleExpressionChecker.prototype.visitAll = function (asts) {
  14176. var _this = this;
  14177. return asts.map(function (node) { return node.visit(_this); });
  14178. };
  14179. SimpleExpressionChecker.prototype.visitChain = function (ast, context) { };
  14180. SimpleExpressionChecker.prototype.visitQuote = function (ast, context) { };
  14181. return SimpleExpressionChecker;
  14182. }());
  14183. /**
  14184. * @license
  14185. * Copyright Google Inc. All Rights Reserved.
  14186. *
  14187. * Use of this source code is governed by an MIT-style license that can be
  14188. * found in the LICENSE file at https://angular.io/license
  14189. */
  14190. // =================================================================================================
  14191. // =================================================================================================
  14192. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  14193. // =================================================================================================
  14194. // =================================================================================================
  14195. //
  14196. // DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
  14197. // Reach out to mprobst for details.
  14198. //
  14199. // =================================================================================================
  14200. /** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
  14201. var _SECURITY_SCHEMA;
  14202. function SECURITY_SCHEMA() {
  14203. if (!_SECURITY_SCHEMA) {
  14204. _SECURITY_SCHEMA = {};
  14205. // Case is insignificant below, all element and attribute names are lower-cased for lookup.
  14206. registerContext(SecurityContext.HTML, [
  14207. 'iframe|srcdoc',
  14208. '*|innerHTML',
  14209. '*|outerHTML',
  14210. ]);
  14211. registerContext(SecurityContext.STYLE, ['*|style']);
  14212. // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
  14213. registerContext(SecurityContext.URL, [
  14214. '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
  14215. 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
  14216. 'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
  14217. 'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
  14218. ]);
  14219. registerContext(SecurityContext.RESOURCE_URL, [
  14220. 'applet|code',
  14221. 'applet|codebase',
  14222. 'base|href',
  14223. 'embed|src',
  14224. 'frame|src',
  14225. 'head|profile',
  14226. 'html|manifest',
  14227. 'iframe|src',
  14228. 'link|href',
  14229. 'media|src',
  14230. 'object|codebase',
  14231. 'object|data',
  14232. 'script|src',
  14233. ]);
  14234. }
  14235. return _SECURITY_SCHEMA;
  14236. }
  14237. function registerContext(ctx, specs) {
  14238. var e_1, _a;
  14239. try {
  14240. for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
  14241. var spec = specs_1_1.value;
  14242. _SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
  14243. }
  14244. }
  14245. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  14246. finally {
  14247. try {
  14248. if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
  14249. }
  14250. finally { if (e_1) throw e_1.error; }
  14251. }
  14252. }
  14253. /**
  14254. * @license
  14255. * Copyright Google Inc. All Rights Reserved.
  14256. *
  14257. * Use of this source code is governed by an MIT-style license that can be
  14258. * found in the LICENSE file at https://angular.io/license
  14259. */
  14260. var ElementSchemaRegistry = /** @class */ (function () {
  14261. function ElementSchemaRegistry() {
  14262. }
  14263. return ElementSchemaRegistry;
  14264. }());
  14265. /**
  14266. * @license
  14267. * Copyright Google Inc. All Rights Reserved.
  14268. *
  14269. * Use of this source code is governed by an MIT-style license that can be
  14270. * found in the LICENSE file at https://angular.io/license
  14271. */
  14272. var BOOLEAN = 'boolean';
  14273. var NUMBER = 'number';
  14274. var STRING = 'string';
  14275. var OBJECT = 'object';
  14276. /**
  14277. * This array represents the DOM schema. It encodes inheritance, properties, and events.
  14278. *
  14279. * ## Overview
  14280. *
  14281. * Each line represents one kind of element. The `element_inheritance` and properties are joined
  14282. * using `element_inheritance|properties` syntax.
  14283. *
  14284. * ## Element Inheritance
  14285. *
  14286. * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
  14287. * Here the individual elements are separated by `,` (commas). Every element in the list
  14288. * has identical properties.
  14289. *
  14290. * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
  14291. * specified then `""` (blank) element is assumed.
  14292. *
  14293. * NOTE: The blank element inherits from root `[Element]` element, the super element of all
  14294. * elements.
  14295. *
  14296. * NOTE an element prefix such as `:svg:` has no special meaning to the schema.
  14297. *
  14298. * ## Properties
  14299. *
  14300. * Each element has a set of properties separated by `,` (commas). Each property can be prefixed
  14301. * by a special character designating its type:
  14302. *
  14303. * - (no prefix): property is a string.
  14304. * - `*`: property represents an event.
  14305. * - `!`: property is a boolean.
  14306. * - `#`: property is a number.
  14307. * - `%`: property is an object.
  14308. *
  14309. * ## Query
  14310. *
  14311. * The class creates an internal squas representation which allows to easily answer the query of
  14312. * if a given property exist on a given element.
  14313. *
  14314. * NOTE: We don't yet support querying for types or events.
  14315. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
  14316. * see dom_element_schema_registry_spec.ts
  14317. */
  14318. // =================================================================================================
  14319. // =================================================================================================
  14320. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  14321. // =================================================================================================
  14322. // =================================================================================================
  14323. //
  14324. // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
  14325. //
  14326. // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
  14327. // dom_security_schema.ts. Reach out to mprobst & rjamet for details.
  14328. //
  14329. // =================================================================================================
  14330. var SCHEMA = [
  14331. '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
  14332. /* added manually to avoid breaking changes */
  14333. ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
  14334. '[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',
  14335. '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',
  14336. 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
  14337. ':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',
  14338. ':svg:graphics^:svg:|',
  14339. ':svg:animation^:svg:|*begin,*end,*repeat',
  14340. ':svg:geometry^:svg:|',
  14341. ':svg:componentTransferFunction^:svg:|',
  14342. ':svg:gradient^:svg:|',
  14343. ':svg:textContent^:svg:graphics|',
  14344. ':svg:textPositioning^:svg:textContent|',
  14345. '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',
  14346. 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
  14347. 'audio^media|',
  14348. 'br^[HTMLElement]|clear',
  14349. 'base^[HTMLElement]|href,target',
  14350. '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',
  14351. 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
  14352. 'canvas^[HTMLElement]|#height,#width',
  14353. 'content^[HTMLElement]|select',
  14354. 'dl^[HTMLElement]|!compact',
  14355. 'datalist^[HTMLElement]|',
  14356. 'details^[HTMLElement]|!open',
  14357. 'dialog^[HTMLElement]|!open,returnValue',
  14358. 'dir^[HTMLElement]|!compact',
  14359. 'div^[HTMLElement]|align',
  14360. 'embed^[HTMLElement]|align,height,name,src,type,width',
  14361. 'fieldset^[HTMLElement]|!disabled,name',
  14362. 'font^[HTMLElement]|color,face,size',
  14363. 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
  14364. 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
  14365. 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
  14366. 'hr^[HTMLElement]|align,color,!noShade,size,width',
  14367. 'head^[HTMLElement]|',
  14368. 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
  14369. 'html^[HTMLElement]|version',
  14370. 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
  14371. 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
  14372. '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',
  14373. 'li^[HTMLElement]|type,#value',
  14374. 'label^[HTMLElement]|htmlFor',
  14375. 'legend^[HTMLElement]|align',
  14376. 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
  14377. 'map^[HTMLElement]|name',
  14378. 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
  14379. 'menu^[HTMLElement]|!compact',
  14380. 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
  14381. 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
  14382. 'ins,del^[HTMLElement]|cite,dateTime',
  14383. 'ol^[HTMLElement]|!compact,!reversed,#start,type',
  14384. 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
  14385. 'optgroup^[HTMLElement]|!disabled,label',
  14386. 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
  14387. 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
  14388. 'p^[HTMLElement]|align',
  14389. 'param^[HTMLElement]|name,type,value,valueType',
  14390. 'picture^[HTMLElement]|',
  14391. 'pre^[HTMLElement]|#width',
  14392. 'progress^[HTMLElement]|#max,#value',
  14393. 'q,blockquote,cite^[HTMLElement]|',
  14394. 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
  14395. 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
  14396. 'shadow^[HTMLElement]|',
  14397. 'slot^[HTMLElement]|name',
  14398. 'source^[HTMLElement]|media,sizes,src,srcset,type',
  14399. 'span^[HTMLElement]|',
  14400. 'style^[HTMLElement]|!disabled,media,type',
  14401. 'caption^[HTMLElement]|align',
  14402. 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
  14403. 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
  14404. 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
  14405. 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
  14406. 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
  14407. 'template^[HTMLElement]|',
  14408. 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
  14409. 'title^[HTMLElement]|text',
  14410. 'track^[HTMLElement]|!default,kind,label,src,srclang',
  14411. 'ul^[HTMLElement]|!compact,type',
  14412. 'unknown^[HTMLElement]|',
  14413. 'video^media|#height,poster,#width',
  14414. ':svg:a^:svg:graphics|',
  14415. ':svg:animate^:svg:animation|',
  14416. ':svg:animateMotion^:svg:animation|',
  14417. ':svg:animateTransform^:svg:animation|',
  14418. ':svg:circle^:svg:geometry|',
  14419. ':svg:clipPath^:svg:graphics|',
  14420. ':svg:defs^:svg:graphics|',
  14421. ':svg:desc^:svg:|',
  14422. ':svg:discard^:svg:|',
  14423. ':svg:ellipse^:svg:geometry|',
  14424. ':svg:feBlend^:svg:|',
  14425. ':svg:feColorMatrix^:svg:|',
  14426. ':svg:feComponentTransfer^:svg:|',
  14427. ':svg:feComposite^:svg:|',
  14428. ':svg:feConvolveMatrix^:svg:|',
  14429. ':svg:feDiffuseLighting^:svg:|',
  14430. ':svg:feDisplacementMap^:svg:|',
  14431. ':svg:feDistantLight^:svg:|',
  14432. ':svg:feDropShadow^:svg:|',
  14433. ':svg:feFlood^:svg:|',
  14434. ':svg:feFuncA^:svg:componentTransferFunction|',
  14435. ':svg:feFuncB^:svg:componentTransferFunction|',
  14436. ':svg:feFuncG^:svg:componentTransferFunction|',
  14437. ':svg:feFuncR^:svg:componentTransferFunction|',
  14438. ':svg:feGaussianBlur^:svg:|',
  14439. ':svg:feImage^:svg:|',
  14440. ':svg:feMerge^:svg:|',
  14441. ':svg:feMergeNode^:svg:|',
  14442. ':svg:feMorphology^:svg:|',
  14443. ':svg:feOffset^:svg:|',
  14444. ':svg:fePointLight^:svg:|',
  14445. ':svg:feSpecularLighting^:svg:|',
  14446. ':svg:feSpotLight^:svg:|',
  14447. ':svg:feTile^:svg:|',
  14448. ':svg:feTurbulence^:svg:|',
  14449. ':svg:filter^:svg:|',
  14450. ':svg:foreignObject^:svg:graphics|',
  14451. ':svg:g^:svg:graphics|',
  14452. ':svg:image^:svg:graphics|',
  14453. ':svg:line^:svg:geometry|',
  14454. ':svg:linearGradient^:svg:gradient|',
  14455. ':svg:mpath^:svg:|',
  14456. ':svg:marker^:svg:|',
  14457. ':svg:mask^:svg:|',
  14458. ':svg:metadata^:svg:|',
  14459. ':svg:path^:svg:geometry|',
  14460. ':svg:pattern^:svg:|',
  14461. ':svg:polygon^:svg:geometry|',
  14462. ':svg:polyline^:svg:geometry|',
  14463. ':svg:radialGradient^:svg:gradient|',
  14464. ':svg:rect^:svg:geometry|',
  14465. ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
  14466. ':svg:script^:svg:|type',
  14467. ':svg:set^:svg:animation|',
  14468. ':svg:stop^:svg:|',
  14469. ':svg:style^:svg:|!disabled,media,title,type',
  14470. ':svg:switch^:svg:graphics|',
  14471. ':svg:symbol^:svg:|',
  14472. ':svg:tspan^:svg:textPositioning|',
  14473. ':svg:text^:svg:textPositioning|',
  14474. ':svg:textPath^:svg:textContent|',
  14475. ':svg:title^:svg:|',
  14476. ':svg:use^:svg:graphics|',
  14477. ':svg:view^:svg:|#zoomAndPan',
  14478. 'data^[HTMLElement]|value',
  14479. 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
  14480. 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
  14481. 'summary^[HTMLElement]|',
  14482. 'time^[HTMLElement]|dateTime',
  14483. ':svg:cursor^:svg:|',
  14484. ];
  14485. var _ATTR_TO_PROP = {
  14486. 'class': 'className',
  14487. 'for': 'htmlFor',
  14488. 'formaction': 'formAction',
  14489. 'innerHtml': 'innerHTML',
  14490. 'readonly': 'readOnly',
  14491. 'tabindex': 'tabIndex',
  14492. };
  14493. var DomElementSchemaRegistry = /** @class */ (function (_super) {
  14494. __extends(DomElementSchemaRegistry, _super);
  14495. function DomElementSchemaRegistry() {
  14496. var _this = _super.call(this) || this;
  14497. _this._schema = {};
  14498. SCHEMA.forEach(function (encodedType) {
  14499. var type = {};
  14500. var _a = __read(encodedType.split('|'), 2), strType = _a[0], strProperties = _a[1];
  14501. var properties = strProperties.split(',');
  14502. var _b = __read(strType.split('^'), 2), typeNames = _b[0], superName = _b[1];
  14503. typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
  14504. var superType = superName && _this._schema[superName.toLowerCase()];
  14505. if (superType) {
  14506. Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; });
  14507. }
  14508. properties.forEach(function (property) {
  14509. if (property.length > 0) {
  14510. switch (property[0]) {
  14511. case '*':
  14512. // We don't yet support events.
  14513. // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
  14514. // will
  14515. // almost certainly introduce bad XSS vulnerabilities.
  14516. // type[property.substring(1)] = EVENT;
  14517. break;
  14518. case '!':
  14519. type[property.substring(1)] = BOOLEAN;
  14520. break;
  14521. case '#':
  14522. type[property.substring(1)] = NUMBER;
  14523. break;
  14524. case '%':
  14525. type[property.substring(1)] = OBJECT;
  14526. break;
  14527. default:
  14528. type[property] = STRING;
  14529. }
  14530. }
  14531. });
  14532. });
  14533. return _this;
  14534. }
  14535. DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
  14536. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  14537. return true;
  14538. }
  14539. if (tagName.indexOf('-') > -1) {
  14540. if (isNgContainer(tagName) || isNgContent(tagName)) {
  14541. return false;
  14542. }
  14543. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  14544. // Can't tell now as we don't know which properties a custom element will get
  14545. // once it is instantiated
  14546. return true;
  14547. }
  14548. }
  14549. var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
  14550. return !!elementProperties[propName];
  14551. };
  14552. DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
  14553. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  14554. return true;
  14555. }
  14556. if (tagName.indexOf('-') > -1) {
  14557. if (isNgContainer(tagName) || isNgContent(tagName)) {
  14558. return true;
  14559. }
  14560. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  14561. // Allow any custom elements
  14562. return true;
  14563. }
  14564. }
  14565. return !!this._schema[tagName.toLowerCase()];
  14566. };
  14567. /**
  14568. * securityContext returns the security context for the given property on the given DOM tag.
  14569. *
  14570. * Tag and property name are statically known and cannot change at runtime, i.e. it is not
  14571. * possible to bind a value into a changing attribute or tag name.
  14572. *
  14573. * The filtering is based on a list of allowed tags|attributes. All attributes in the schema
  14574. * above are assumed to have the 'NONE' security context, i.e. that they are safe inert
  14575. * string values. Only specific well known attack vectors are assigned their appropriate context.
  14576. */
  14577. DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
  14578. if (isAttribute) {
  14579. // NB: For security purposes, use the mapped property name, not the attribute name.
  14580. propName = this.getMappedPropName(propName);
  14581. }
  14582. // Make sure comparisons are case insensitive, so that case differences between attribute and
  14583. // property names do not have a security impact.
  14584. tagName = tagName.toLowerCase();
  14585. propName = propName.toLowerCase();
  14586. var ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
  14587. if (ctx) {
  14588. return ctx;
  14589. }
  14590. ctx = SECURITY_SCHEMA()['*|' + propName];
  14591. return ctx ? ctx : SecurityContext.NONE;
  14592. };
  14593. DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; };
  14594. DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; };
  14595. DomElementSchemaRegistry.prototype.validateProperty = function (name) {
  14596. if (name.toLowerCase().startsWith('on')) {
  14597. var msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
  14598. ("please use (" + name.slice(2) + ")=...") +
  14599. ("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
  14600. " current module.";
  14601. return { error: true, msg: msg };
  14602. }
  14603. else {
  14604. return { error: false };
  14605. }
  14606. };
  14607. DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
  14608. if (name.toLowerCase().startsWith('on')) {
  14609. var msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
  14610. ("please use (" + name.slice(2) + ")=...");
  14611. return { error: true, msg: msg };
  14612. }
  14613. else {
  14614. return { error: false };
  14615. }
  14616. };
  14617. DomElementSchemaRegistry.prototype.allKnownElementNames = function () { return Object.keys(this._schema); };
  14618. DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
  14619. return dashCaseToCamelCase(propName);
  14620. };
  14621. DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
  14622. var unit = '';
  14623. var strVal = val.toString().trim();
  14624. var errorMsg = null;
  14625. if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
  14626. if (typeof val === 'number') {
  14627. unit = 'px';
  14628. }
  14629. else {
  14630. var valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
  14631. if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
  14632. errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
  14633. }
  14634. }
  14635. }
  14636. return { error: errorMsg, value: strVal + unit };
  14637. };
  14638. return DomElementSchemaRegistry;
  14639. }(ElementSchemaRegistry));
  14640. function _isPixelDimensionStyle(prop) {
  14641. switch (prop) {
  14642. case 'width':
  14643. case 'height':
  14644. case 'minWidth':
  14645. case 'minHeight':
  14646. case 'maxWidth':
  14647. case 'maxHeight':
  14648. case 'left':
  14649. case 'top':
  14650. case 'bottom':
  14651. case 'right':
  14652. case 'fontSize':
  14653. case 'outlineWidth':
  14654. case 'outlineOffset':
  14655. case 'paddingTop':
  14656. case 'paddingLeft':
  14657. case 'paddingBottom':
  14658. case 'paddingRight':
  14659. case 'marginTop':
  14660. case 'marginLeft':
  14661. case 'marginBottom':
  14662. case 'marginRight':
  14663. case 'borderRadius':
  14664. case 'borderWidth':
  14665. case 'borderTopWidth':
  14666. case 'borderLeftWidth':
  14667. case 'borderRightWidth':
  14668. case 'borderBottomWidth':
  14669. case 'textIndent':
  14670. return true;
  14671. default:
  14672. return false;
  14673. }
  14674. }
  14675. /**
  14676. * @license
  14677. * Copyright Google Inc. All Rights Reserved.
  14678. *
  14679. * Use of this source code is governed by an MIT-style license that can be
  14680. * found in the LICENSE file at https://angular.io/license
  14681. */
  14682. var BIND_NAME_REGEXP$1 = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  14683. // Group 1 = "bind-"
  14684. var KW_BIND_IDX$1 = 1;
  14685. // Group 2 = "let-"
  14686. var KW_LET_IDX$1 = 2;
  14687. // Group 3 = "ref-/#"
  14688. var KW_REF_IDX$1 = 3;
  14689. // Group 4 = "on-"
  14690. var KW_ON_IDX$1 = 4;
  14691. // Group 5 = "bindon-"
  14692. var KW_BINDON_IDX$1 = 5;
  14693. // Group 6 = "@"
  14694. var KW_AT_IDX$1 = 6;
  14695. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  14696. var IDENT_KW_IDX$1 = 7;
  14697. // Group 8 = identifier inside [()]
  14698. var IDENT_BANANA_BOX_IDX$1 = 8;
  14699. // Group 9 = identifier inside []
  14700. var IDENT_PROPERTY_IDX$1 = 9;
  14701. // Group 10 = identifier inside ()
  14702. var IDENT_EVENT_IDX$1 = 10;
  14703. var TEMPLATE_ATTR_PREFIX$1 = '*';
  14704. function htmlAstToRender3Ast(htmlNodes, bindingParser) {
  14705. var transformer = new HtmlAstToIvyAst(bindingParser);
  14706. var ivyNodes = visitAll$1(transformer, htmlNodes);
  14707. // Errors might originate in either the binding parser or the html to ivy transformer
  14708. var allErrors = bindingParser.errors.concat(transformer.errors);
  14709. var errors = allErrors.filter(function (e) { return e.level === ParseErrorLevel.ERROR; });
  14710. if (errors.length > 0) {
  14711. var errorString = errors.join('\n');
  14712. throw syntaxError("Template parse errors:\n" + errorString, errors);
  14713. }
  14714. return {
  14715. nodes: ivyNodes,
  14716. errors: allErrors,
  14717. styleUrls: transformer.styleUrls,
  14718. styles: transformer.styles,
  14719. };
  14720. }
  14721. var HtmlAstToIvyAst = /** @class */ (function () {
  14722. function HtmlAstToIvyAst(bindingParser) {
  14723. this.bindingParser = bindingParser;
  14724. this.errors = [];
  14725. this.styles = [];
  14726. this.styleUrls = [];
  14727. }
  14728. // HTML visitor
  14729. HtmlAstToIvyAst.prototype.visitElement = function (element) {
  14730. var _this = this;
  14731. var e_1, _a;
  14732. var preparsedElement = preparseElement(element);
  14733. if (preparsedElement.type === PreparsedElementType.SCRIPT) {
  14734. return null;
  14735. }
  14736. else if (preparsedElement.type === PreparsedElementType.STYLE) {
  14737. var contents = textContents(element);
  14738. if (contents !== null) {
  14739. this.styles.push(contents);
  14740. }
  14741. return null;
  14742. }
  14743. else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  14744. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  14745. this.styleUrls.push(preparsedElement.hrefAttr);
  14746. return null;
  14747. }
  14748. // Whether the element is a `<ng-template>`
  14749. var isTemplateElement = isNgTemplate(element.name);
  14750. var parsedProperties = [];
  14751. var boundEvents = [];
  14752. var variables = [];
  14753. var references = [];
  14754. var attributes = [];
  14755. var i18nAttrsMeta = {};
  14756. var templateParsedProperties = [];
  14757. var templateVariables = [];
  14758. // Whether the element has any *-attribute
  14759. var elementHasInlineTemplate = false;
  14760. try {
  14761. for (var _b = __values(element.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
  14762. var attribute = _c.value;
  14763. var hasBinding = false;
  14764. var normalizedName = normalizeAttributeName(attribute.name);
  14765. // `*attr` defines template bindings
  14766. var isTemplateBinding = false;
  14767. if (attribute.i18n) {
  14768. i18nAttrsMeta[attribute.name] = attribute.i18n;
  14769. }
  14770. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
  14771. // *-attributes
  14772. if (elementHasInlineTemplate) {
  14773. this.reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attribute.sourceSpan);
  14774. }
  14775. isTemplateBinding = true;
  14776. elementHasInlineTemplate = true;
  14777. var templateValue = attribute.value;
  14778. var templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
  14779. var parsedVariables = [];
  14780. this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, [], templateParsedProperties, parsedVariables);
  14781. templateVariables.push.apply(templateVariables, __spread(parsedVariables.map(function (v) { return new Variable(v.name, v.value, v.sourceSpan); })));
  14782. }
  14783. else {
  14784. // Check for variables, events, property bindings, interpolation
  14785. hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
  14786. }
  14787. if (!hasBinding && !isTemplateBinding) {
  14788. // don't include the bindings as attributes as well in the AST
  14789. attributes.push(this.visitAttribute(attribute));
  14790. }
  14791. }
  14792. }
  14793. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  14794. finally {
  14795. try {
  14796. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  14797. }
  14798. finally { if (e_1) throw e_1.error; }
  14799. }
  14800. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
  14801. var parsedElement;
  14802. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  14803. // `<ng-content>`
  14804. if (element.children &&
  14805. !element.children.every(function (node) { return isEmptyTextNode(node) || isCommentNode(node); })) {
  14806. this.reportError("<ng-content> element cannot have content.", element.sourceSpan);
  14807. }
  14808. var selector = preparsedElement.selectAttr;
  14809. var attrs = element.attrs.map(function (attr) { return _this.visitAttribute(attr); });
  14810. parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
  14811. }
  14812. else if (isTemplateElement) {
  14813. // `<ng-template>`
  14814. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  14815. parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14816. }
  14817. else {
  14818. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  14819. parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14820. }
  14821. if (elementHasInlineTemplate) {
  14822. // If this node is an inline-template (e.g. has *ngFor) then we need to create a template
  14823. // node that contains this node.
  14824. // Moreover, if the node is an element, then we need to hoist its attributes to the template
  14825. // node for matching against content projection selectors.
  14826. var attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
  14827. var templateAttrs_1 = [];
  14828. attrs.literal.forEach(function (attr) { return templateAttrs_1.push(attr); });
  14829. attrs.bound.forEach(function (attr) { return templateAttrs_1.push(attr); });
  14830. var hoistedAttrs = parsedElement instanceof Element ?
  14831. {
  14832. attributes: parsedElement.attributes,
  14833. inputs: parsedElement.inputs,
  14834. outputs: parsedElement.outputs,
  14835. } :
  14836. { attributes: [], inputs: [], outputs: [] };
  14837. // TODO(pk): test for this case
  14838. parsedElement = new Template(parsedElement.name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs_1, [parsedElement], [ /* no references */], templateVariables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14839. }
  14840. return parsedElement;
  14841. };
  14842. HtmlAstToIvyAst.prototype.visitAttribute = function (attribute) {
  14843. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.valueSpan, attribute.i18n);
  14844. };
  14845. HtmlAstToIvyAst.prototype.visitText = function (text) {
  14846. return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
  14847. };
  14848. HtmlAstToIvyAst.prototype.visitExpansion = function (expansion) {
  14849. var _this = this;
  14850. var meta = expansion.i18n;
  14851. // do not generate Icu in case it was created
  14852. // outside of i18n block in a template
  14853. if (!meta) {
  14854. return null;
  14855. }
  14856. var vars = {};
  14857. var placeholders = {};
  14858. // extract VARs from ICUs - we process them separately while
  14859. // assembling resulting message via goog.getMsg function, since
  14860. // we need to pass them to top-level goog.getMsg call
  14861. Object.keys(meta.placeholders).forEach(function (key) {
  14862. var value = meta.placeholders[key];
  14863. if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
  14864. var config = _this.bindingParser.interpolationConfig;
  14865. // ICU expression is a plain string, not wrapped into start
  14866. // and end tags, so we wrap it before passing to binding parser
  14867. var wrapped = "" + config.start + value + config.end;
  14868. vars[key] = _this._visitTextWithInterpolation(wrapped, expansion.sourceSpan);
  14869. }
  14870. else {
  14871. placeholders[key] = _this._visitTextWithInterpolation(value, expansion.sourceSpan);
  14872. }
  14873. });
  14874. return new Icu(vars, placeholders, expansion.sourceSpan, meta);
  14875. };
  14876. HtmlAstToIvyAst.prototype.visitExpansionCase = function (expansionCase) { return null; };
  14877. HtmlAstToIvyAst.prototype.visitComment = function (comment) { return null; };
  14878. // convert view engine `ParsedProperty` to a format suitable for IVY
  14879. HtmlAstToIvyAst.prototype.extractAttributes = function (elementName, properties, i18nPropsMeta) {
  14880. var _this = this;
  14881. var bound = [];
  14882. var literal = [];
  14883. properties.forEach(function (prop) {
  14884. var i18n = i18nPropsMeta[prop.name];
  14885. if (prop.isLiteral) {
  14886. literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, undefined, i18n));
  14887. }
  14888. else {
  14889. // Note that validation is skipped and property mapping is disabled
  14890. // due to the fact that we need to make sure a given prop is not an
  14891. // input of a directive and directive matching happens at runtime.
  14892. var bep = _this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
  14893. bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
  14894. }
  14895. });
  14896. return { bound: bound, literal: literal };
  14897. };
  14898. HtmlAstToIvyAst.prototype.parseAttribute = function (isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
  14899. var name = normalizeAttributeName(attribute.name);
  14900. var value = attribute.value;
  14901. var srcSpan = attribute.sourceSpan;
  14902. var bindParts = name.match(BIND_NAME_REGEXP$1);
  14903. var hasBinding = false;
  14904. if (bindParts) {
  14905. hasBinding = true;
  14906. if (bindParts[KW_BIND_IDX$1] != null) {
  14907. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14908. }
  14909. else if (bindParts[KW_LET_IDX$1]) {
  14910. if (isTemplateElement) {
  14911. var identifier = bindParts[IDENT_KW_IDX$1];
  14912. this.parseVariable(identifier, value, srcSpan, variables);
  14913. }
  14914. else {
  14915. this.reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  14916. }
  14917. }
  14918. else if (bindParts[KW_REF_IDX$1]) {
  14919. var identifier = bindParts[IDENT_KW_IDX$1];
  14920. this.parseReference(identifier, value, srcSpan, references);
  14921. }
  14922. else if (bindParts[KW_ON_IDX$1]) {
  14923. var events = [];
  14924. this.bindingParser.parseEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14925. addEvents(events, boundEvents);
  14926. }
  14927. else if (bindParts[KW_BINDON_IDX$1]) {
  14928. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14929. this.parseAssignmentEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14930. }
  14931. else if (bindParts[KW_AT_IDX$1]) {
  14932. this.bindingParser.parseLiteralAttr(name, value, srcSpan, matchableAttributes, parsedProperties);
  14933. }
  14934. else if (bindParts[IDENT_BANANA_BOX_IDX$1]) {
  14935. this.bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14936. this.parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14937. }
  14938. else if (bindParts[IDENT_PROPERTY_IDX$1]) {
  14939. this.bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14940. }
  14941. else if (bindParts[IDENT_EVENT_IDX$1]) {
  14942. var events = [];
  14943. this.bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14944. addEvents(events, boundEvents);
  14945. }
  14946. }
  14947. else {
  14948. hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, matchableAttributes, parsedProperties);
  14949. }
  14950. return hasBinding;
  14951. };
  14952. HtmlAstToIvyAst.prototype._visitTextWithInterpolation = function (value, sourceSpan, i18n) {
  14953. var valueNoNgsp = replaceNgsp(value);
  14954. var expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
  14955. return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
  14956. };
  14957. HtmlAstToIvyAst.prototype.parseVariable = function (identifier, value, sourceSpan, variables) {
  14958. if (identifier.indexOf('-') > -1) {
  14959. this.reportError("\"-\" is not allowed in variable names", sourceSpan);
  14960. }
  14961. variables.push(new Variable(identifier, value, sourceSpan));
  14962. };
  14963. HtmlAstToIvyAst.prototype.parseReference = function (identifier, value, sourceSpan, references) {
  14964. if (identifier.indexOf('-') > -1) {
  14965. this.reportError("\"-\" is not allowed in reference names", sourceSpan);
  14966. }
  14967. references.push(new Reference(identifier, value, sourceSpan));
  14968. };
  14969. HtmlAstToIvyAst.prototype.parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents) {
  14970. var events = [];
  14971. this.bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events);
  14972. addEvents(events, boundEvents);
  14973. };
  14974. HtmlAstToIvyAst.prototype.reportError = function (message, sourceSpan, level) {
  14975. if (level === void 0) { level = ParseErrorLevel.ERROR; }
  14976. this.errors.push(new ParseError(sourceSpan, message, level));
  14977. };
  14978. return HtmlAstToIvyAst;
  14979. }());
  14980. var NonBindableVisitor$1 = /** @class */ (function () {
  14981. function NonBindableVisitor() {
  14982. }
  14983. NonBindableVisitor.prototype.visitElement = function (ast) {
  14984. var preparsedElement = preparseElement(ast);
  14985. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  14986. preparsedElement.type === PreparsedElementType.STYLE ||
  14987. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  14988. // Skipping <script> for security reasons
  14989. // Skipping <style> and stylesheets as we already processed them
  14990. // in the StyleCompiler
  14991. return null;
  14992. }
  14993. var children = visitAll$1(this, ast.children, null);
  14994. return new Element(ast.name, visitAll$1(this, ast.attrs),
  14995. /* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
  14996. };
  14997. NonBindableVisitor.prototype.visitComment = function (comment) { return null; };
  14998. NonBindableVisitor.prototype.visitAttribute = function (attribute) {
  14999. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, undefined, attribute.i18n);
  15000. };
  15001. NonBindableVisitor.prototype.visitText = function (text) { return new Text(text.value, text.sourceSpan); };
  15002. NonBindableVisitor.prototype.visitExpansion = function (expansion) { return null; };
  15003. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase) { return null; };
  15004. return NonBindableVisitor;
  15005. }());
  15006. var NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
  15007. function normalizeAttributeName(attrName) {
  15008. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  15009. }
  15010. function addEvents(events, boundEvents) {
  15011. boundEvents.push.apply(boundEvents, __spread(events.map(function (e) { return BoundEvent.fromParsedEvent(e); })));
  15012. }
  15013. function isEmptyTextNode(node) {
  15014. return node instanceof Text$3 && node.value.trim().length == 0;
  15015. }
  15016. function isCommentNode(node) {
  15017. return node instanceof Comment;
  15018. }
  15019. function textContents(node) {
  15020. if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
  15021. return null;
  15022. }
  15023. else {
  15024. return node.children[0].value;
  15025. }
  15026. }
  15027. /**
  15028. * @license
  15029. * Copyright Google Inc. All Rights Reserved.
  15030. *
  15031. * Use of this source code is governed by an MIT-style license that can be
  15032. * found in the LICENSE file at https://angular.io/license
  15033. */
  15034. var TagType;
  15035. (function (TagType) {
  15036. TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
  15037. TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
  15038. TagType[TagType["PROJECTION"] = 2] = "PROJECTION";
  15039. })(TagType || (TagType = {}));
  15040. /**
  15041. * Generates an object that is used as a shared state between parent and all child contexts.
  15042. */
  15043. function setupRegistry() {
  15044. return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
  15045. }
  15046. /**
  15047. * I18nContext is a helper class which keeps track of all i18n-related aspects
  15048. * (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
  15049. *
  15050. * When we enter a nested template, the top-level context is being passed down
  15051. * to the nested component, which uses this context to generate a child instance
  15052. * of I18nContext class (to handle nested template) and at the end, reconciles it back
  15053. * with the parent context.
  15054. *
  15055. * @param index Instruction index of i18nStart, which initiates this context
  15056. * @param ref Reference to a translation const that represents the content if thus context
  15057. * @param level Nestng level defined for child contexts
  15058. * @param templateIndex Instruction index of a template which this context belongs to
  15059. * @param meta Meta information (id, meaning, description, etc) associated with this context
  15060. */
  15061. var I18nContext = /** @class */ (function () {
  15062. function I18nContext(index, ref, level, templateIndex, meta, registry) {
  15063. if (level === void 0) { level = 0; }
  15064. if (templateIndex === void 0) { templateIndex = null; }
  15065. this.index = index;
  15066. this.ref = ref;
  15067. this.level = level;
  15068. this.templateIndex = templateIndex;
  15069. this.meta = meta;
  15070. this.registry = registry;
  15071. this.bindings = new Set();
  15072. this.placeholders = new Map();
  15073. this.isEmitted = false;
  15074. this._unresolvedCtxCount = 0;
  15075. this._registry = registry || setupRegistry();
  15076. this.id = this._registry.getUniqueId();
  15077. }
  15078. I18nContext.prototype.appendTag = function (type, node, index, closed) {
  15079. if (node.isVoid && closed) {
  15080. return; // ignore "close" for void tags
  15081. }
  15082. var ph = node.isVoid || !closed ? node.startName : node.closeName;
  15083. var content = { type: type, index: index, ctx: this.id, isVoid: node.isVoid, closed: closed };
  15084. updatePlaceholderMap(this.placeholders, ph, content);
  15085. };
  15086. Object.defineProperty(I18nContext.prototype, "icus", {
  15087. get: function () { return this._registry.icus; },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Object.defineProperty(I18nContext.prototype, "isRoot", {
  15092. get: function () { return this.level === 0; },
  15093. enumerable: true,
  15094. configurable: true
  15095. });
  15096. Object.defineProperty(I18nContext.prototype, "isResolved", {
  15097. get: function () { return this._unresolvedCtxCount === 0; },
  15098. enumerable: true,
  15099. configurable: true
  15100. });
  15101. I18nContext.prototype.getSerializedPlaceholders = function () {
  15102. var result = new Map();
  15103. this.placeholders.forEach(function (values, key) { return result.set(key, values.map(serializePlaceholderValue)); });
  15104. return result;
  15105. };
  15106. // public API to accumulate i18n-related content
  15107. I18nContext.prototype.appendBinding = function (binding) { this.bindings.add(binding); };
  15108. I18nContext.prototype.appendIcu = function (name, ref) {
  15109. updatePlaceholderMap(this._registry.icus, name, ref);
  15110. };
  15111. I18nContext.prototype.appendBoundText = function (node) {
  15112. var _this = this;
  15113. var phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
  15114. phs.forEach(function (values, key) { return updatePlaceholderMap.apply(void 0, __spread([_this.placeholders, key], values)); });
  15115. };
  15116. I18nContext.prototype.appendTemplate = function (node, index) {
  15117. // add open and close tags at the same time,
  15118. // since we process nested templates separately
  15119. this.appendTag(TagType.TEMPLATE, node, index, false);
  15120. this.appendTag(TagType.TEMPLATE, node, index, true);
  15121. this._unresolvedCtxCount++;
  15122. };
  15123. I18nContext.prototype.appendElement = function (node, index, closed) {
  15124. this.appendTag(TagType.ELEMENT, node, index, closed);
  15125. };
  15126. I18nContext.prototype.appendProjection = function (node, index) {
  15127. // add open and close tags at the same time,
  15128. // since we process projected content separately
  15129. this.appendTag(TagType.PROJECTION, node, index, false);
  15130. this.appendTag(TagType.PROJECTION, node, index, true);
  15131. };
  15132. /**
  15133. * Generates an instance of a child context based on the root one,
  15134. * when we enter a nested template within I18n section.
  15135. *
  15136. * @param index Instruction index of corresponding i18nStart, which initiates this context
  15137. * @param templateIndex Instruction index of a template which this context belongs to
  15138. * @param meta Meta information (id, meaning, description, etc) associated with this context
  15139. *
  15140. * @returns I18nContext instance
  15141. */
  15142. I18nContext.prototype.forkChildContext = function (index, templateIndex, meta) {
  15143. return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
  15144. };
  15145. /**
  15146. * Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
  15147. *
  15148. * @param context Child I18nContext instance to be reconciled with parent context.
  15149. */
  15150. I18nContext.prototype.reconcileChildContext = function (context) {
  15151. var _this = this;
  15152. // set the right context id for open and close
  15153. // template tags, so we can use it as sub-block ids
  15154. ['start', 'close'].forEach(function (op) {
  15155. var key = context.meta[op + "Name"];
  15156. var phs = _this.placeholders.get(key) || [];
  15157. var tag = phs.find(findTemplateFn(_this.id, context.templateIndex));
  15158. if (tag) {
  15159. tag.ctx = context.id;
  15160. }
  15161. });
  15162. // reconcile placeholders
  15163. var childPhs = context.placeholders;
  15164. childPhs.forEach(function (values, key) {
  15165. var phs = _this.placeholders.get(key);
  15166. if (!phs) {
  15167. _this.placeholders.set(key, values);
  15168. return;
  15169. }
  15170. // try to find matching template...
  15171. var tmplIdx = findIndex(phs, findTemplateFn(context.id, context.templateIndex));
  15172. if (tmplIdx >= 0) {
  15173. // ... if found - replace it with nested template content
  15174. var isCloseTag = key.startsWith('CLOSE');
  15175. var isTemplateTag = key.endsWith('NG-TEMPLATE');
  15176. if (isTemplateTag) {
  15177. // current template's content is placed before or after
  15178. // parent template tag, depending on the open/close atrribute
  15179. phs.splice.apply(phs, __spread([tmplIdx + (isCloseTag ? 0 : 1), 0], values));
  15180. }
  15181. else {
  15182. var idx = isCloseTag ? values.length - 1 : 0;
  15183. values[idx].tmpl = phs[tmplIdx];
  15184. phs.splice.apply(phs, __spread([tmplIdx, 1], values));
  15185. }
  15186. }
  15187. else {
  15188. // ... otherwise just append content to placeholder value
  15189. phs.push.apply(phs, __spread(values));
  15190. }
  15191. _this.placeholders.set(key, phs);
  15192. });
  15193. this._unresolvedCtxCount--;
  15194. };
  15195. return I18nContext;
  15196. }());
  15197. //
  15198. // Helper methods
  15199. //
  15200. function wrap(symbol, index, contextId, closed) {
  15201. var state = closed ? '/' : '';
  15202. return wrapI18nPlaceholder("" + state + symbol + index, contextId);
  15203. }
  15204. function wrapTag(symbol, _a, closed) {
  15205. var index = _a.index, ctx = _a.ctx, isVoid = _a.isVoid;
  15206. return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
  15207. wrap(symbol, index, ctx, closed);
  15208. }
  15209. function findTemplateFn(ctx, templateIndex) {
  15210. return function (token) { return typeof token === 'object' && token.type === TagType.TEMPLATE &&
  15211. token.index === templateIndex && token.ctx === ctx; };
  15212. }
  15213. function serializePlaceholderValue(value) {
  15214. var element = function (data, closed) { return wrapTag('#', data, closed); };
  15215. var template = function (data, closed) { return wrapTag('*', data, closed); };
  15216. var projection = function (data, closed) { return wrapTag('!', data, closed); };
  15217. switch (value.type) {
  15218. case TagType.ELEMENT:
  15219. // close element tag
  15220. if (value.closed) {
  15221. return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
  15222. }
  15223. // open element tag that also initiates a template
  15224. if (value.tmpl) {
  15225. return template(value.tmpl) + element(value) +
  15226. (value.isVoid ? template(value.tmpl, true) : '');
  15227. }
  15228. return element(value);
  15229. case TagType.TEMPLATE:
  15230. return template(value, value.closed);
  15231. case TagType.PROJECTION:
  15232. return projection(value, value.closed);
  15233. default:
  15234. return value;
  15235. }
  15236. }
  15237. /**
  15238. * @license
  15239. * Copyright Google Inc. All Rights Reserved.
  15240. *
  15241. * Use of this source code is governed by an MIT-style license that can be
  15242. * found in the LICENSE file at https://angular.io/license
  15243. */
  15244. var TAG_TO_PLACEHOLDER_NAMES = {
  15245. 'A': 'LINK',
  15246. 'B': 'BOLD_TEXT',
  15247. 'BR': 'LINE_BREAK',
  15248. 'EM': 'EMPHASISED_TEXT',
  15249. 'H1': 'HEADING_LEVEL1',
  15250. 'H2': 'HEADING_LEVEL2',
  15251. 'H3': 'HEADING_LEVEL3',
  15252. 'H4': 'HEADING_LEVEL4',
  15253. 'H5': 'HEADING_LEVEL5',
  15254. 'H6': 'HEADING_LEVEL6',
  15255. 'HR': 'HORIZONTAL_RULE',
  15256. 'I': 'ITALIC_TEXT',
  15257. 'LI': 'LIST_ITEM',
  15258. 'LINK': 'MEDIA_LINK',
  15259. 'OL': 'ORDERED_LIST',
  15260. 'P': 'PARAGRAPH',
  15261. 'Q': 'QUOTATION',
  15262. 'S': 'STRIKETHROUGH_TEXT',
  15263. 'SMALL': 'SMALL_TEXT',
  15264. 'SUB': 'SUBSTRIPT',
  15265. 'SUP': 'SUPERSCRIPT',
  15266. 'TBODY': 'TABLE_BODY',
  15267. 'TD': 'TABLE_CELL',
  15268. 'TFOOT': 'TABLE_FOOTER',
  15269. 'TH': 'TABLE_HEADER_CELL',
  15270. 'THEAD': 'TABLE_HEADER',
  15271. 'TR': 'TABLE_ROW',
  15272. 'TT': 'MONOSPACED_TEXT',
  15273. 'U': 'UNDERLINED_TEXT',
  15274. 'UL': 'UNORDERED_LIST',
  15275. };
  15276. /**
  15277. * Creates unique names for placeholder with different content.
  15278. *
  15279. * Returns the same placeholder name when the content is identical.
  15280. */
  15281. var PlaceholderRegistry = /** @class */ (function () {
  15282. function PlaceholderRegistry() {
  15283. // Count the occurrence of the base name top generate a unique name
  15284. this._placeHolderNameCounts = {};
  15285. // Maps signature to placeholder names
  15286. this._signatureToName = {};
  15287. }
  15288. PlaceholderRegistry.prototype.getStartTagPlaceholderName = function (tag, attrs, isVoid) {
  15289. var signature = this._hashTag(tag, attrs, isVoid);
  15290. if (this._signatureToName[signature]) {
  15291. return this._signatureToName[signature];
  15292. }
  15293. var upperTag = tag.toUpperCase();
  15294. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  15295. var name = this._generateUniqueName(isVoid ? baseName : "START_" + baseName);
  15296. this._signatureToName[signature] = name;
  15297. return name;
  15298. };
  15299. PlaceholderRegistry.prototype.getCloseTagPlaceholderName = function (tag) {
  15300. var signature = this._hashClosingTag(tag);
  15301. if (this._signatureToName[signature]) {
  15302. return this._signatureToName[signature];
  15303. }
  15304. var upperTag = tag.toUpperCase();
  15305. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  15306. var name = this._generateUniqueName("CLOSE_" + baseName);
  15307. this._signatureToName[signature] = name;
  15308. return name;
  15309. };
  15310. PlaceholderRegistry.prototype.getPlaceholderName = function (name, content) {
  15311. var upperName = name.toUpperCase();
  15312. var signature = "PH: " + upperName + "=" + content;
  15313. if (this._signatureToName[signature]) {
  15314. return this._signatureToName[signature];
  15315. }
  15316. var uniqueName = this._generateUniqueName(upperName);
  15317. this._signatureToName[signature] = uniqueName;
  15318. return uniqueName;
  15319. };
  15320. PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
  15321. return this._generateUniqueName(name.toUpperCase());
  15322. };
  15323. // Generate a hash for a tag - does not take attribute order into account
  15324. PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {
  15325. var start = "<" + tag;
  15326. var strAttrs = Object.keys(attrs).sort().map(function (name) { return " " + name + "=" + attrs[name]; }).join('');
  15327. var end = isVoid ? '/>' : "></" + tag + ">";
  15328. return start + strAttrs + end;
  15329. };
  15330. PlaceholderRegistry.prototype._hashClosingTag = function (tag) { return this._hashTag("/" + tag, {}, false); };
  15331. PlaceholderRegistry.prototype._generateUniqueName = function (base) {
  15332. var seen = this._placeHolderNameCounts.hasOwnProperty(base);
  15333. if (!seen) {
  15334. this._placeHolderNameCounts[base] = 1;
  15335. return base;
  15336. }
  15337. var id = this._placeHolderNameCounts[base];
  15338. this._placeHolderNameCounts[base] = id + 1;
  15339. return base + "_" + id;
  15340. };
  15341. return PlaceholderRegistry;
  15342. }());
  15343. /**
  15344. * @license
  15345. * Copyright Google Inc. All Rights Reserved.
  15346. *
  15347. * Use of this source code is governed by an MIT-style license that can be
  15348. * found in the LICENSE file at https://angular.io/license
  15349. */
  15350. var _expParser = new Parser$1(new Lexer());
  15351. /**
  15352. * Returns a function converting html nodes to an i18n Message given an interpolationConfig
  15353. */
  15354. function createI18nMessageFactory(interpolationConfig) {
  15355. var visitor = new _I18nVisitor(_expParser, interpolationConfig);
  15356. return function (nodes, meaning, description, id, visitNodeFn) {
  15357. return visitor.toI18nMessage(nodes, meaning, description, id, visitNodeFn);
  15358. };
  15359. }
  15360. var _I18nVisitor = /** @class */ (function () {
  15361. function _I18nVisitor(_expressionParser, _interpolationConfig) {
  15362. this._expressionParser = _expressionParser;
  15363. this._interpolationConfig = _interpolationConfig;
  15364. }
  15365. _I18nVisitor.prototype.toI18nMessage = function (nodes, meaning, description, id, visitNodeFn) {
  15366. this._isIcu = nodes.length == 1 && nodes[0] instanceof Expansion;
  15367. this._icuDepth = 0;
  15368. this._placeholderRegistry = new PlaceholderRegistry();
  15369. this._placeholderToContent = {};
  15370. this._placeholderToMessage = {};
  15371. this._visitNodeFn = visitNodeFn;
  15372. var i18nodes = visitAll$1(this, nodes, {});
  15373. return new Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description, id);
  15374. };
  15375. _I18nVisitor.prototype._visitNode = function (html, i18n) {
  15376. if (this._visitNodeFn) {
  15377. this._visitNodeFn(html, i18n);
  15378. }
  15379. return i18n;
  15380. };
  15381. _I18nVisitor.prototype.visitElement = function (el, context) {
  15382. var children = visitAll$1(this, el.children);
  15383. var attrs = {};
  15384. el.attrs.forEach(function (attr) {
  15385. // Do not visit the attributes, translatable ones are top-level ASTs
  15386. attrs[attr.name] = attr.value;
  15387. });
  15388. var isVoid = getHtmlTagDefinition(el.name).isVoid;
  15389. var startPhName = this._placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
  15390. this._placeholderToContent[startPhName] = el.sourceSpan.toString();
  15391. var closePhName = '';
  15392. if (!isVoid) {
  15393. closePhName = this._placeholderRegistry.getCloseTagPlaceholderName(el.name);
  15394. this._placeholderToContent[closePhName] = "</" + el.name + ">";
  15395. }
  15396. var node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan);
  15397. return this._visitNode(el, node);
  15398. };
  15399. _I18nVisitor.prototype.visitAttribute = function (attribute, context) {
  15400. var node = this._visitTextWithInterpolation(attribute.value, attribute.sourceSpan);
  15401. return this._visitNode(attribute, node);
  15402. };
  15403. _I18nVisitor.prototype.visitText = function (text, context) {
  15404. var node = this._visitTextWithInterpolation(text.value, text.sourceSpan);
  15405. return this._visitNode(text, node);
  15406. };
  15407. _I18nVisitor.prototype.visitComment = function (comment, context) { return null; };
  15408. _I18nVisitor.prototype.visitExpansion = function (icu, context) {
  15409. var _this = this;
  15410. this._icuDepth++;
  15411. var i18nIcuCases = {};
  15412. var i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
  15413. icu.cases.forEach(function (caze) {
  15414. i18nIcuCases[caze.value] = new Container(caze.expression.map(function (node) { return node.visit(_this, {}); }), caze.expSourceSpan);
  15415. });
  15416. this._icuDepth--;
  15417. if (this._isIcu || this._icuDepth > 0) {
  15418. // Returns an ICU node when:
  15419. // - the message (vs a part of the message) is an ICU message, or
  15420. // - the ICU message is nested.
  15421. var expPh = this._placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
  15422. i18nIcu.expressionPlaceholder = expPh;
  15423. this._placeholderToContent[expPh] = icu.switchValue;
  15424. return this._visitNode(icu, i18nIcu);
  15425. }
  15426. // Else returns a placeholder
  15427. // ICU placeholders should not be replaced with their original content but with the their
  15428. // translations. We need to create a new visitor (they are not re-entrant) to compute the
  15429. // message id.
  15430. // TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
  15431. var phName = this._placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
  15432. var visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
  15433. this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '', '');
  15434. var node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
  15435. return this._visitNode(icu, node);
  15436. };
  15437. _I18nVisitor.prototype.visitExpansionCase = function (icuCase, context) {
  15438. throw new Error('Unreachable code');
  15439. };
  15440. _I18nVisitor.prototype._visitTextWithInterpolation = function (text, sourceSpan) {
  15441. var splitInterpolation = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
  15442. if (!splitInterpolation) {
  15443. // No expression, return a single text
  15444. return new Text$1(text, sourceSpan);
  15445. }
  15446. // Return a group of text + expressions
  15447. var nodes = [];
  15448. var container = new Container(nodes, sourceSpan);
  15449. var _a = this._interpolationConfig, sDelimiter = _a.start, eDelimiter = _a.end;
  15450. for (var i = 0; i < splitInterpolation.strings.length - 1; i++) {
  15451. var expression = splitInterpolation.expressions[i];
  15452. var baseName = _extractPlaceholderName(expression) || 'INTERPOLATION';
  15453. var phName = this._placeholderRegistry.getPlaceholderName(baseName, expression);
  15454. if (splitInterpolation.strings[i].length) {
  15455. // No need to add empty strings
  15456. nodes.push(new Text$1(splitInterpolation.strings[i], sourceSpan));
  15457. }
  15458. nodes.push(new Placeholder(expression, phName, sourceSpan));
  15459. this._placeholderToContent[phName] = sDelimiter + expression + eDelimiter;
  15460. }
  15461. // The last index contains no expression
  15462. var lastStringIdx = splitInterpolation.strings.length - 1;
  15463. if (splitInterpolation.strings[lastStringIdx].length) {
  15464. nodes.push(new Text$1(splitInterpolation.strings[lastStringIdx], sourceSpan));
  15465. }
  15466. return container;
  15467. };
  15468. return _I18nVisitor;
  15469. }());
  15470. var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
  15471. function _extractPlaceholderName(input) {
  15472. return input.split(_CUSTOM_PH_EXP)[2];
  15473. }
  15474. /**
  15475. * @license
  15476. * Copyright Google Inc. All Rights Reserved.
  15477. *
  15478. * Use of this source code is governed by an MIT-style license that can be
  15479. * found in the LICENSE file at https://angular.io/license
  15480. */
  15481. function setI18nRefs(html, i18n) {
  15482. html.i18n = i18n;
  15483. }
  15484. /**
  15485. * This visitor walks over HTML parse tree and converts information stored in
  15486. * i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
  15487. * stored with other element's and attribute's information.
  15488. */
  15489. var I18nMetaVisitor = /** @class */ (function () {
  15490. function I18nMetaVisitor(interpolationConfig, keepI18nAttrs) {
  15491. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15492. if (keepI18nAttrs === void 0) { keepI18nAttrs = false; }
  15493. this.interpolationConfig = interpolationConfig;
  15494. this.keepI18nAttrs = keepI18nAttrs;
  15495. // i18n message generation factory
  15496. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  15497. }
  15498. I18nMetaVisitor.prototype._generateI18nMessage = function (nodes, meta, visitNodeFn) {
  15499. if (meta === void 0) { meta = ''; }
  15500. var parsed = typeof meta === 'string' ? parseI18nMeta(meta) : metaFromI18nMessage(meta);
  15501. var message = this._createI18nMessage(nodes, parsed.meaning || '', parsed.description || '', parsed.id || '', visitNodeFn);
  15502. if (!message.id) {
  15503. // generate (or restore) message id if not specified in template
  15504. message.id = typeof meta !== 'string' && meta.id || decimalDigest(message);
  15505. }
  15506. return message;
  15507. };
  15508. I18nMetaVisitor.prototype.visitElement = function (element, context) {
  15509. var e_1, _a, e_2, _b;
  15510. if (hasI18nAttrs(element)) {
  15511. var attrs = [];
  15512. var attrsMeta = {};
  15513. try {
  15514. for (var _c = __values(element.attrs), _d = _c.next(); !_d.done; _d = _c.next()) {
  15515. var attr = _d.value;
  15516. if (attr.name === I18N_ATTR) {
  15517. // root 'i18n' node attribute
  15518. var i18n_1 = element.i18n || attr.value;
  15519. var message = this._generateI18nMessage(element.children, i18n_1, setI18nRefs);
  15520. // do not assign empty i18n meta
  15521. if (message.nodes.length) {
  15522. element.i18n = message;
  15523. }
  15524. }
  15525. else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
  15526. // 'i18n-*' attributes
  15527. var key = attr.name.slice(I18N_ATTR_PREFIX.length);
  15528. attrsMeta[key] = attr.value;
  15529. }
  15530. else {
  15531. // non-i18n attributes
  15532. attrs.push(attr);
  15533. }
  15534. }
  15535. }
  15536. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  15537. finally {
  15538. try {
  15539. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  15540. }
  15541. finally { if (e_1) throw e_1.error; }
  15542. }
  15543. // set i18n meta for attributes
  15544. if (Object.keys(attrsMeta).length) {
  15545. try {
  15546. for (var attrs_1 = __values(attrs), attrs_1_1 = attrs_1.next(); !attrs_1_1.done; attrs_1_1 = attrs_1.next()) {
  15547. var attr = attrs_1_1.value;
  15548. var meta = attrsMeta[attr.name];
  15549. // do not create translation for empty attributes
  15550. if (meta !== undefined && attr.value) {
  15551. attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
  15552. }
  15553. }
  15554. }
  15555. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  15556. finally {
  15557. try {
  15558. if (attrs_1_1 && !attrs_1_1.done && (_b = attrs_1.return)) _b.call(attrs_1);
  15559. }
  15560. finally { if (e_2) throw e_2.error; }
  15561. }
  15562. }
  15563. if (!this.keepI18nAttrs) {
  15564. // update element's attributes,
  15565. // keeping only non-i18n related ones
  15566. element.attrs = attrs;
  15567. }
  15568. }
  15569. visitAll$1(this, element.children);
  15570. return element;
  15571. };
  15572. I18nMetaVisitor.prototype.visitExpansion = function (expansion, context) {
  15573. var message;
  15574. var meta = expansion.i18n;
  15575. if (meta instanceof IcuPlaceholder) {
  15576. // set ICU placeholder name (e.g. "ICU_1"),
  15577. // generated while processing root element contents,
  15578. // so we can reference it when we output translation
  15579. var name_1 = meta.name;
  15580. message = this._generateI18nMessage([expansion], meta);
  15581. var icu = icuFromI18nMessage(message);
  15582. icu.name = name_1;
  15583. }
  15584. else {
  15585. // when ICU is a root level translation
  15586. message = this._generateI18nMessage([expansion], meta);
  15587. }
  15588. expansion.i18n = message;
  15589. return expansion;
  15590. };
  15591. I18nMetaVisitor.prototype.visitText = function (text, context) { return text; };
  15592. I18nMetaVisitor.prototype.visitAttribute = function (attribute, context) { return attribute; };
  15593. I18nMetaVisitor.prototype.visitComment = function (comment, context) { return comment; };
  15594. I18nMetaVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  15595. return I18nMetaVisitor;
  15596. }());
  15597. /**
  15598. * @license
  15599. * Copyright Google Inc. All Rights Reserved.
  15600. *
  15601. * Use of this source code is governed by an MIT-style license that can be
  15602. * found in the LICENSE file at https://angular.io/license
  15603. */
  15604. var formatPh = function (value) { return "{$" + formatI18nPlaceholderName(value) + "}"; };
  15605. /**
  15606. * This visitor walks over i18n tree and generates its string representation,
  15607. * including ICUs and placeholders in {$PLACEHOLDER} format.
  15608. */
  15609. var SerializerVisitor = /** @class */ (function () {
  15610. function SerializerVisitor() {
  15611. }
  15612. SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
  15613. SerializerVisitor.prototype.visitContainer = function (container, context) {
  15614. var _this = this;
  15615. return container.children.map(function (child) { return child.visit(_this); }).join('');
  15616. };
  15617. SerializerVisitor.prototype.visitIcu = function (icu, context) {
  15618. var _this = this;
  15619. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  15620. return "{" + icu.expressionPlaceholder + ", " + icu.type + ", " + strCases.join(' ') + "}";
  15621. };
  15622. SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  15623. var _this = this;
  15624. return ph.isVoid ?
  15625. formatPh(ph.startName) :
  15626. "" + formatPh(ph.startName) + ph.children.map(function (child) { return child.visit(_this); }).join('') + formatPh(ph.closeName);
  15627. };
  15628. SerializerVisitor.prototype.visitPlaceholder = function (ph, context) { return formatPh(ph.name); };
  15629. SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return formatPh(ph.name); };
  15630. return SerializerVisitor;
  15631. }());
  15632. var serializerVisitor$1 = new SerializerVisitor();
  15633. function getSerializedI18nContent(message) {
  15634. return message.nodes.map(function (node) { return node.visit(serializerVisitor$1, null); }).join('');
  15635. }
  15636. /**
  15637. * @license
  15638. * Copyright Google Inc. All Rights Reserved.
  15639. *
  15640. * Use of this source code is governed by an MIT-style license that can be
  15641. * found in the LICENSE file at https://angular.io/license
  15642. */
  15643. // Selector attribute name of `<ng-content>`
  15644. var NG_CONTENT_SELECT_ATTR$1 = 'select';
  15645. // Attribute name of `ngProjectAs`.
  15646. var NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
  15647. // List of supported global targets for event listeners
  15648. var GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers$1.resolveWindow], ['document', Identifiers$1.resolveDocument], ['body', Identifiers$1.resolveBody]]);
  15649. var LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
  15650. // if (rf & flags) { .. }
  15651. function renderFlagCheckIfStmt(flags, statements) {
  15652. return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
  15653. }
  15654. function prepareEventListenerParameters(eventAst, handlerName, scope) {
  15655. if (handlerName === void 0) { handlerName = null; }
  15656. if (scope === void 0) { scope = null; }
  15657. var type = eventAst.type, name = eventAst.name, target = eventAst.target, phase = eventAst.phase, handler = eventAst.handler;
  15658. if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
  15659. throw new Error("Unexpected global target '" + target + "' defined for '" + name + "' event.\n Supported list of global targets: " + Array.from(GLOBAL_TARGET_RESOLVERS.keys()) + ".");
  15660. }
  15661. var implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
  15662. variable(CONTEXT_NAME) :
  15663. scope.getOrCreateSharedContextVar(0);
  15664. var bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', function () { return error('Unexpected interpolation'); }, eventAst.handlerSpan);
  15665. var statements = [];
  15666. if (scope) {
  15667. statements.push.apply(statements, __spread(scope.restoreViewStatement()));
  15668. statements.push.apply(statements, __spread(scope.variableDeclarations()));
  15669. }
  15670. statements.push.apply(statements, __spread(bindingExpr.render3Stmts));
  15671. var eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
  15672. var fnName = handlerName && sanitizeIdentifier(handlerName);
  15673. var fnArgs = [new FnParam('$event', DYNAMIC_TYPE)];
  15674. var handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
  15675. var params = [literal(eventName), handlerFn];
  15676. if (target) {
  15677. params.push(literal(false), // `useCapture` flag, defaults to `false`
  15678. importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
  15679. }
  15680. return params;
  15681. }
  15682. var TemplateDefinitionBuilder = /** @class */ (function () {
  15683. function TemplateDefinitionBuilder(constantPool, parentBindingScope, level, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds) {
  15684. var _this = this;
  15685. if (level === void 0) { level = 0; }
  15686. this.constantPool = constantPool;
  15687. this.level = level;
  15688. this.contextName = contextName;
  15689. this.i18nContext = i18nContext;
  15690. this.templateIndex = templateIndex;
  15691. this.templateName = templateName;
  15692. this.directiveMatcher = directiveMatcher;
  15693. this.directives = directives;
  15694. this.pipeTypeByName = pipeTypeByName;
  15695. this.pipes = pipes;
  15696. this._namespace = _namespace;
  15697. this.relativeContextFilePath = relativeContextFilePath;
  15698. this.i18nUseExternalIds = i18nUseExternalIds;
  15699. this._dataIndex = 0;
  15700. this._bindingContext = 0;
  15701. this._prefixCode = [];
  15702. /**
  15703. * List of callbacks to generate creation mode instructions. We store them here as we process
  15704. * the template so bindings in listeners are resolved only once all nodes have been visited.
  15705. * This ensures all local refs and context variables are available for matching.
  15706. */
  15707. this._creationCodeFns = [];
  15708. /**
  15709. * List of callbacks to generate update mode instructions. We store them here as we process
  15710. * the template so bindings are resolved only once all nodes have been visited. This ensures
  15711. * all local refs and context variables are available for matching.
  15712. */
  15713. this._updateCodeFns = [];
  15714. /**
  15715. * Memorizes the last node index for which a select instruction has been generated.
  15716. * We're initializing this to -1 to ensure the `select(0)` instruction is generated before any
  15717. * relevant update instructions.
  15718. */
  15719. this._lastNodeIndexWithFlush = -1;
  15720. /** Temporary variable declarations generated from visiting pipes, literals, etc. */
  15721. this._tempVariables = [];
  15722. /**
  15723. * List of callbacks to build nested templates. Nested templates must not be visited until
  15724. * after the parent template has finished visiting all of its nodes. This ensures that all
  15725. * local ref bindings in nested templates are able to find local ref values if the refs
  15726. * are defined after the template declaration.
  15727. */
  15728. this._nestedTemplateFns = [];
  15729. this._unsupported = unsupported;
  15730. // i18n context local to this template
  15731. this.i18n = null;
  15732. // Number of slots to reserve for pureFunctions
  15733. this._pureFunctionSlots = 0;
  15734. // Number of binding slots
  15735. this._bindingSlots = 0;
  15736. // Projection slots found in the template. Projection slots can distribute projected
  15737. // nodes based on a selector, or can just use the wildcard selector to match
  15738. // all nodes which aren't matching any selector.
  15739. this._ngContentReservedSlots = [];
  15740. // Number of non-default selectors found in all parent templates of this template. We need to
  15741. // track it to properly adjust projection slot index in the `projection` instruction.
  15742. this._ngContentSelectorsOffset = 0;
  15743. // Expression that should be used as implicit receiver when converting template
  15744. // expressions to output AST.
  15745. this._implicitReceiverExpr = null;
  15746. // These should be handled in the template or element directly.
  15747. this.visitReference = invalid$1;
  15748. this.visitVariable = invalid$1;
  15749. this.visitTextAttribute = invalid$1;
  15750. this.visitBoundAttribute = invalid$1;
  15751. this.visitBoundEvent = invalid$1;
  15752. this._bindingScope = parentBindingScope.nestedScope(level);
  15753. // Turn the relative context file path into an identifier by replacing non-alphanumeric
  15754. // characters with underscores.
  15755. this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
  15756. this._valueConverter = new ValueConverter(constantPool, function () { return _this.allocateDataSlot(); }, function (numSlots) { return _this.allocatePureFunctionSlots(numSlots); }, function (name, localName, slot, value) {
  15757. var pipeType = pipeTypeByName.get(name);
  15758. if (pipeType) {
  15759. _this.pipes.add(pipeType);
  15760. }
  15761. _this._bindingScope.set(_this.level, localName, value);
  15762. _this.creationInstruction(null, Identifiers$1.pipe, [literal(slot), literal(name)]);
  15763. });
  15764. }
  15765. TemplateDefinitionBuilder.prototype.registerContextVariables = function (variable$1) {
  15766. var scopedName = this._bindingScope.freshReferenceName();
  15767. var retrievalLevel = this.level;
  15768. var lhs = variable(variable$1.name + scopedName);
  15769. this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, function (scope, relativeLevel) {
  15770. var rhs;
  15771. if (scope.bindingLevel === retrievalLevel) {
  15772. // e.g. ctx
  15773. rhs = variable(CONTEXT_NAME);
  15774. }
  15775. else {
  15776. var sharedCtxVar = scope.getSharedContextName(retrievalLevel);
  15777. // e.g. ctx_r0 OR x(2);
  15778. rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
  15779. }
  15780. // e.g. const $item$ = x(2).$implicit;
  15781. return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
  15782. });
  15783. };
  15784. TemplateDefinitionBuilder.prototype.buildTemplateFunction = function (nodes, variables, ngContentSelectorsOffset, i18n) {
  15785. var _this = this;
  15786. if (ngContentSelectorsOffset === void 0) { ngContentSelectorsOffset = 0; }
  15787. this._ngContentSelectorsOffset = ngContentSelectorsOffset;
  15788. if (this._namespace !== Identifiers$1.namespaceHTML) {
  15789. this.creationInstruction(null, this._namespace);
  15790. }
  15791. // Create variable bindings
  15792. variables.forEach(function (v) { return _this.registerContextVariables(v); });
  15793. // Initiate i18n context in case:
  15794. // - this template has parent i18n context
  15795. // - or the template has i18n meta associated with it,
  15796. // but it's not initiated by the Element (e.g. <ng-template i18n>)
  15797. var initI18nContext = this.i18nContext || (isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
  15798. !(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
  15799. var selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
  15800. if (initI18nContext) {
  15801. this.i18nStart(null, i18n, selfClosingI18nInstruction);
  15802. }
  15803. // This is the initial pass through the nodes of this template. In this pass, we
  15804. // queue all creation mode and update mode instructions for generation in the second
  15805. // pass. It's necessary to separate the passes to ensure local refs are defined before
  15806. // resolving bindings. We also count bindings in this pass as we walk bound expressions.
  15807. visitAll(this, nodes);
  15808. // Add total binding count to pure function count so pure function instructions are
  15809. // generated with the correct slot offset when update instructions are processed.
  15810. this._pureFunctionSlots += this._bindingSlots;
  15811. // Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
  15812. // `pipeBind` update instructions), so we have to update the slot offsets manually
  15813. // to account for bindings.
  15814. this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
  15815. // Nested templates must be processed before creation instructions so template()
  15816. // instructions can be generated with the correct internal const count.
  15817. this._nestedTemplateFns.forEach(function (buildTemplateFn) { return buildTemplateFn(); });
  15818. // Output the `projectionDef` instruction when some `<ng-content>` tags are present.
  15819. // The `projectionDef` instruction is only emitted for the component template and
  15820. // is skipped for nested templates (<ng-template> tags).
  15821. if (this.level === 0 && this._ngContentReservedSlots.length) {
  15822. var parameters = [];
  15823. // By default the `projectionDef` instructions creates one slot for the wildcard
  15824. // selector if no parameters are passed. Therefore we only want to allocate a new
  15825. // array for the projection slots if the default projection slot is not sufficient.
  15826. if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
  15827. var r3ReservedSlots = this._ngContentReservedSlots.map(function (s) { return s !== '*' ? parseSelectorToR3Selector(s) : s; });
  15828. parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
  15829. }
  15830. // Since we accumulate ngContent selectors while processing template elements,
  15831. // we *prepend* `projectionDef` to creation instructions block, to put it before
  15832. // any `projection` instructions
  15833. this.creationInstruction(null, Identifiers$1.projectionDef, parameters, /* prepend */ true);
  15834. }
  15835. if (initI18nContext) {
  15836. this.i18nEnd(null, selfClosingI18nInstruction);
  15837. }
  15838. // Generate all the creation mode instructions (e.g. resolve bindings in listeners)
  15839. var creationStatements = this._creationCodeFns.map(function (fn) { return fn(); });
  15840. // Generate all the update mode instructions (e.g. resolve property or text bindings)
  15841. var updateStatements = this._updateCodeFns.map(function (fn) { return fn(); });
  15842. // Variable declaration must occur after binding resolution so we can generate context
  15843. // instructions that build on each other.
  15844. // e.g. const b = nextContext().$implicit(); const b = nextContext();
  15845. var creationVariables = this._bindingScope.viewSnapshotStatements();
  15846. var updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
  15847. var creationBlock = creationStatements.length > 0 ?
  15848. [renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
  15849. [];
  15850. var updateBlock = updateStatements.length > 0 ?
  15851. [renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
  15852. [];
  15853. return fn(
  15854. // i.e. (rf: RenderFlags, ctx: any)
  15855. [new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], __spread(this._prefixCode, creationBlock, updateBlock), INFERRED_TYPE, null, this.templateName);
  15856. };
  15857. // LocalResolver
  15858. TemplateDefinitionBuilder.prototype.getLocal = function (name) { return this._bindingScope.get(name); };
  15859. // LocalResolver
  15860. TemplateDefinitionBuilder.prototype.notifyImplicitReceiverUse = function () { this._bindingScope.notifyImplicitReceiverUse(); };
  15861. TemplateDefinitionBuilder.prototype.i18nTranslate = function (message, params, ref, transformFn) {
  15862. var _a;
  15863. if (params === void 0) { params = {}; }
  15864. var _ref = ref || variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  15865. // Closure Compiler requires const names to start with `MSG_` but disallows any other const to
  15866. // start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
  15867. var closureVar = this.i18nGenerateClosureVar(message.id);
  15868. var _params = {};
  15869. if (params && Object.keys(params).length) {
  15870. Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key)] = params[key]; });
  15871. }
  15872. var meta = metaFromI18nMessage(message);
  15873. var content = getSerializedI18nContent(message);
  15874. var statements = getTranslationDeclStmts(_ref, closureVar, content, meta, _params, transformFn);
  15875. (_a = this.constantPool.statements).push.apply(_a, __spread(statements));
  15876. return _ref;
  15877. };
  15878. TemplateDefinitionBuilder.prototype.i18nAppendBindings = function (expressions) {
  15879. var _this = this;
  15880. if (expressions.length > 0) {
  15881. expressions.forEach(function (expression) { return _this.i18n.appendBinding(expression); });
  15882. }
  15883. };
  15884. TemplateDefinitionBuilder.prototype.i18nBindProps = function (props) {
  15885. var _this = this;
  15886. var bound = {};
  15887. Object.keys(props).forEach(function (key) {
  15888. var prop = props[key];
  15889. if (prop instanceof Text) {
  15890. bound[key] = literal(prop.value);
  15891. }
  15892. else {
  15893. var value = prop.value.visit(_this._valueConverter);
  15894. _this.allocateBindingSlots(value);
  15895. if (value instanceof Interpolation) {
  15896. var strings = value.strings, expressions = value.expressions;
  15897. var _a = _this.i18n, id = _a.id, bindings = _a.bindings;
  15898. var label = assembleI18nBoundString(strings, bindings.size, id);
  15899. _this.i18nAppendBindings(expressions);
  15900. bound[key] = literal(label);
  15901. }
  15902. }
  15903. });
  15904. return bound;
  15905. };
  15906. TemplateDefinitionBuilder.prototype.i18nGenerateClosureVar = function (messageId) {
  15907. var name;
  15908. var suffix = this.fileBasedI18nSuffix.toUpperCase();
  15909. if (this.i18nUseExternalIds) {
  15910. var prefix = getTranslationConstPrefix("EXTERNAL_");
  15911. var uniqueSuffix = this.constantPool.uniqueName(suffix);
  15912. name = "" + prefix + sanitizeIdentifier(messageId) + "$$" + uniqueSuffix;
  15913. }
  15914. else {
  15915. var prefix = getTranslationConstPrefix(suffix);
  15916. name = this.constantPool.uniqueName(prefix);
  15917. }
  15918. return variable(name);
  15919. };
  15920. TemplateDefinitionBuilder.prototype.i18nUpdateRef = function (context) {
  15921. var icus = context.icus, meta = context.meta, isRoot = context.isRoot, isResolved = context.isResolved, isEmitted = context.isEmitted;
  15922. if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
  15923. context.isEmitted = true;
  15924. var placeholders = context.getSerializedPlaceholders();
  15925. var icuMapping_1 = {};
  15926. var params_1 = placeholders.size ? placeholdersToParams(placeholders) : {};
  15927. if (icus.size) {
  15928. icus.forEach(function (refs, key) {
  15929. if (refs.length === 1) {
  15930. // if we have one ICU defined for a given
  15931. // placeholder - just output its reference
  15932. params_1[key] = refs[0];
  15933. }
  15934. else {
  15935. // ... otherwise we need to activate post-processing
  15936. // to replace ICU placeholders with proper values
  15937. var placeholder = wrapI18nPlaceholder("" + I18N_ICU_MAPPING_PREFIX + key);
  15938. params_1[key] = literal(placeholder);
  15939. icuMapping_1[key] = literalArr(refs);
  15940. }
  15941. });
  15942. }
  15943. // translation requires post processing in 2 cases:
  15944. // - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
  15945. // - if we have multiple ICUs that refer to the same placeholder name
  15946. var needsPostprocessing = Array.from(placeholders.values()).some(function (value) { return value.length > 1; }) ||
  15947. Object.keys(icuMapping_1).length;
  15948. var transformFn = void 0;
  15949. if (needsPostprocessing) {
  15950. transformFn = function (raw) {
  15951. var args = [raw];
  15952. if (Object.keys(icuMapping_1).length) {
  15953. args.push(mapLiteral(icuMapping_1, true));
  15954. }
  15955. return instruction(null, Identifiers$1.i18nPostprocess, args);
  15956. };
  15957. }
  15958. this.i18nTranslate(meta, params_1, context.ref, transformFn);
  15959. }
  15960. };
  15961. TemplateDefinitionBuilder.prototype.i18nStart = function (span, meta, selfClosing) {
  15962. if (span === void 0) { span = null; }
  15963. var index = this.allocateDataSlot();
  15964. if (this.i18nContext) {
  15965. this.i18n = this.i18nContext.forkChildContext(index, this.templateIndex, meta);
  15966. }
  15967. else {
  15968. var ref_1 = variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  15969. this.i18n = new I18nContext(index, ref_1, 0, this.templateIndex, meta);
  15970. }
  15971. // generate i18nStart instruction
  15972. var _a = this.i18n, id = _a.id, ref = _a.ref;
  15973. var params = [literal(index), ref];
  15974. if (id > 0) {
  15975. // do not push 3rd argument (sub-block id)
  15976. // into i18nStart call for top level i18n context
  15977. params.push(literal(id));
  15978. }
  15979. this.creationInstruction(span, selfClosing ? Identifiers$1.i18n : Identifiers$1.i18nStart, params);
  15980. };
  15981. TemplateDefinitionBuilder.prototype.i18nEnd = function (span, selfClosing) {
  15982. var _this = this;
  15983. if (span === void 0) { span = null; }
  15984. if (!this.i18n) {
  15985. throw new Error('i18nEnd is executed with no i18n context present');
  15986. }
  15987. if (this.i18nContext) {
  15988. this.i18nContext.reconcileChildContext(this.i18n);
  15989. this.i18nUpdateRef(this.i18nContext);
  15990. }
  15991. else {
  15992. this.i18nUpdateRef(this.i18n);
  15993. }
  15994. // setup accumulated bindings
  15995. var _a = this.i18n, index = _a.index, bindings = _a.bindings;
  15996. if (bindings.size) {
  15997. var chainBindings_1 = [];
  15998. bindings.forEach(function (binding) {
  15999. chainBindings_1.push({ sourceSpan: span, value: function () { return _this.convertPropertyBinding(binding); } });
  16000. });
  16001. this.updateInstructionChain(index, Identifiers$1.i18nExp, chainBindings_1);
  16002. this.updateInstruction(index, span, Identifiers$1.i18nApply, [literal(index)]);
  16003. }
  16004. if (!selfClosing) {
  16005. this.creationInstruction(span, Identifiers$1.i18nEnd);
  16006. }
  16007. this.i18n = null; // reset local i18n context
  16008. };
  16009. TemplateDefinitionBuilder.prototype.visitContent = function (ngContent) {
  16010. var slot = this.allocateDataSlot();
  16011. var projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
  16012. var parameters = [literal(slot)];
  16013. var attributes = [];
  16014. this._ngContentReservedSlots.push(ngContent.selector);
  16015. ngContent.attributes.forEach(function (attribute) {
  16016. var name = attribute.name, value = attribute.value;
  16017. if (name === NG_PROJECT_AS_ATTR_NAME) {
  16018. attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attribute)));
  16019. }
  16020. else if (name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1) {
  16021. attributes.push(literal(name), literal(value));
  16022. }
  16023. });
  16024. if (attributes.length > 0) {
  16025. parameters.push(literal(projectionSlotIdx), literalArr(attributes));
  16026. }
  16027. else if (projectionSlotIdx !== 0) {
  16028. parameters.push(literal(projectionSlotIdx));
  16029. }
  16030. this.creationInstruction(ngContent.sourceSpan, Identifiers$1.projection, parameters);
  16031. if (this.i18n) {
  16032. this.i18n.appendProjection(ngContent.i18n, slot);
  16033. }
  16034. };
  16035. TemplateDefinitionBuilder.prototype.getNamespaceInstruction = function (namespaceKey) {
  16036. switch (namespaceKey) {
  16037. case 'math':
  16038. return Identifiers$1.namespaceMathML;
  16039. case 'svg':
  16040. return Identifiers$1.namespaceSVG;
  16041. default:
  16042. return Identifiers$1.namespaceHTML;
  16043. }
  16044. };
  16045. TemplateDefinitionBuilder.prototype.addNamespaceInstruction = function (nsInstruction, element) {
  16046. this._namespace = nsInstruction;
  16047. this.creationInstruction(element.sourceSpan, nsInstruction);
  16048. };
  16049. TemplateDefinitionBuilder.prototype.visitElement = function (element) {
  16050. var _this = this;
  16051. var e_1, _a;
  16052. var elementIndex = this.allocateDataSlot();
  16053. var stylingBuilder = new StylingBuilder(literal(elementIndex), null);
  16054. var isNonBindableMode = false;
  16055. var isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
  16056. if (isI18nRootElement && this.i18n) {
  16057. throw new Error("Could not mark an element as translatable inside of a translatable section");
  16058. }
  16059. var i18nAttrs = [];
  16060. var outputAttrs = [];
  16061. var _b = __read(splitNsName(element.name), 2), namespaceKey = _b[0], elementName = _b[1];
  16062. var isNgContainer$1 = isNgContainer(element.name);
  16063. try {
  16064. // Handle styling, i18n, ngNonBindable attributes
  16065. for (var _c = __values(element.attributes), _d = _c.next(); !_d.done; _d = _c.next()) {
  16066. var attr = _d.value;
  16067. var name_1 = attr.name, value = attr.value;
  16068. if (name_1 === NON_BINDABLE_ATTR) {
  16069. isNonBindableMode = true;
  16070. }
  16071. else if (name_1 === 'style') {
  16072. stylingBuilder.registerStyleAttr(value);
  16073. }
  16074. else if (name_1 === 'class') {
  16075. stylingBuilder.registerClassAttr(value);
  16076. }
  16077. else {
  16078. if (attr.i18n) {
  16079. // Place attributes into a separate array for i18n processing, but also keep such
  16080. // attributes in the main list to make them available for directive matching at runtime.
  16081. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  16082. // arguments
  16083. i18nAttrs.push(attr);
  16084. }
  16085. else {
  16086. outputAttrs.push(attr);
  16087. }
  16088. }
  16089. }
  16090. }
  16091. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  16092. finally {
  16093. try {
  16094. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  16095. }
  16096. finally { if (e_1) throw e_1.error; }
  16097. }
  16098. // Match directives on non i18n attributes
  16099. this.matchDirectives(element.name, element);
  16100. // Regular element or ng-container creation mode
  16101. var parameters = [literal(elementIndex)];
  16102. if (!isNgContainer$1) {
  16103. parameters.push(literal(elementName));
  16104. }
  16105. // Add the attributes
  16106. var attributes = [];
  16107. var allOtherInputs = [];
  16108. element.inputs.forEach(function (input) {
  16109. var stylingInputWasSet = stylingBuilder.registerBoundInput(input);
  16110. if (!stylingInputWasSet) {
  16111. if (input.type === 0 /* Property */ && input.i18n) {
  16112. // Place attributes into a separate array for i18n processing, but also keep such
  16113. // attributes in the main list to make them available for directive matching at runtime.
  16114. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  16115. // arguments
  16116. i18nAttrs.push(input);
  16117. }
  16118. else {
  16119. allOtherInputs.push(input);
  16120. }
  16121. }
  16122. });
  16123. outputAttrs.forEach(function (attr) {
  16124. if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
  16125. attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attr)));
  16126. }
  16127. else {
  16128. attributes.push.apply(attributes, __spread(getAttributeNameLiterals(attr.name), [literal(attr.value)]));
  16129. }
  16130. });
  16131. // add attributes for directive and projection matching purposes
  16132. attributes.push.apply(attributes, __spread(this.prepareNonRenderAttrs(allOtherInputs, element.outputs, stylingBuilder, [], i18nAttrs)));
  16133. parameters.push(this.toAttrsParam(attributes));
  16134. // local refs (ex.: <div #foo #bar="baz">)
  16135. parameters.push(this.prepareRefsParameter(element.references));
  16136. var wasInNamespace = this._namespace;
  16137. var currentNamespace = this.getNamespaceInstruction(namespaceKey);
  16138. // If the namespace is changing now, include an instruction to change it
  16139. // during element creation.
  16140. if (currentNamespace !== wasInNamespace) {
  16141. this.addNamespaceInstruction(currentNamespace, element);
  16142. }
  16143. if (this.i18n) {
  16144. this.i18n.appendElement(element.i18n, elementIndex);
  16145. }
  16146. var hasChildren = function () {
  16147. if (!isI18nRootElement && _this.i18n) {
  16148. // we do not append text node instructions and ICUs inside i18n section,
  16149. // so we exclude them while calculating whether current element has children
  16150. return !hasTextChildrenOnly(element.children);
  16151. }
  16152. return element.children.length > 0;
  16153. };
  16154. var createSelfClosingInstruction = !stylingBuilder.hasBindings && !isNgContainer$1 &&
  16155. element.outputs.length === 0 && i18nAttrs.length === 0 && !hasChildren();
  16156. var createSelfClosingI18nInstruction = !createSelfClosingInstruction &&
  16157. !stylingBuilder.hasBindings && hasTextChildrenOnly(element.children);
  16158. if (createSelfClosingInstruction) {
  16159. this.creationInstruction(element.sourceSpan, Identifiers$1.element, trimTrailingNulls(parameters));
  16160. }
  16161. else {
  16162. this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainerStart : Identifiers$1.elementStart, trimTrailingNulls(parameters));
  16163. if (isNonBindableMode) {
  16164. this.creationInstruction(element.sourceSpan, Identifiers$1.disableBindings);
  16165. }
  16166. // process i18n element attributes
  16167. if (i18nAttrs.length) {
  16168. var hasBindings_1 = false;
  16169. var i18nAttrArgs_1 = [];
  16170. var bindings_1 = [];
  16171. i18nAttrs.forEach(function (attr) {
  16172. var message = attr.i18n;
  16173. if (attr instanceof TextAttribute) {
  16174. i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message));
  16175. }
  16176. else {
  16177. var converted = attr.value.visit(_this._valueConverter);
  16178. _this.allocateBindingSlots(converted);
  16179. if (converted instanceof Interpolation) {
  16180. var placeholders = assembleBoundTextPlaceholders(message);
  16181. var params = placeholdersToParams(placeholders);
  16182. i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message, params));
  16183. converted.expressions.forEach(function (expression) {
  16184. hasBindings_1 = true;
  16185. bindings_1.push({
  16186. sourceSpan: element.sourceSpan,
  16187. value: function () { return _this.convertExpressionBinding(expression); }
  16188. });
  16189. });
  16190. }
  16191. }
  16192. });
  16193. if (bindings_1.length) {
  16194. this.updateInstructionChain(elementIndex, Identifiers$1.i18nExp, bindings_1);
  16195. }
  16196. if (i18nAttrArgs_1.length) {
  16197. var index = literal(this.allocateDataSlot());
  16198. var args = this.constantPool.getConstLiteral(literalArr(i18nAttrArgs_1), true);
  16199. this.creationInstruction(element.sourceSpan, Identifiers$1.i18nAttributes, [index, args]);
  16200. if (hasBindings_1) {
  16201. this.updateInstruction(elementIndex, element.sourceSpan, Identifiers$1.i18nApply, [index]);
  16202. }
  16203. }
  16204. }
  16205. // The style bindings code is placed into two distinct blocks within the template function AOT
  16206. // code: creation and update. The creation code contains the `styling` instructions
  16207. // which will apply the collected binding values to the element. `styling` is
  16208. // designed to run inside of `elementStart` and `elementEnd`. The update instructions
  16209. // (things like `styleProp`, `classProp`, etc..) are applied later on in this
  16210. // file
  16211. this.processStylingInstruction(elementIndex, stylingBuilder.buildStylingInstruction(element.sourceSpan, this.constantPool), true);
  16212. // Generate Listeners (outputs)
  16213. element.outputs.forEach(function (outputAst) {
  16214. _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter(element.name, outputAst, elementIndex));
  16215. });
  16216. // Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
  16217. // listeners, to make sure i18nAttributes instruction targets current element at runtime.
  16218. if (isI18nRootElement) {
  16219. this.i18nStart(element.sourceSpan, element.i18n, createSelfClosingI18nInstruction);
  16220. }
  16221. }
  16222. // the code here will collect all update-level styling instructions and add them to the
  16223. // update block of the template function AOT code. Instructions like `styleProp`,
  16224. // `styleMap`, `classMap`, `classProp` and `stylingApply`
  16225. // are all generated and assigned in the code below.
  16226. var stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
  16227. var limit = stylingInstructions.length - 1;
  16228. for (var i = 0; i <= limit; i++) {
  16229. var instruction_1 = stylingInstructions[i];
  16230. this._bindingSlots += instruction_1.allocateBindingSlots;
  16231. this.processStylingInstruction(elementIndex, instruction_1, false);
  16232. }
  16233. // the reason why `undefined` is used is because the renderer understands this as a
  16234. // special value to symbolize that there is no RHS to this binding
  16235. // TODO (matsko): revisit this once FW-959 is approached
  16236. var emptyValueBindInstruction = literal(undefined);
  16237. var propertyBindings = [];
  16238. var attributeBindings = [];
  16239. // Generate element input bindings
  16240. allOtherInputs.forEach(function (input) {
  16241. var inputType = input.type;
  16242. if (inputType === 4 /* Animation */) {
  16243. var value_1 = input.value.visit(_this._valueConverter);
  16244. // animation bindings can be presented in the following formats:
  16245. // 1. [@binding]="fooExp"
  16246. // 2. [@binding]="{value:fooExp, params:{...}}"
  16247. // 3. [@binding]
  16248. // 4. @binding
  16249. // All formats will be valid for when a synthetic binding is created.
  16250. // The reasoning for this is because the renderer should get each
  16251. // synthetic binding value in the order of the array that they are
  16252. // defined in...
  16253. var hasValue_1 = value_1 instanceof LiteralPrimitive ? !!value_1.value : true;
  16254. _this.allocateBindingSlots(value_1);
  16255. propertyBindings.push({
  16256. name: prepareSyntheticPropertyName(input.name),
  16257. sourceSpan: input.sourceSpan,
  16258. value: function () { return hasValue_1 ? _this.convertPropertyBinding(value_1) : emptyValueBindInstruction; }
  16259. });
  16260. }
  16261. else {
  16262. // we must skip attributes with associated i18n context, since these attributes are handled
  16263. // separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
  16264. if (input.i18n)
  16265. return;
  16266. var value_2 = input.value.visit(_this._valueConverter);
  16267. if (value_2 !== undefined) {
  16268. var params_2 = [];
  16269. var _a = __read(splitNsName(input.name), 2), attrNamespace = _a[0], attrName_1 = _a[1];
  16270. var isAttributeBinding = inputType === 1 /* Attribute */;
  16271. var sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
  16272. if (sanitizationRef)
  16273. params_2.push(sanitizationRef);
  16274. if (attrNamespace) {
  16275. var namespaceLiteral = literal(attrNamespace);
  16276. if (sanitizationRef) {
  16277. params_2.push(namespaceLiteral);
  16278. }
  16279. else {
  16280. // If there wasn't a sanitization ref, we need to add
  16281. // an extra param so that we can pass in the namespace.
  16282. params_2.push(literal(null), namespaceLiteral);
  16283. }
  16284. }
  16285. _this.allocateBindingSlots(value_2);
  16286. if (inputType === 0 /* Property */) {
  16287. if (value_2 instanceof Interpolation) {
  16288. // prop="{{value}}" and friends
  16289. _this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  16290. }
  16291. else {
  16292. // [prop]="value"
  16293. // Collect all the properties so that we can chain into a single function at the end.
  16294. propertyBindings.push({
  16295. name: attrName_1,
  16296. sourceSpan: input.sourceSpan,
  16297. value: function () { return _this.convertPropertyBinding(value_2); }, params: params_2
  16298. });
  16299. }
  16300. }
  16301. else if (inputType === 1 /* Attribute */) {
  16302. if (value_2 instanceof Interpolation && getInterpolationArgsLength(value_2) > 1) {
  16303. // attr.name="text{{value}}" and friends
  16304. _this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  16305. }
  16306. else {
  16307. var boundValue_1 = value_2 instanceof Interpolation ? value_2.expressions[0] : value_2;
  16308. // [attr.name]="value" or attr.name="{{value}}"
  16309. // Collect the attribute bindings so that they can be chained at the end.
  16310. attributeBindings.push({
  16311. name: attrName_1,
  16312. sourceSpan: input.sourceSpan,
  16313. value: function () { return _this.convertPropertyBinding(boundValue_1); }, params: params_2
  16314. });
  16315. }
  16316. }
  16317. else {
  16318. // class prop
  16319. _this.updateInstruction(elementIndex, input.sourceSpan, Identifiers$1.classProp, function () {
  16320. return __spread([
  16321. literal(elementIndex), literal(attrName_1), _this.convertPropertyBinding(value_2)
  16322. ], params_2);
  16323. });
  16324. }
  16325. }
  16326. }
  16327. });
  16328. if (propertyBindings.length > 0) {
  16329. this.updateInstructionChain(elementIndex, Identifiers$1.property, propertyBindings);
  16330. }
  16331. if (attributeBindings.length > 0) {
  16332. this.updateInstructionChain(elementIndex, Identifiers$1.attribute, attributeBindings);
  16333. }
  16334. // Traverse element child nodes
  16335. visitAll(this, element.children);
  16336. if (!isI18nRootElement && this.i18n) {
  16337. this.i18n.appendElement(element.i18n, elementIndex, true);
  16338. }
  16339. if (!createSelfClosingInstruction) {
  16340. // Finish element construction mode.
  16341. var span = element.endSourceSpan || element.sourceSpan;
  16342. if (isI18nRootElement) {
  16343. this.i18nEnd(span, createSelfClosingI18nInstruction);
  16344. }
  16345. if (isNonBindableMode) {
  16346. this.creationInstruction(span, Identifiers$1.enableBindings);
  16347. }
  16348. this.creationInstruction(span, isNgContainer$1 ? Identifiers$1.elementContainerEnd : Identifiers$1.elementEnd);
  16349. }
  16350. };
  16351. /**
  16352. * Adds an update instruction for an interpolated property or attribute, such as
  16353. * `prop="{{value}}"` or `attr.title="{{value}}"`
  16354. */
  16355. TemplateDefinitionBuilder.prototype.interpolatedUpdateInstruction = function (instruction, elementIndex, attrName, input, value, params) {
  16356. var _this = this;
  16357. this.updateInstruction(elementIndex, input.sourceSpan, instruction, function () { return __spread([literal(attrName)], _this.getUpdateInstructionArguments(value), params); });
  16358. };
  16359. TemplateDefinitionBuilder.prototype.visitTemplate = function (template) {
  16360. var _this = this;
  16361. var NG_TEMPLATE_TAG_NAME = 'ng-template';
  16362. var templateIndex = this.allocateDataSlot();
  16363. if (this.i18n) {
  16364. this.i18n.appendTemplate(template.i18n, templateIndex);
  16365. }
  16366. var tagName = sanitizeIdentifier(template.tagName || '');
  16367. var contextName = "" + this.contextName + (tagName ? '_' + tagName : '') + "_" + templateIndex;
  16368. var templateName = contextName + "_Template";
  16369. var parameters = [
  16370. literal(templateIndex),
  16371. variable(templateName),
  16372. // We don't care about the tag's namespace here, because we infer
  16373. // it based on the parent nodes inside the template instruction.
  16374. literal(template.tagName ? splitNsName(template.tagName)[1] : template.tagName),
  16375. ];
  16376. // find directives matching on a given <ng-template> node
  16377. this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
  16378. // prepare attributes parameter (including attributes used for directive matching)
  16379. var attrsExprs = [];
  16380. template.attributes.forEach(function (a) { attrsExprs.push(asLiteral(a.name), asLiteral(a.value)); });
  16381. attrsExprs.push.apply(attrsExprs, __spread(this.prepareNonRenderAttrs(template.inputs, template.outputs, undefined, template.templateAttrs)));
  16382. parameters.push(this.toAttrsParam(attrsExprs));
  16383. // local refs (ex.: <ng-template #foo>)
  16384. if (template.references && template.references.length) {
  16385. parameters.push(this.prepareRefsParameter(template.references));
  16386. parameters.push(importExpr(Identifiers$1.templateRefExtractor));
  16387. }
  16388. // Create the template function
  16389. var templateVisitor = new TemplateDefinitionBuilder(this.constantPool, this._bindingScope, this.level + 1, contextName, this.i18n, templateIndex, templateName, this.directiveMatcher, this.directives, this.pipeTypeByName, this.pipes, this._namespace, this.fileBasedI18nSuffix, this.i18nUseExternalIds);
  16390. // Nested templates must not be visited until after their parent templates have completed
  16391. // processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
  16392. // be able to support bindings in nested templates to local refs that occur after the
  16393. // template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
  16394. this._nestedTemplateFns.push(function () {
  16395. var _a;
  16396. var templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, _this._ngContentReservedSlots.length + _this._ngContentSelectorsOffset, template.i18n);
  16397. _this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName, null));
  16398. if (templateVisitor._ngContentReservedSlots.length) {
  16399. (_a = _this._ngContentReservedSlots).push.apply(_a, __spread(templateVisitor._ngContentReservedSlots));
  16400. }
  16401. });
  16402. // e.g. template(1, MyComp_Template_1)
  16403. this.creationInstruction(template.sourceSpan, Identifiers$1.templateCreate, function () {
  16404. parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
  16405. return trimTrailingNulls(parameters);
  16406. });
  16407. // handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
  16408. this.templatePropertyBindings(templateIndex, template.templateAttrs);
  16409. // Only add normal input/output binding instructions on explicit ng-template elements.
  16410. if (template.tagName === NG_TEMPLATE_TAG_NAME) {
  16411. // Add the input bindings
  16412. this.templatePropertyBindings(templateIndex, template.inputs);
  16413. // Generate listeners for directive output
  16414. template.outputs.forEach(function (outputAst) {
  16415. _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter('ng_template', outputAst, templateIndex));
  16416. });
  16417. }
  16418. };
  16419. TemplateDefinitionBuilder.prototype.visitBoundText = function (text) {
  16420. var _this = this;
  16421. if (this.i18n) {
  16422. var value_3 = text.value.visit(this._valueConverter);
  16423. this.allocateBindingSlots(value_3);
  16424. if (value_3 instanceof Interpolation) {
  16425. this.i18n.appendBoundText(text.i18n);
  16426. this.i18nAppendBindings(value_3.expressions);
  16427. }
  16428. return;
  16429. }
  16430. var nodeIndex = this.allocateDataSlot();
  16431. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(nodeIndex)]);
  16432. var value = text.value.visit(this._valueConverter);
  16433. this.allocateBindingSlots(value);
  16434. if (value instanceof Interpolation) {
  16435. this.updateInstruction(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), function () { return _this.getUpdateInstructionArguments(value); });
  16436. }
  16437. else {
  16438. this.updateInstruction(nodeIndex, text.sourceSpan, Identifiers$1.textBinding, function () { return [_this.convertPropertyBinding(value)]; });
  16439. }
  16440. };
  16441. TemplateDefinitionBuilder.prototype.visitText = function (text) {
  16442. // when a text element is located within a translatable
  16443. // block, we exclude this text element from instructions set,
  16444. // since it will be captured in i18n content and processed at runtime
  16445. if (!this.i18n) {
  16446. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(this.allocateDataSlot()), literal(text.value)]);
  16447. }
  16448. };
  16449. TemplateDefinitionBuilder.prototype.visitIcu = function (icu) {
  16450. var initWasInvoked = false;
  16451. // if an ICU was created outside of i18n block, we still treat
  16452. // it as a translatable entity and invoke i18nStart and i18nEnd
  16453. // to generate i18n context and the necessary instructions
  16454. if (!this.i18n) {
  16455. initWasInvoked = true;
  16456. this.i18nStart(null, icu.i18n, true);
  16457. }
  16458. var i18n = this.i18n;
  16459. var vars = this.i18nBindProps(icu.vars);
  16460. var placeholders = this.i18nBindProps(icu.placeholders);
  16461. // output ICU directly and keep ICU reference in context
  16462. var message = icu.i18n;
  16463. var transformFn = function (raw) {
  16464. return instruction(null, Identifiers$1.i18nPostprocess, [raw, mapLiteral(vars, true)]);
  16465. };
  16466. // in case the whole i18n message is a single ICU - we do not need to
  16467. // create a separate top-level translation, we can use the root ref instead
  16468. // and make this ICU a top-level translation
  16469. if (isSingleI18nIcu(i18n.meta)) {
  16470. this.i18nTranslate(message, placeholders, i18n.ref, transformFn);
  16471. }
  16472. else {
  16473. // output ICU directly and keep ICU reference in context
  16474. var ref = this.i18nTranslate(message, placeholders, undefined, transformFn);
  16475. i18n.appendIcu(icuFromI18nMessage(message).name, ref);
  16476. }
  16477. if (initWasInvoked) {
  16478. this.i18nEnd(null, true);
  16479. }
  16480. return null;
  16481. };
  16482. TemplateDefinitionBuilder.prototype.allocateDataSlot = function () { return this._dataIndex++; };
  16483. TemplateDefinitionBuilder.prototype.getConstCount = function () { return this._dataIndex; };
  16484. TemplateDefinitionBuilder.prototype.getVarCount = function () { return this._pureFunctionSlots; };
  16485. TemplateDefinitionBuilder.prototype.getNgContentSelectors = function () {
  16486. return this._ngContentReservedSlots.length ?
  16487. this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
  16488. null;
  16489. };
  16490. TemplateDefinitionBuilder.prototype.bindingContext = function () { return "" + this._bindingContext++; };
  16491. TemplateDefinitionBuilder.prototype.templatePropertyBindings = function (templateIndex, attrs) {
  16492. var _this = this;
  16493. var propertyBindings = [];
  16494. attrs.forEach(function (input) {
  16495. if (input instanceof BoundAttribute) {
  16496. var value_4 = input.value.visit(_this._valueConverter);
  16497. if (value_4 !== undefined) {
  16498. _this.allocateBindingSlots(value_4);
  16499. propertyBindings.push({
  16500. name: input.name,
  16501. sourceSpan: input.sourceSpan,
  16502. value: function () { return _this.convertPropertyBinding(value_4); }
  16503. });
  16504. }
  16505. }
  16506. });
  16507. if (propertyBindings.length > 0) {
  16508. this.updateInstructionChain(templateIndex, Identifiers$1.property, propertyBindings);
  16509. }
  16510. };
  16511. // Bindings must only be resolved after all local refs have been visited, so all
  16512. // instructions are queued in callbacks that execute once the initial pass has completed.
  16513. // Otherwise, we wouldn't be able to support local refs that are defined after their
  16514. // bindings. e.g. {{ foo }} <div #foo></div>
  16515. TemplateDefinitionBuilder.prototype.instructionFn = function (fns, span, reference, paramsOrFn, prepend) {
  16516. if (prepend === void 0) { prepend = false; }
  16517. fns[prepend ? 'unshift' : 'push'](function () {
  16518. var params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
  16519. return instruction(span, reference, params).toStmt();
  16520. });
  16521. };
  16522. TemplateDefinitionBuilder.prototype.processStylingInstruction = function (elementIndex, instruction, createMode) {
  16523. var _this = this;
  16524. if (instruction) {
  16525. var paramsFn = function () { return instruction.buildParams(function (value) { return _this.convertPropertyBinding(value); }); };
  16526. if (createMode) {
  16527. this.creationInstruction(instruction.sourceSpan, instruction.reference, paramsFn);
  16528. }
  16529. else {
  16530. this.updateInstruction(elementIndex, instruction.sourceSpan, instruction.reference, paramsFn);
  16531. }
  16532. }
  16533. };
  16534. TemplateDefinitionBuilder.prototype.creationInstruction = function (span, reference, paramsOrFn, prepend) {
  16535. this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
  16536. };
  16537. TemplateDefinitionBuilder.prototype.updateInstruction = function (nodeIndex, span, reference, paramsOrFn) {
  16538. this.addSelectInstructionIfNecessary(nodeIndex, span);
  16539. this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
  16540. };
  16541. TemplateDefinitionBuilder.prototype.updateInstructionChain = function (nodeIndex, reference, bindings) {
  16542. var span = bindings.length ? bindings[0].sourceSpan : null;
  16543. this.addSelectInstructionIfNecessary(nodeIndex, span);
  16544. this._updateCodeFns.push(function () {
  16545. var calls = bindings.map(function (property) {
  16546. var fnParams = __spread([property.value()], (property.params || []));
  16547. if (property.name) {
  16548. fnParams.unshift(literal(property.name));
  16549. }
  16550. return fnParams;
  16551. });
  16552. return chainedInstruction(span, reference, calls).toStmt();
  16553. });
  16554. };
  16555. TemplateDefinitionBuilder.prototype.addSelectInstructionIfNecessary = function (nodeIndex, span) {
  16556. if (this._lastNodeIndexWithFlush < nodeIndex) {
  16557. if (nodeIndex > 0) {
  16558. this.instructionFn(this._updateCodeFns, span, Identifiers$1.select, [literal(nodeIndex)]);
  16559. }
  16560. this._lastNodeIndexWithFlush = nodeIndex;
  16561. }
  16562. };
  16563. TemplateDefinitionBuilder.prototype.allocatePureFunctionSlots = function (numSlots) {
  16564. var originalSlots = this._pureFunctionSlots;
  16565. this._pureFunctionSlots += numSlots;
  16566. return originalSlots;
  16567. };
  16568. TemplateDefinitionBuilder.prototype.allocateBindingSlots = function (value) {
  16569. this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
  16570. };
  16571. /**
  16572. * Gets an expression that refers to the implicit receiver. The implicit
  16573. * receiver is always the root level context.
  16574. */
  16575. TemplateDefinitionBuilder.prototype.getImplicitReceiverExpr = function () {
  16576. if (this._implicitReceiverExpr) {
  16577. return this._implicitReceiverExpr;
  16578. }
  16579. return this._implicitReceiverExpr = this.level === 0 ?
  16580. variable(CONTEXT_NAME) :
  16581. this._bindingScope.getOrCreateSharedContextVar(0);
  16582. };
  16583. TemplateDefinitionBuilder.prototype.convertExpressionBinding = function (value) {
  16584. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple);
  16585. return convertedPropertyBinding.currValExpr;
  16586. };
  16587. TemplateDefinitionBuilder.prototype.convertPropertyBinding = function (value) {
  16588. var _a;
  16589. var interpolationFn = value instanceof Interpolation ? interpolate : function () { return error('Unexpected interpolation'); };
  16590. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple, interpolationFn);
  16591. var valExpr = convertedPropertyBinding.currValExpr;
  16592. (_a = this._tempVariables).push.apply(_a, __spread(convertedPropertyBinding.stmts));
  16593. return valExpr;
  16594. };
  16595. /**
  16596. * Gets a list of argument expressions to pass to an update instruction expression. Also updates
  16597. * the temp variables state with temp variables that were identified as needing to be created
  16598. * while visiting the arguments.
  16599. * @param value The original expression we will be resolving an arguments list from.
  16600. */
  16601. TemplateDefinitionBuilder.prototype.getUpdateInstructionArguments = function (value) {
  16602. var _a;
  16603. var _b = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext()), args = _b.args, stmts = _b.stmts;
  16604. (_a = this._tempVariables).push.apply(_a, __spread(stmts));
  16605. return args;
  16606. };
  16607. TemplateDefinitionBuilder.prototype.matchDirectives = function (tagName, elOrTpl) {
  16608. var _this = this;
  16609. if (this.directiveMatcher) {
  16610. var selector = createCssSelector(tagName, getAttrsForDirectiveMatching(elOrTpl));
  16611. this.directiveMatcher.match(selector, function (cssSelector, staticType) { _this.directives.add(staticType); });
  16612. }
  16613. };
  16614. /**
  16615. * Prepares all attribute expression values for the `TAttributes` array.
  16616. *
  16617. * The purpose of this function is to properly construct an attributes array that
  16618. * is passed into the `elementStart` (or just `element`) functions. Because there
  16619. * are many different types of attributes, the array needs to be constructed in a
  16620. * special way so that `elementStart` can properly evaluate them.
  16621. *
  16622. * The format looks like this:
  16623. *
  16624. * ```
  16625. * attrs = [prop, value, prop2, value2,
  16626. * CLASSES, class1, class2,
  16627. * STYLES, style1, value1, style2, value2,
  16628. * BINDINGS, name1, name2, name3,
  16629. * TEMPLATE, name4, name5, name6,
  16630. * I18N, name7, name8, ...]
  16631. * ```
  16632. *
  16633. * Note that this function will fully ignore all synthetic (@foo) attribute values
  16634. * because those values are intended to always be generated as property instructions.
  16635. */
  16636. TemplateDefinitionBuilder.prototype.prepareNonRenderAttrs = function (inputs, outputs, styles, templateAttrs, i18nAttrs) {
  16637. if (templateAttrs === void 0) { templateAttrs = []; }
  16638. if (i18nAttrs === void 0) { i18nAttrs = []; }
  16639. var alreadySeen = new Set();
  16640. var attrExprs = [];
  16641. function addAttrExpr(key, value) {
  16642. if (typeof key === 'string') {
  16643. if (!alreadySeen.has(key)) {
  16644. attrExprs.push.apply(attrExprs, __spread(getAttributeNameLiterals(key)));
  16645. value !== undefined && attrExprs.push(value);
  16646. alreadySeen.add(key);
  16647. }
  16648. }
  16649. else {
  16650. attrExprs.push(literal(key));
  16651. }
  16652. }
  16653. // it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
  16654. // comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
  16655. // as single property value cell by cell.
  16656. if (styles) {
  16657. styles.populateInitialStylingAttrs(attrExprs);
  16658. }
  16659. if (inputs.length || outputs.length) {
  16660. var attrsStartIndex = attrExprs.length;
  16661. for (var i = 0; i < inputs.length; i++) {
  16662. var input = inputs[i];
  16663. if (input.type !== 4 /* Animation */) {
  16664. addAttrExpr(input.name);
  16665. }
  16666. }
  16667. for (var i = 0; i < outputs.length; i++) {
  16668. var output = outputs[i];
  16669. if (output.type !== 1 /* Animation */) {
  16670. addAttrExpr(output.name);
  16671. }
  16672. }
  16673. // this is a cheap way of adding the marker only after all the input/output
  16674. // values have been filtered (by not including the animation ones) and added
  16675. // to the expressions. The marker is important because it tells the runtime
  16676. // code that this is where attributes without values start...
  16677. if (attrExprs.length) {
  16678. attrExprs.splice(attrsStartIndex, 0, literal(3 /* Bindings */));
  16679. }
  16680. }
  16681. if (templateAttrs.length) {
  16682. attrExprs.push(literal(4 /* Template */));
  16683. templateAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  16684. }
  16685. if (i18nAttrs.length) {
  16686. attrExprs.push(literal(6 /* I18n */));
  16687. i18nAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  16688. }
  16689. return attrExprs;
  16690. };
  16691. TemplateDefinitionBuilder.prototype.toAttrsParam = function (attrsExprs) {
  16692. return attrsExprs.length > 0 ?
  16693. this.constantPool.getConstLiteral(literalArr(attrsExprs), true) :
  16694. TYPED_NULL_EXPR;
  16695. };
  16696. TemplateDefinitionBuilder.prototype.prepareRefsParameter = function (references) {
  16697. var _this = this;
  16698. if (!references || references.length === 0) {
  16699. return TYPED_NULL_EXPR;
  16700. }
  16701. var refsParam = flatten(references.map(function (reference) {
  16702. var slot = _this.allocateDataSlot();
  16703. // Generate the update temporary.
  16704. var variableName = _this._bindingScope.freshReferenceName();
  16705. var retrievalLevel = _this.level;
  16706. var lhs = variable(variableName);
  16707. _this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, function (scope, relativeLevel) {
  16708. // e.g. nextContext(2);
  16709. var nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
  16710. // e.g. const $foo$ = reference(1);
  16711. var refExpr = lhs.set(importExpr(Identifiers$1.reference).callFn([literal(slot)]));
  16712. return nextContextStmt.concat(refExpr.toConstDecl());
  16713. }, true);
  16714. return [reference.name, reference.value];
  16715. }));
  16716. return this.constantPool.getConstLiteral(asLiteral(refsParam), true);
  16717. };
  16718. TemplateDefinitionBuilder.prototype.prepareListenerParameter = function (tagName, outputAst, index) {
  16719. var _this = this;
  16720. return function () {
  16721. var eventName = outputAst.name;
  16722. var bindingFnName = outputAst.type === 1 /* Animation */ ?
  16723. // synthetic @listener.foo values are treated the exact same as are standard listeners
  16724. prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
  16725. sanitizeIdentifier(eventName);
  16726. var handlerName = _this.templateName + "_" + tagName + "_" + bindingFnName + "_" + index + "_listener";
  16727. var scope = _this._bindingScope.nestedScope(_this._bindingScope.bindingLevel);
  16728. return prepareEventListenerParameters(outputAst, handlerName, scope);
  16729. };
  16730. };
  16731. return TemplateDefinitionBuilder;
  16732. }());
  16733. var ValueConverter = /** @class */ (function (_super) {
  16734. __extends(ValueConverter, _super);
  16735. function ValueConverter(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
  16736. var _this = _super.call(this) || this;
  16737. _this.constantPool = constantPool;
  16738. _this.allocateSlot = allocateSlot;
  16739. _this.allocatePureFunctionSlots = allocatePureFunctionSlots;
  16740. _this.definePipe = definePipe;
  16741. _this._pipeBindExprs = [];
  16742. return _this;
  16743. }
  16744. // AstMemoryEfficientTransformer
  16745. ValueConverter.prototype.visitPipe = function (pipe, context) {
  16746. // Allocate a slot to create the pipe
  16747. var slot = this.allocateSlot();
  16748. var slotPseudoLocal = "PIPE:" + slot;
  16749. // Allocate one slot for the result plus one slot per pipe argument
  16750. var pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
  16751. var target = new PropertyRead(pipe.span, new ImplicitReceiver(pipe.span), slotPseudoLocal);
  16752. var _a = pipeBindingCallInfo(pipe.args), identifier = _a.identifier, isVarLength = _a.isVarLength;
  16753. this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
  16754. var args = __spread([pipe.exp], pipe.args);
  16755. var convertedArgs = isVarLength ? this.visitAll([new LiteralArray(pipe.span, args)]) : this.visitAll(args);
  16756. var pipeBindExpr = new FunctionCall(pipe.span, target, __spread([
  16757. new LiteralPrimitive(pipe.span, slot),
  16758. new LiteralPrimitive(pipe.span, pureFunctionSlot)
  16759. ], convertedArgs));
  16760. this._pipeBindExprs.push(pipeBindExpr);
  16761. return pipeBindExpr;
  16762. };
  16763. ValueConverter.prototype.updatePipeSlotOffsets = function (bindingSlots) {
  16764. this._pipeBindExprs.forEach(function (pipe) {
  16765. // update the slot offset arg (index 1) to account for binding slots
  16766. var slotOffset = pipe.args[1];
  16767. slotOffset.value += bindingSlots;
  16768. });
  16769. };
  16770. ValueConverter.prototype.visitLiteralArray = function (array, context) {
  16771. var _this = this;
  16772. return new BuiltinFunctionCall(array.span, this.visitAll(array.expressions), function (values) {
  16773. // If the literal has calculated (non-literal) elements transform it into
  16774. // calls to literal factories that compose the literal and will cache intermediate
  16775. // values. Otherwise, just return an literal array that contains the values.
  16776. var literal = literalArr(values);
  16777. return values.every(function (a) { return a.isConstant(); }) ?
  16778. _this.constantPool.getConstLiteral(literal, true) :
  16779. getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  16780. });
  16781. };
  16782. ValueConverter.prototype.visitLiteralMap = function (map, context) {
  16783. var _this = this;
  16784. return new BuiltinFunctionCall(map.span, this.visitAll(map.values), function (values) {
  16785. // If the literal has calculated (non-literal) elements transform it into
  16786. // calls to literal factories that compose the literal and will cache intermediate
  16787. // values. Otherwise, just return an literal array that contains the values.
  16788. var literal = literalMap(values.map(function (value, index) { return ({ key: map.keys[index].key, value: value, quoted: map.keys[index].quoted }); }));
  16789. return values.every(function (a) { return a.isConstant(); }) ?
  16790. _this.constantPool.getConstLiteral(literal, true) :
  16791. getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  16792. });
  16793. };
  16794. return ValueConverter;
  16795. }(AstMemoryEfficientTransformer));
  16796. // Pipes always have at least one parameter, the value they operate on
  16797. var pipeBindingIdentifiers = [Identifiers$1.pipeBind1, Identifiers$1.pipeBind2, Identifiers$1.pipeBind3, Identifiers$1.pipeBind4];
  16798. function pipeBindingCallInfo(args) {
  16799. var identifier = pipeBindingIdentifiers[args.length];
  16800. return {
  16801. identifier: identifier || Identifiers$1.pipeBindV,
  16802. isVarLength: !identifier,
  16803. };
  16804. }
  16805. var pureFunctionIdentifiers = [
  16806. Identifiers$1.pureFunction0, Identifiers$1.pureFunction1, Identifiers$1.pureFunction2, Identifiers$1.pureFunction3, Identifiers$1.pureFunction4,
  16807. Identifiers$1.pureFunction5, Identifiers$1.pureFunction6, Identifiers$1.pureFunction7, Identifiers$1.pureFunction8
  16808. ];
  16809. function pureFunctionCallInfo(args) {
  16810. var identifier = pureFunctionIdentifiers[args.length];
  16811. return {
  16812. identifier: identifier || Identifiers$1.pureFunctionV,
  16813. isVarLength: !identifier,
  16814. };
  16815. }
  16816. function instruction(span, reference, params) {
  16817. return importExpr(reference, null, span).callFn(params, span);
  16818. }
  16819. function chainedInstruction(span, reference, calls) {
  16820. var expression = importExpr(reference, null, span);
  16821. if (calls.length > 0) {
  16822. for (var i = 0; i < calls.length; i++) {
  16823. expression = expression.callFn(calls[i], span);
  16824. }
  16825. }
  16826. else {
  16827. // Add a blank invocation, in case the `calls` array is empty.
  16828. expression = expression.callFn([], span);
  16829. }
  16830. return expression;
  16831. }
  16832. // e.g. x(2);
  16833. function generateNextContextExpr(relativeLevelDiff) {
  16834. return importExpr(Identifiers$1.nextContext)
  16835. .callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
  16836. }
  16837. function getLiteralFactory(constantPool, literal$1, allocateSlots) {
  16838. var _a = constantPool.getLiteralFactory(literal$1), literalFactory = _a.literalFactory, literalFactoryArguments = _a.literalFactoryArguments;
  16839. // Allocate 1 slot for the result plus 1 per argument
  16840. var startSlot = allocateSlots(1 + literalFactoryArguments.length);
  16841. literalFactoryArguments.length > 0 || error("Expected arguments to a literal factory function");
  16842. var _b = pureFunctionCallInfo(literalFactoryArguments), identifier = _b.identifier, isVarLength = _b.isVarLength;
  16843. // Literal factories are pure functions that only need to be re-invoked when the parameters
  16844. // change.
  16845. var args = [
  16846. literal(startSlot),
  16847. literalFactory,
  16848. ];
  16849. if (isVarLength) {
  16850. args.push(literalArr(literalFactoryArguments));
  16851. }
  16852. else {
  16853. args.push.apply(args, __spread(literalFactoryArguments));
  16854. }
  16855. return importExpr(identifier).callFn(args);
  16856. }
  16857. /**
  16858. * Gets an array of literals that can be added to an expression
  16859. * to represent the name and namespace of an attribute. E.g.
  16860. * `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
  16861. *
  16862. * @param name Name of the attribute, including the namespace.
  16863. */
  16864. function getAttributeNameLiterals(name) {
  16865. var _a = __read(splitNsName(name), 2), attributeNamespace = _a[0], attributeName = _a[1];
  16866. var nameLiteral = literal(attributeName);
  16867. if (attributeNamespace) {
  16868. return [
  16869. literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
  16870. ];
  16871. }
  16872. return [nameLiteral];
  16873. }
  16874. /** The prefix used to get a shared context in BindingScope's map. */
  16875. var SHARED_CONTEXT_KEY = '$$shared_ctx$$';
  16876. var BindingScope = /** @class */ (function () {
  16877. function BindingScope(bindingLevel, parent) {
  16878. if (bindingLevel === void 0) { bindingLevel = 0; }
  16879. if (parent === void 0) { parent = null; }
  16880. this.bindingLevel = bindingLevel;
  16881. this.parent = parent;
  16882. /** Keeps a map from local variables to their BindingData. */
  16883. this.map = new Map();
  16884. this.referenceNameIndex = 0;
  16885. this.restoreViewVariable = null;
  16886. }
  16887. Object.defineProperty(BindingScope, "ROOT_SCOPE", {
  16888. get: function () {
  16889. if (!BindingScope._ROOT_SCOPE) {
  16890. BindingScope._ROOT_SCOPE = new BindingScope().set(0, '$event', variable('$event'));
  16891. }
  16892. return BindingScope._ROOT_SCOPE;
  16893. },
  16894. enumerable: true,
  16895. configurable: true
  16896. });
  16897. BindingScope.prototype.get = function (name) {
  16898. var current = this;
  16899. while (current) {
  16900. var value = current.map.get(name);
  16901. if (value != null) {
  16902. if (current !== this) {
  16903. // make a local copy and reset the `declare` state
  16904. value = {
  16905. retrievalLevel: value.retrievalLevel,
  16906. lhs: value.lhs,
  16907. declareLocalCallback: value.declareLocalCallback,
  16908. declare: false,
  16909. priority: value.priority,
  16910. localRef: value.localRef
  16911. };
  16912. // Cache the value locally.
  16913. this.map.set(name, value);
  16914. // Possibly generate a shared context var
  16915. this.maybeGenerateSharedContextVar(value);
  16916. this.maybeRestoreView(value.retrievalLevel, value.localRef);
  16917. }
  16918. if (value.declareLocalCallback && !value.declare) {
  16919. value.declare = true;
  16920. }
  16921. return value.lhs;
  16922. }
  16923. current = current.parent;
  16924. }
  16925. // If we get to this point, we are looking for a property on the top level component
  16926. // - If level === 0, we are on the top and don't need to re-declare `ctx`.
  16927. // - If level > 0, we are in an embedded view. We need to retrieve the name of the
  16928. // local var we used to store the component context, e.g. const $comp$ = x();
  16929. return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
  16930. };
  16931. /**
  16932. * Create a local variable for later reference.
  16933. *
  16934. * @param retrievalLevel The level from which this value can be retrieved
  16935. * @param name Name of the variable.
  16936. * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
  16937. * @param priority The sorting priority of this var
  16938. * @param declareLocalCallback The callback to invoke when declaring this local var
  16939. * @param localRef Whether or not this is a local ref
  16940. */
  16941. BindingScope.prototype.set = function (retrievalLevel, name, lhs, priority, declareLocalCallback, localRef) {
  16942. if (priority === void 0) { priority = 0 /* DEFAULT */; }
  16943. if (this.map.has(name)) {
  16944. if (localRef) {
  16945. // Do not throw an error if it's a local ref and do not update existing value,
  16946. // so the first defined ref is always returned.
  16947. return this;
  16948. }
  16949. error("The name " + name + " is already defined in scope to be " + this.map.get(name));
  16950. }
  16951. this.map.set(name, {
  16952. retrievalLevel: retrievalLevel,
  16953. lhs: lhs,
  16954. declare: false,
  16955. declareLocalCallback: declareLocalCallback,
  16956. priority: priority,
  16957. localRef: localRef || false
  16958. });
  16959. return this;
  16960. };
  16961. // Implemented as part of LocalResolver.
  16962. BindingScope.prototype.getLocal = function (name) { return this.get(name); };
  16963. // Implemented as part of LocalResolver.
  16964. BindingScope.prototype.notifyImplicitReceiverUse = function () {
  16965. if (this.bindingLevel !== 0) {
  16966. // Since the implicit receiver is accessed in an embedded view, we need to
  16967. // ensure that we declare a shared context variable for the current template
  16968. // in the update variables.
  16969. this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
  16970. }
  16971. };
  16972. BindingScope.prototype.nestedScope = function (level) {
  16973. var newScope = new BindingScope(level, this);
  16974. if (level > 0)
  16975. newScope.generateSharedContextVar(0);
  16976. return newScope;
  16977. };
  16978. /**
  16979. * Gets or creates a shared context variable and returns its expression. Note that
  16980. * this does not mean that the shared variable will be declared. Variables in the
  16981. * binding scope will be only declared if they are used.
  16982. */
  16983. BindingScope.prototype.getOrCreateSharedContextVar = function (retrievalLevel) {
  16984. var bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
  16985. if (!this.map.has(bindingKey)) {
  16986. this.generateSharedContextVar(retrievalLevel);
  16987. }
  16988. return this.map.get(bindingKey).lhs;
  16989. };
  16990. BindingScope.prototype.getSharedContextName = function (retrievalLevel) {
  16991. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
  16992. return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
  16993. };
  16994. BindingScope.prototype.maybeGenerateSharedContextVar = function (value) {
  16995. if (value.priority === 1 /* CONTEXT */ &&
  16996. value.retrievalLevel < this.bindingLevel) {
  16997. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
  16998. if (sharedCtxObj) {
  16999. sharedCtxObj.declare = true;
  17000. }
  17001. else {
  17002. this.generateSharedContextVar(value.retrievalLevel);
  17003. }
  17004. }
  17005. };
  17006. BindingScope.prototype.generateSharedContextVar = function (retrievalLevel) {
  17007. var lhs = variable(CONTEXT_NAME + this.freshReferenceName());
  17008. this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
  17009. retrievalLevel: retrievalLevel,
  17010. lhs: lhs,
  17011. declareLocalCallback: function (scope, relativeLevel) {
  17012. // const ctx_r0 = nextContext(2);
  17013. return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
  17014. },
  17015. declare: false,
  17016. priority: 2 /* SHARED_CONTEXT */,
  17017. localRef: false
  17018. });
  17019. };
  17020. BindingScope.prototype.getComponentProperty = function (name) {
  17021. var componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
  17022. componentValue.declare = true;
  17023. this.maybeRestoreView(0, false);
  17024. return componentValue.lhs.prop(name);
  17025. };
  17026. BindingScope.prototype.maybeRestoreView = function (retrievalLevel, localRefLookup) {
  17027. // We want to restore the current view in listener fns if:
  17028. // 1 - we are accessing a value in a parent view, which requires walking the view tree rather
  17029. // than using the ctx arg. In this case, the retrieval and binding level will be different.
  17030. // 2 - we are looking up a local ref, which requires restoring the view where the local
  17031. // ref is stored
  17032. if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
  17033. if (!this.parent.restoreViewVariable) {
  17034. // parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
  17035. this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
  17036. }
  17037. this.restoreViewVariable = this.parent.restoreViewVariable;
  17038. }
  17039. };
  17040. BindingScope.prototype.restoreViewStatement = function () {
  17041. // restoreView($state$);
  17042. return this.restoreViewVariable ?
  17043. [instruction(null, Identifiers$1.restoreView, [this.restoreViewVariable]).toStmt()] :
  17044. [];
  17045. };
  17046. BindingScope.prototype.viewSnapshotStatements = function () {
  17047. // const $state$ = getCurrentView();
  17048. var getCurrentViewInstruction = instruction(null, Identifiers$1.getCurrentView, []);
  17049. return this.restoreViewVariable ?
  17050. [this.restoreViewVariable.set(getCurrentViewInstruction).toConstDecl()] :
  17051. [];
  17052. };
  17053. BindingScope.prototype.isListenerScope = function () { return this.parent && this.parent.bindingLevel === this.bindingLevel; };
  17054. BindingScope.prototype.variableDeclarations = function () {
  17055. var _this = this;
  17056. var currentContextLevel = 0;
  17057. return Array.from(this.map.values())
  17058. .filter(function (value) { return value.declare; })
  17059. .sort(function (a, b) { return b.retrievalLevel - a.retrievalLevel || b.priority - a.priority; })
  17060. .reduce(function (stmts, value) {
  17061. var levelDiff = _this.bindingLevel - value.retrievalLevel;
  17062. var currStmts = value.declareLocalCallback(_this, levelDiff - currentContextLevel);
  17063. currentContextLevel = levelDiff;
  17064. return stmts.concat(currStmts);
  17065. }, []);
  17066. };
  17067. BindingScope.prototype.freshReferenceName = function () {
  17068. var current = this;
  17069. // Find the top scope as it maintains the global reference count
  17070. while (current.parent)
  17071. current = current.parent;
  17072. var ref = "" + REFERENCE_PREFIX + current.referenceNameIndex++;
  17073. return ref;
  17074. };
  17075. return BindingScope;
  17076. }());
  17077. /**
  17078. * Creates a `CssSelector` given a tag name and a map of attributes
  17079. */
  17080. function createCssSelector(tag, attributes) {
  17081. var cssSelector = new CssSelector();
  17082. cssSelector.setElement(tag);
  17083. Object.getOwnPropertyNames(attributes).forEach(function (name) {
  17084. var value = attributes[name];
  17085. cssSelector.addAttribute(name, value);
  17086. if (name.toLowerCase() === 'class') {
  17087. var classes = value.trim().split(/\s+/);
  17088. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  17089. }
  17090. });
  17091. return cssSelector;
  17092. }
  17093. /**
  17094. * Creates an array of expressions out of an `ngProjectAs` attributes
  17095. * which can be added to the instruction parameters.
  17096. */
  17097. function getNgProjectAsLiteral(attribute) {
  17098. // Parse the attribute value into a CssSelectorList. Note that we only take the
  17099. // first selector, because we don't support multiple selectors in ngProjectAs.
  17100. var parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
  17101. return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
  17102. }
  17103. function interpolate(args) {
  17104. args = args.slice(1); // Ignore the length prefix added for render2
  17105. switch (args.length) {
  17106. case 3:
  17107. return importExpr(Identifiers$1.interpolation1).callFn(args);
  17108. case 5:
  17109. return importExpr(Identifiers$1.interpolation2).callFn(args);
  17110. case 7:
  17111. return importExpr(Identifiers$1.interpolation3).callFn(args);
  17112. case 9:
  17113. return importExpr(Identifiers$1.interpolation4).callFn(args);
  17114. case 11:
  17115. return importExpr(Identifiers$1.interpolation5).callFn(args);
  17116. case 13:
  17117. return importExpr(Identifiers$1.interpolation6).callFn(args);
  17118. case 15:
  17119. return importExpr(Identifiers$1.interpolation7).callFn(args);
  17120. case 17:
  17121. return importExpr(Identifiers$1.interpolation8).callFn(args);
  17122. }
  17123. (args.length >= 19 && args.length % 2 == 1) ||
  17124. error("Invalid interpolation argument length " + args.length);
  17125. return importExpr(Identifiers$1.interpolationV).callFn([literalArr(args)]);
  17126. }
  17127. /**
  17128. * Gets the instruction to generate for an interpolated property
  17129. * @param interpolation An Interpolation AST
  17130. */
  17131. function getPropertyInterpolationExpression(interpolation) {
  17132. switch (getInterpolationArgsLength(interpolation)) {
  17133. case 1:
  17134. return Identifiers$1.propertyInterpolate;
  17135. case 3:
  17136. return Identifiers$1.propertyInterpolate1;
  17137. case 5:
  17138. return Identifiers$1.propertyInterpolate2;
  17139. case 7:
  17140. return Identifiers$1.propertyInterpolate3;
  17141. case 9:
  17142. return Identifiers$1.propertyInterpolate4;
  17143. case 11:
  17144. return Identifiers$1.propertyInterpolate5;
  17145. case 13:
  17146. return Identifiers$1.propertyInterpolate6;
  17147. case 15:
  17148. return Identifiers$1.propertyInterpolate7;
  17149. case 17:
  17150. return Identifiers$1.propertyInterpolate8;
  17151. default:
  17152. return Identifiers$1.propertyInterpolateV;
  17153. }
  17154. }
  17155. /**
  17156. * Gets the instruction to generate for an interpolated attribute
  17157. * @param interpolation An Interpolation AST
  17158. */
  17159. function getAttributeInterpolationExpression(interpolation) {
  17160. switch (getInterpolationArgsLength(interpolation)) {
  17161. case 3:
  17162. return Identifiers$1.attributeInterpolate1;
  17163. case 5:
  17164. return Identifiers$1.attributeInterpolate2;
  17165. case 7:
  17166. return Identifiers$1.attributeInterpolate3;
  17167. case 9:
  17168. return Identifiers$1.attributeInterpolate4;
  17169. case 11:
  17170. return Identifiers$1.attributeInterpolate5;
  17171. case 13:
  17172. return Identifiers$1.attributeInterpolate6;
  17173. case 15:
  17174. return Identifiers$1.attributeInterpolate7;
  17175. case 17:
  17176. return Identifiers$1.attributeInterpolate8;
  17177. default:
  17178. return Identifiers$1.attributeInterpolateV;
  17179. }
  17180. }
  17181. /**
  17182. * Gets the instruction to generate for interpolated text.
  17183. * @param interpolation An Interpolation AST
  17184. */
  17185. function getTextInterpolationExpression(interpolation) {
  17186. switch (getInterpolationArgsLength(interpolation)) {
  17187. case 1:
  17188. return Identifiers$1.textInterpolate;
  17189. case 3:
  17190. return Identifiers$1.textInterpolate1;
  17191. case 5:
  17192. return Identifiers$1.textInterpolate2;
  17193. case 7:
  17194. return Identifiers$1.textInterpolate3;
  17195. case 9:
  17196. return Identifiers$1.textInterpolate4;
  17197. case 11:
  17198. return Identifiers$1.textInterpolate5;
  17199. case 13:
  17200. return Identifiers$1.textInterpolate6;
  17201. case 15:
  17202. return Identifiers$1.textInterpolate7;
  17203. case 17:
  17204. return Identifiers$1.textInterpolate8;
  17205. default:
  17206. return Identifiers$1.textInterpolateV;
  17207. }
  17208. }
  17209. /**
  17210. * Gets the number of arguments expected to be passed to a generated instruction in the case of
  17211. * interpolation instructions.
  17212. * @param interpolation An interpolation ast
  17213. */
  17214. function getInterpolationArgsLength(interpolation) {
  17215. var expressions = interpolation.expressions, strings = interpolation.strings;
  17216. if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
  17217. // If the interpolation has one interpolated value, but the prefix and suffix are both empty
  17218. // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
  17219. // `textInterpolate`.
  17220. return 1;
  17221. }
  17222. else {
  17223. return expressions.length + strings.length;
  17224. }
  17225. }
  17226. /**
  17227. * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
  17228. *
  17229. * @param template text of the template to parse
  17230. * @param templateUrl URL to use for source mapping of the parsed template
  17231. * @param options options to modify how the template is parsed
  17232. */
  17233. function parseTemplate(template, templateUrl, options) {
  17234. if (options === void 0) { options = {}; }
  17235. var interpolationConfig = options.interpolationConfig, preserveWhitespaces = options.preserveWhitespaces;
  17236. var bindingParser = makeBindingParser(interpolationConfig);
  17237. var htmlParser = new HtmlParser();
  17238. var parseResult = htmlParser.parse(template, templateUrl, __assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options, { tokenizeExpansionForms: true }));
  17239. if (parseResult.errors && parseResult.errors.length > 0) {
  17240. return { errors: parseResult.errors, nodes: [], styleUrls: [], styles: [] };
  17241. }
  17242. var rootNodes = parseResult.rootNodes;
  17243. // process i18n meta information (scan attributes, generate ids)
  17244. // before we run whitespace removal process, because existing i18n
  17245. // extraction process (ng xi18n) relies on a raw content to generate
  17246. // message ids
  17247. rootNodes =
  17248. visitAll$1(new I18nMetaVisitor(interpolationConfig, !preserveWhitespaces), rootNodes);
  17249. if (!preserveWhitespaces) {
  17250. rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
  17251. // run i18n meta visitor again in case we remove whitespaces, because
  17252. // that might affect generated i18n message content. During this pass
  17253. // i18n IDs generated at the first pass will be preserved, so we can mimic
  17254. // existing extraction process (ng xi18n)
  17255. rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
  17256. }
  17257. var _a = htmlAstToRender3Ast(rootNodes, bindingParser), nodes = _a.nodes, errors = _a.errors, styleUrls = _a.styleUrls, styles = _a.styles;
  17258. if (errors && errors.length > 0) {
  17259. return { errors: errors, nodes: [], styleUrls: [], styles: [] };
  17260. }
  17261. return { nodes: nodes, styleUrls: styleUrls, styles: styles };
  17262. }
  17263. /**
  17264. * Construct a `BindingParser` with a default configuration.
  17265. */
  17266. function makeBindingParser(interpolationConfig) {
  17267. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  17268. return new BindingParser(new Parser$1(new Lexer()), interpolationConfig, new DomElementSchemaRegistry(), null, []);
  17269. }
  17270. function resolveSanitizationFn(context, isAttribute) {
  17271. switch (context) {
  17272. case SecurityContext.HTML:
  17273. return importExpr(Identifiers$1.sanitizeHtml);
  17274. case SecurityContext.SCRIPT:
  17275. return importExpr(Identifiers$1.sanitizeScript);
  17276. case SecurityContext.STYLE:
  17277. // the compiler does not fill in an instruction for [style.prop?] binding
  17278. // values because the style algorithm knows internally what props are subject
  17279. // to sanitization (only [attr.style] values are explicitly sanitized)
  17280. return isAttribute ? importExpr(Identifiers$1.sanitizeStyle) : null;
  17281. case SecurityContext.URL:
  17282. return importExpr(Identifiers$1.sanitizeUrl);
  17283. case SecurityContext.RESOURCE_URL:
  17284. return importExpr(Identifiers$1.sanitizeResourceUrl);
  17285. default:
  17286. return null;
  17287. }
  17288. }
  17289. function isSingleElementTemplate(children) {
  17290. return children.length === 1 && children[0] instanceof Element;
  17291. }
  17292. function isTextNode(node) {
  17293. return node instanceof Text || node instanceof BoundText || node instanceof Icu;
  17294. }
  17295. function hasTextChildrenOnly(children) {
  17296. return children.every(isTextNode);
  17297. }
  17298. /**
  17299. * @license
  17300. * Copyright Google Inc. All Rights Reserved.
  17301. *
  17302. * Use of this source code is governed by an MIT-style license that can be
  17303. * found in the LICENSE file at https://angular.io/license
  17304. */
  17305. var EMPTY_ARRAY = [];
  17306. // This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
  17307. // If there is a match, the first matching group will contain the attribute name to bind.
  17308. var ATTR_REGEX = /attr\.([^\]]+)/;
  17309. function getStylingPrefix(name) {
  17310. return name.substring(0, 5); // style or class
  17311. }
  17312. function baseDirectiveFields(meta, constantPool, bindingParser) {
  17313. var definitionMap = new DefinitionMap();
  17314. // e.g. `type: MyDirective`
  17315. definitionMap.set('type', meta.type);
  17316. // e.g. `selectors: [['', 'someDir', '']]`
  17317. definitionMap.set('selectors', createDirectiveSelector(meta.selector));
  17318. // e.g. `factory: () => new MyApp(directiveInject(ElementRef))`
  17319. var result = compileFactoryFunction({
  17320. name: meta.name,
  17321. type: meta.type,
  17322. deps: meta.deps,
  17323. injectFn: Identifiers$1.directiveInject,
  17324. });
  17325. definitionMap.set('factory', result.factory);
  17326. if (meta.queries.length > 0) {
  17327. // e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
  17328. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
  17329. }
  17330. if (meta.viewQueries.length) {
  17331. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
  17332. }
  17333. // e.g. `hostBindings: (rf, ctx, elIndex) => { ... }
  17334. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name));
  17335. // e.g 'inputs: {a: 'a'}`
  17336. definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
  17337. // e.g 'outputs: {a: 'a'}`
  17338. definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
  17339. if (meta.exportAs !== null) {
  17340. definitionMap.set('exportAs', literalArr(meta.exportAs.map(function (e) { return literal(e); })));
  17341. }
  17342. return { definitionMap: definitionMap, statements: result.statements };
  17343. }
  17344. /**
  17345. * Add features to the definition map.
  17346. */
  17347. function addFeatures(definitionMap, meta) {
  17348. // e.g. `features: [NgOnChangesFeature()]`
  17349. var features = [];
  17350. var providers = meta.providers;
  17351. var viewProviders = meta.viewProviders;
  17352. if (providers || viewProviders) {
  17353. var args = [providers || new LiteralArrayExpr([])];
  17354. if (viewProviders) {
  17355. args.push(viewProviders);
  17356. }
  17357. features.push(importExpr(Identifiers$1.ProvidersFeature).callFn(args));
  17358. }
  17359. if (meta.usesInheritance) {
  17360. features.push(importExpr(Identifiers$1.InheritDefinitionFeature));
  17361. }
  17362. if (meta.lifecycle.usesOnChanges) {
  17363. features.push(importExpr(Identifiers$1.NgOnChangesFeature).callFn(EMPTY_ARRAY));
  17364. }
  17365. if (features.length) {
  17366. definitionMap.set('features', literalArr(features));
  17367. }
  17368. }
  17369. /**
  17370. * Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
  17371. */
  17372. function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
  17373. var _a = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _a.definitionMap, statements = _a.statements;
  17374. addFeatures(definitionMap, meta);
  17375. var expression = importExpr(Identifiers$1.defineDirective).callFn([definitionMap.toLiteralMap()]);
  17376. if (!meta.selector) {
  17377. throw new Error("Directive " + meta.name + " has no selector, please add it!");
  17378. }
  17379. var type = createTypeForDef(meta, Identifiers$1.DirectiveDefWithMeta);
  17380. return { expression: expression, type: type, statements: statements };
  17381. }
  17382. /**
  17383. * Compile a base definition for the render3 runtime as defined by {@link R3BaseRefMetadata}
  17384. * @param meta the metadata used for compilation.
  17385. */
  17386. function compileBaseDefFromMetadata(meta, constantPool, bindingParser) {
  17387. var definitionMap = new DefinitionMap();
  17388. if (meta.inputs) {
  17389. var inputs_1 = meta.inputs;
  17390. var inputsMap = Object.keys(inputs_1).map(function (key) {
  17391. var v = inputs_1[key];
  17392. var value = Array.isArray(v) ? literalArr(v.map(function (vx) { return literal(vx); })) : literal(v);
  17393. return { key: key, value: value, quoted: false };
  17394. });
  17395. definitionMap.set('inputs', literalMap(inputsMap));
  17396. }
  17397. if (meta.outputs) {
  17398. var outputs_1 = meta.outputs;
  17399. var outputsMap = Object.keys(outputs_1).map(function (key) {
  17400. var value = literal(outputs_1[key]);
  17401. return { key: key, value: value, quoted: false };
  17402. });
  17403. definitionMap.set('outputs', literalMap(outputsMap));
  17404. }
  17405. if (meta.viewQueries && meta.viewQueries.length > 0) {
  17406. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool));
  17407. }
  17408. if (meta.queries && meta.queries.length > 0) {
  17409. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool));
  17410. }
  17411. if (meta.host) {
  17412. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.name));
  17413. }
  17414. var expression = importExpr(Identifiers$1.defineBase).callFn([definitionMap.toLiteralMap()]);
  17415. var type = new ExpressionType(importExpr(Identifiers$1.BaseDef));
  17416. return { expression: expression, type: type };
  17417. }
  17418. /**
  17419. * Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
  17420. */
  17421. function compileComponentFromMetadata(meta, constantPool, bindingParser) {
  17422. var e_1, _a;
  17423. var _b = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _b.definitionMap, statements = _b.statements;
  17424. addFeatures(definitionMap, meta);
  17425. var selector = meta.selector && CssSelector.parse(meta.selector);
  17426. var firstSelector = selector && selector[0];
  17427. // e.g. `attr: ["class", ".my.app"]`
  17428. // This is optional an only included if the first selector of a component specifies attributes.
  17429. if (firstSelector) {
  17430. var selectorAttributes = firstSelector.getAttrs();
  17431. if (selectorAttributes.length) {
  17432. definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(function (value) { return value != null ? literal(value) : literal(undefined); })),
  17433. /* forceShared */ true));
  17434. }
  17435. }
  17436. // Generate the CSS matcher that recognize directive
  17437. var directiveMatcher = null;
  17438. if (meta.directives.length > 0) {
  17439. var matcher = new SelectorMatcher();
  17440. try {
  17441. for (var _c = __values(meta.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
  17442. var _e = _d.value, selector_1 = _e.selector, expression_1 = _e.expression;
  17443. matcher.addSelectables(CssSelector.parse(selector_1), expression_1);
  17444. }
  17445. }
  17446. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  17447. finally {
  17448. try {
  17449. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  17450. }
  17451. finally { if (e_1) throw e_1.error; }
  17452. }
  17453. directiveMatcher = matcher;
  17454. }
  17455. // e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
  17456. var templateTypeName = meta.name;
  17457. var templateName = templateTypeName ? templateTypeName + "_Template" : null;
  17458. var directivesUsed = new Set();
  17459. var pipesUsed = new Set();
  17460. var changeDetection = meta.changeDetection;
  17461. var template = meta.template;
  17462. var templateBuilder = new TemplateDefinitionBuilder(constantPool, BindingScope.ROOT_SCOPE, 0, templateTypeName, null, null, templateName, directiveMatcher, directivesUsed, meta.pipes, pipesUsed, Identifiers$1.namespaceHTML, meta.relativeContextFilePath, meta.i18nUseExternalIds);
  17463. var templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
  17464. // We need to provide this so that dynamically generated components know what
  17465. // projected content blocks to pass through to the component when it is instantiated.
  17466. var ngContentSelectors = templateBuilder.getNgContentSelectors();
  17467. if (ngContentSelectors) {
  17468. definitionMap.set('ngContentSelectors', ngContentSelectors);
  17469. }
  17470. // e.g. `consts: 2`
  17471. definitionMap.set('consts', literal(templateBuilder.getConstCount()));
  17472. // e.g. `vars: 2`
  17473. definitionMap.set('vars', literal(templateBuilder.getVarCount()));
  17474. definitionMap.set('template', templateFunctionExpression);
  17475. // e.g. `directives: [MyDirective]`
  17476. if (directivesUsed.size) {
  17477. var directivesExpr = literalArr(Array.from(directivesUsed));
  17478. if (meta.wrapDirectivesAndPipesInClosure) {
  17479. directivesExpr = fn([], [new ReturnStatement(directivesExpr)]);
  17480. }
  17481. definitionMap.set('directives', directivesExpr);
  17482. }
  17483. // e.g. `pipes: [MyPipe]`
  17484. if (pipesUsed.size) {
  17485. var pipesExpr = literalArr(Array.from(pipesUsed));
  17486. if (meta.wrapDirectivesAndPipesInClosure) {
  17487. pipesExpr = fn([], [new ReturnStatement(pipesExpr)]);
  17488. }
  17489. definitionMap.set('pipes', pipesExpr);
  17490. }
  17491. if (meta.encapsulation === null) {
  17492. meta.encapsulation = ViewEncapsulation.Emulated;
  17493. }
  17494. // e.g. `styles: [str1, str2]`
  17495. if (meta.styles && meta.styles.length) {
  17496. var styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
  17497. compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
  17498. meta.styles;
  17499. var strings = styleValues.map(function (str) { return literal(str); });
  17500. definitionMap.set('styles', literalArr(strings));
  17501. }
  17502. else if (meta.encapsulation === ViewEncapsulation.Emulated) {
  17503. // If there is no style, don't generate css selectors on elements
  17504. meta.encapsulation = ViewEncapsulation.None;
  17505. }
  17506. // Only set view encapsulation if it's not the default value
  17507. if (meta.encapsulation !== ViewEncapsulation.Emulated) {
  17508. definitionMap.set('encapsulation', literal(meta.encapsulation));
  17509. }
  17510. // e.g. `animation: [trigger('123', [])]`
  17511. if (meta.animations !== null) {
  17512. definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
  17513. }
  17514. // Only set the change detection flag if it's defined and it's not the default.
  17515. if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
  17516. definitionMap.set('changeDetection', literal(changeDetection));
  17517. }
  17518. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  17519. // string literal, which must be on one line.
  17520. var selectorForType = (meta.selector || '').replace(/\n/g, '');
  17521. var expression = importExpr(Identifiers$1.defineComponent).callFn([definitionMap.toLiteralMap()]);
  17522. var type = createTypeForDef(meta, Identifiers$1.ComponentDefWithMeta);
  17523. return { expression: expression, type: type, statements: statements };
  17524. }
  17525. /**
  17526. * A wrapper around `compileDirective` which depends on render2 global analysis data as its input
  17527. * instead of the `R3DirectiveMetadata`.
  17528. *
  17529. * `R3DirectiveMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
  17530. * information.
  17531. */
  17532. function compileDirectiveFromRender2(outputCtx, directive, reflector, bindingParser) {
  17533. var name = identifierName(directive.type);
  17534. name || error("Cannot resolver the name of " + directive.type);
  17535. var definitionField = outputCtx.constantPool.propertyNameOf(1 /* Directive */);
  17536. var meta = directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector);
  17537. var res = compileDirectiveFromMetadata(meta, outputCtx.constantPool, bindingParser);
  17538. // Create the partial class to be merged with the actual class.
  17539. outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
  17540. }
  17541. /**
  17542. * A wrapper around `compileComponent` which depends on render2 global analysis data as its input
  17543. * instead of the `R3DirectiveMetadata`.
  17544. *
  17545. * `R3ComponentMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
  17546. * information.
  17547. */
  17548. function compileComponentFromRender2(outputCtx, component, render3Ast, reflector, bindingParser, directiveTypeBySel, pipeTypeByName) {
  17549. var name = identifierName(component.type);
  17550. name || error("Cannot resolver the name of " + component.type);
  17551. var definitionField = outputCtx.constantPool.propertyNameOf(2 /* Component */);
  17552. var summary = component.toSummary();
  17553. // Compute the R3ComponentMetadata from the CompileDirectiveMetadata
  17554. var meta = __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 });
  17555. var res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser);
  17556. // Create the partial class to be merged with the actual class.
  17557. outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
  17558. }
  17559. /**
  17560. * Compute `R3DirectiveMetadata` given `CompileDirectiveMetadata` and a `CompileReflector`.
  17561. */
  17562. function directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector) {
  17563. // The global-analysis based Ivy mode in ngc is no longer utilized/supported.
  17564. throw new Error('unsupported');
  17565. }
  17566. /**
  17567. * Convert `CompileQueryMetadata` into `R3QueryMetadata`.
  17568. */
  17569. function queriesFromGlobalMetadata(queries, outputCtx) {
  17570. return queries.map(function (query) {
  17571. var read = null;
  17572. if (query.read && query.read.identifier) {
  17573. read = outputCtx.importExpr(query.read.identifier.reference);
  17574. }
  17575. return {
  17576. propertyName: query.propertyName,
  17577. first: query.first,
  17578. predicate: selectorsFromGlobalMetadata(query.selectors, outputCtx),
  17579. descendants: query.descendants, read: read,
  17580. static: !!query.static
  17581. };
  17582. });
  17583. }
  17584. /**
  17585. * Convert `CompileTokenMetadata` for query selectors into either an expression for a predicate
  17586. * type, or a list of string predicates.
  17587. */
  17588. function selectorsFromGlobalMetadata(selectors, outputCtx) {
  17589. if (selectors.length > 1 || (selectors.length == 1 && selectors[0].value)) {
  17590. var selectorStrings = selectors.map(function (value) { return value.value; });
  17591. selectorStrings.some(function (value) { return !value; }) &&
  17592. error('Found a type among the string selectors expected');
  17593. return outputCtx.constantPool.getConstLiteral(literalArr(selectorStrings.map(function (value) { return literal(value); })));
  17594. }
  17595. if (selectors.length == 1) {
  17596. var first = selectors[0];
  17597. if (first.identifier) {
  17598. return outputCtx.importExpr(first.identifier.reference);
  17599. }
  17600. }
  17601. error('Unexpected query form');
  17602. return NULL_EXPR;
  17603. }
  17604. function prepareQueryParams(query, constantPool) {
  17605. var parameters = [
  17606. getQueryPredicate(query, constantPool),
  17607. literal(query.descendants),
  17608. query.read || literal(null),
  17609. ];
  17610. return parameters;
  17611. }
  17612. // Turn a directive selector into an R3-compatible selector for directive def
  17613. function createDirectiveSelector(selector) {
  17614. return asLiteral(parseSelectorToR3Selector(selector));
  17615. }
  17616. function convertAttributesToExpressions(attributes) {
  17617. var e_2, _a;
  17618. var values = [];
  17619. try {
  17620. for (var _b = __values(Object.getOwnPropertyNames(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) {
  17621. var key = _c.value;
  17622. var value = attributes[key];
  17623. values.push(literal(key), value);
  17624. }
  17625. }
  17626. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  17627. finally {
  17628. try {
  17629. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  17630. }
  17631. finally { if (e_2) throw e_2.error; }
  17632. }
  17633. return values;
  17634. }
  17635. // Define and update any content queries
  17636. function createContentQueriesFunction(queries, constantPool, name) {
  17637. var e_3, _a;
  17638. var createStatements = [];
  17639. var updateStatements = [];
  17640. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  17641. try {
  17642. for (var queries_1 = __values(queries), queries_1_1 = queries_1.next(); !queries_1_1.done; queries_1_1 = queries_1.next()) {
  17643. var query = queries_1_1.value;
  17644. // creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
  17645. var args = __spread([variable('dirIndex')], prepareQueryParams(query, constantPool));
  17646. var queryInstruction = query.static ? Identifiers$1.staticContentQuery : Identifiers$1.contentQuery;
  17647. createStatements.push(importExpr(queryInstruction).callFn(args).toStmt());
  17648. // update, e.g. (r3.queryRefresh(tmp = r3.loadContentQuery()) && (ctx.someDir = tmp));
  17649. var temporary = tempAllocator();
  17650. var getQueryList = importExpr(Identifiers$1.loadContentQuery).callFn([]);
  17651. var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  17652. var updateDirective = variable(CONTEXT_NAME)
  17653. .prop(query.propertyName)
  17654. .set(query.first ? temporary.prop('first') : temporary);
  17655. updateStatements.push(refresh.and(updateDirective).toStmt());
  17656. }
  17657. }
  17658. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  17659. finally {
  17660. try {
  17661. if (queries_1_1 && !queries_1_1.done && (_a = queries_1.return)) _a.call(queries_1);
  17662. }
  17663. finally { if (e_3) throw e_3.error; }
  17664. }
  17665. var contentQueriesFnName = name ? name + "_ContentQueries" : null;
  17666. return fn([
  17667. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  17668. new FnParam('dirIndex', null)
  17669. ], [
  17670. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  17671. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  17672. ], INFERRED_TYPE, null, contentQueriesFnName);
  17673. }
  17674. function stringAsType(str) {
  17675. return expressionType(literal(str));
  17676. }
  17677. function stringMapAsType(map) {
  17678. var mapValues = Object.keys(map).map(function (key) {
  17679. var value = Array.isArray(map[key]) ? map[key][0] : map[key];
  17680. return {
  17681. key: key,
  17682. value: literal(value),
  17683. quoted: true,
  17684. };
  17685. });
  17686. return expressionType(literalMap(mapValues));
  17687. }
  17688. function stringArrayAsType(arr) {
  17689. return arr.length > 0 ? expressionType(literalArr(arr.map(function (value) { return literal(value); }))) :
  17690. NONE_TYPE;
  17691. }
  17692. function createTypeForDef(meta, typeBase) {
  17693. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  17694. // string literal, which must be on one line.
  17695. var selectorForType = (meta.selector || '').replace(/\n/g, '');
  17696. return expressionType(importExpr(typeBase, [
  17697. typeWithParameters(meta.type, meta.typeArgumentCount),
  17698. stringAsType(selectorForType),
  17699. meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
  17700. stringMapAsType(meta.inputs),
  17701. stringMapAsType(meta.outputs),
  17702. stringArrayAsType(meta.queries.map(function (q) { return q.propertyName; })),
  17703. ]));
  17704. }
  17705. // Define and update any view queries
  17706. function createViewQueriesFunction(viewQueries, constantPool, name) {
  17707. var createStatements = [];
  17708. var updateStatements = [];
  17709. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  17710. viewQueries.forEach(function (query) {
  17711. var queryInstruction = query.static ? Identifiers$1.staticViewQuery : Identifiers$1.viewQuery;
  17712. // creation, e.g. r3.viewQuery(somePredicate, true);
  17713. var queryDefinition = importExpr(queryInstruction).callFn(prepareQueryParams(query, constantPool));
  17714. createStatements.push(queryDefinition.toStmt());
  17715. // update, e.g. (r3.queryRefresh(tmp = r3.loadViewQuery()) && (ctx.someDir = tmp));
  17716. var temporary = tempAllocator();
  17717. var getQueryList = importExpr(Identifiers$1.loadViewQuery).callFn([]);
  17718. var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  17719. var updateDirective = variable(CONTEXT_NAME)
  17720. .prop(query.propertyName)
  17721. .set(query.first ? temporary.prop('first') : temporary);
  17722. updateStatements.push(refresh.and(updateDirective).toStmt());
  17723. });
  17724. var viewQueryFnName = name ? name + "_Query" : null;
  17725. return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
  17726. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  17727. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  17728. ], INFERRED_TYPE, null, viewQueryFnName);
  17729. }
  17730. // Return a host binding function or null if one is not necessary.
  17731. function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name) {
  17732. // Initialize hostVarsCount to number of bound host properties (interpolations illegal),
  17733. // except 'style' and 'class' properties, since they should *not* allocate host var slots
  17734. var hostVarsCount = Object.keys(hostBindingsMetadata.properties)
  17735. .filter(function (name) {
  17736. var prefix = getStylingPrefix(name);
  17737. return prefix !== 'style' && prefix !== 'class';
  17738. })
  17739. .length;
  17740. var elVarExp = variable('elIndex');
  17741. var bindingContext = variable(CONTEXT_NAME);
  17742. var styleBuilder = new StylingBuilder(elVarExp, bindingContext);
  17743. var _a = hostBindingsMetadata.specialAttributes, styleAttr = _a.styleAttr, classAttr = _a.classAttr;
  17744. if (styleAttr !== undefined) {
  17745. styleBuilder.registerStyleAttr(styleAttr);
  17746. }
  17747. if (classAttr !== undefined) {
  17748. styleBuilder.registerClassAttr(classAttr);
  17749. }
  17750. var createStatements = [];
  17751. var updateStatements = [];
  17752. var totalHostVarsCount = hostVarsCount;
  17753. var hostBindingSourceSpan = typeSourceSpan;
  17754. var directiveSummary = metadataAsSummary(hostBindingsMetadata);
  17755. var valueConverter;
  17756. var getValueConverter = function () {
  17757. if (!valueConverter) {
  17758. var hostVarsCountFn = function (numSlots) {
  17759. var originalVarsCount = totalHostVarsCount;
  17760. totalHostVarsCount += numSlots;
  17761. return originalVarsCount;
  17762. };
  17763. valueConverter = new ValueConverter(constantPool, function () { return error('Unexpected node'); }, // new nodes are illegal here
  17764. hostVarsCountFn, function () { return error('Unexpected pipe'); }); // pipes are illegal here
  17765. }
  17766. return valueConverter;
  17767. };
  17768. // Calculate host event bindings
  17769. var eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
  17770. if (eventBindings && eventBindings.length) {
  17771. var listeners = createHostListeners(eventBindings, name);
  17772. createStatements.push.apply(createStatements, __spread(listeners));
  17773. }
  17774. // Calculate the host property bindings
  17775. var bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
  17776. (bindings || []).forEach(function (binding) {
  17777. var name = binding.name;
  17778. var stylingInputWasSet = styleBuilder.registerInputBasedOnName(name, binding.expression, binding.sourceSpan);
  17779. if (!stylingInputWasSet) {
  17780. // resolve literal arrays and literal objects
  17781. var value = binding.expression.visit(getValueConverter());
  17782. var bindingExpr = bindingFn(bindingContext, value);
  17783. var _a = getBindingNameAndInstruction(binding), bindingName = _a.bindingName, instruction = _a.instruction, isAttribute = _a.isAttribute;
  17784. var securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
  17785. .filter(function (context) { return context !== SecurityContext.NONE; });
  17786. var sanitizerFn = null;
  17787. if (securityContexts.length) {
  17788. if (securityContexts.length === 2 &&
  17789. securityContexts.indexOf(SecurityContext.URL) > -1 &&
  17790. securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
  17791. // Special case for some URL attributes (such as "src" and "href") that may be a part
  17792. // of different security contexts. In this case we use special santitization function and
  17793. // select the actual sanitizer at runtime based on a tag name that is provided while
  17794. // invoking sanitization function.
  17795. sanitizerFn = importExpr(Identifiers$1.sanitizeUrlOrResourceUrl);
  17796. }
  17797. else {
  17798. sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
  17799. }
  17800. }
  17801. var instructionParams = [literal(bindingName), bindingExpr.currValExpr];
  17802. if (sanitizerFn) {
  17803. instructionParams.push(sanitizerFn);
  17804. }
  17805. if (!isAttribute) {
  17806. if (!sanitizerFn) {
  17807. // append `null` in front of `nativeOnly` flag if no sanitizer fn defined
  17808. instructionParams.push(literal(null));
  17809. }
  17810. // host bindings must have nativeOnly prop set to true
  17811. instructionParams.push(literal(true));
  17812. }
  17813. updateStatements.push.apply(updateStatements, __spread(bindingExpr.stmts));
  17814. updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
  17815. }
  17816. });
  17817. // since we're dealing with directives/components and both have hostBinding
  17818. // functions, we need to generate a special hostAttrs instruction that deals
  17819. // with both the assignment of styling as well as static attributes to the host
  17820. // element. The instruction below will instruct all initial styling (styling
  17821. // that is inside of a host binding within a directive/component) to be attached
  17822. // to the host element alongside any of the provided host attributes that were
  17823. // collected earlier.
  17824. var hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
  17825. var hostInstruction = styleBuilder.buildHostAttrsInstruction(null, hostAttrs, constantPool);
  17826. if (hostInstruction) {
  17827. createStatements.push(createStylingStmt(hostInstruction, bindingContext, bindingFn));
  17828. }
  17829. if (styleBuilder.hasBindings) {
  17830. // singular style/class bindings (things like `[style.prop]` and `[class.name]`)
  17831. // MUST be registered on a given element within the component/directive
  17832. // templateFn/hostBindingsFn functions. The instruction below will figure out
  17833. // what all the bindings are and then generate the statements required to register
  17834. // those bindings to the element via `styling`.
  17835. var stylingInstruction = styleBuilder.buildStylingInstruction(null, constantPool);
  17836. if (stylingInstruction) {
  17837. createStatements.push(createStylingStmt(stylingInstruction, bindingContext, bindingFn));
  17838. }
  17839. // finally each binding that was registered in the statement above will need to be added to
  17840. // the update block of a component/directive templateFn/hostBindingsFn so that the bindings
  17841. // are evaluated and updated for the element.
  17842. styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(function (instruction) {
  17843. totalHostVarsCount += instruction.allocateBindingSlots;
  17844. updateStatements.push(createStylingStmt(instruction, bindingContext, bindingFn));
  17845. });
  17846. }
  17847. if (totalHostVarsCount) {
  17848. createStatements.unshift(importExpr(Identifiers$1.allocHostVars).callFn([literal(totalHostVarsCount)]).toStmt());
  17849. }
  17850. if (createStatements.length > 0 || updateStatements.length > 0) {
  17851. var hostBindingsFnName = name ? name + "_HostBindings" : null;
  17852. var statements = [];
  17853. if (createStatements.length > 0) {
  17854. statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
  17855. }
  17856. if (updateStatements.length > 0) {
  17857. statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
  17858. }
  17859. return fn([
  17860. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  17861. new FnParam(elVarExp.name, NUMBER_TYPE)
  17862. ], statements, INFERRED_TYPE, null, hostBindingsFnName);
  17863. }
  17864. return null;
  17865. }
  17866. function bindingFn(implicit, value) {
  17867. return convertPropertyBinding(null, implicit, value, 'b', BindingForm.TrySimple, function () { return error('Unexpected interpolation'); });
  17868. }
  17869. function createStylingStmt(instruction, bindingContext, bindingFn) {
  17870. var params = instruction.buildParams(function (value) { return bindingFn(bindingContext, value).currValExpr; });
  17871. return importExpr(instruction.reference, null, instruction.sourceSpan)
  17872. .callFn(params, instruction.sourceSpan)
  17873. .toStmt();
  17874. }
  17875. function getBindingNameAndInstruction(binding) {
  17876. var bindingName = binding.name;
  17877. var instruction;
  17878. // Check to see if this is an attr binding or a property binding
  17879. var attrMatches = bindingName.match(ATTR_REGEX);
  17880. if (attrMatches) {
  17881. bindingName = attrMatches[1];
  17882. instruction = Identifiers$1.attribute;
  17883. }
  17884. else {
  17885. if (binding.isAnimation) {
  17886. bindingName = prepareSyntheticPropertyName(bindingName);
  17887. // host bindings that have a synthetic property (e.g. @foo) should always be rendered
  17888. // in the context of the component and not the parent. Therefore there is a special
  17889. // compatibility instruction available for this purpose.
  17890. instruction = Identifiers$1.updateSyntheticHostBinding;
  17891. }
  17892. else {
  17893. instruction = Identifiers$1.property;
  17894. }
  17895. }
  17896. return { bindingName: bindingName, instruction: instruction, isAttribute: !!attrMatches };
  17897. }
  17898. function createHostListeners(eventBindings, name) {
  17899. return eventBindings.map(function (binding) {
  17900. var bindingName = binding.name && sanitizeIdentifier(binding.name);
  17901. var bindingFnName = binding.type === 1 /* Animation */ ?
  17902. prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
  17903. bindingName;
  17904. var handlerName = name && bindingName ? name + "_" + bindingFnName + "_HostBindingHandler" : null;
  17905. var params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
  17906. var instruction = binding.type == 1 /* Animation */ ? Identifiers$1.componentHostSyntheticListener : Identifiers$1.listener;
  17907. return importExpr(instruction).callFn(params).toStmt();
  17908. });
  17909. }
  17910. function metadataAsSummary(meta) {
  17911. // clang-format off
  17912. return {
  17913. // This is used by the BindingParser, which only deals with listeners and properties. There's no
  17914. // need to pass attributes to it.
  17915. hostAttributes: {},
  17916. hostListeners: meta.listeners,
  17917. hostProperties: meta.properties,
  17918. };
  17919. // clang-format on
  17920. }
  17921. function typeMapToExpressionMap(map, outputCtx) {
  17922. // Convert each map entry into another entry where the value is an expression importing the type.
  17923. var entries = Array.from(map).map(function (_a) {
  17924. var _b = __read(_a, 2), key = _b[0], type = _b[1];
  17925. return [key, outputCtx.importExpr(type)];
  17926. });
  17927. return new Map(entries);
  17928. }
  17929. var HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
  17930. function parseHostBindings(host) {
  17931. var e_4, _a;
  17932. var attributes = {};
  17933. var listeners = {};
  17934. var properties = {};
  17935. var specialAttributes = {};
  17936. try {
  17937. for (var _b = __values(Object.keys(host)), _c = _b.next(); !_c.done; _c = _b.next()) {
  17938. var key = _c.value;
  17939. var value = host[key];
  17940. var matches = key.match(HOST_REG_EXP$1);
  17941. if (matches === null) {
  17942. switch (key) {
  17943. case 'class':
  17944. if (typeof value !== 'string') {
  17945. // TODO(alxhub): make this a diagnostic.
  17946. throw new Error("Class binding must be string");
  17947. }
  17948. specialAttributes.classAttr = value;
  17949. break;
  17950. case 'style':
  17951. if (typeof value !== 'string') {
  17952. // TODO(alxhub): make this a diagnostic.
  17953. throw new Error("Style binding must be string");
  17954. }
  17955. specialAttributes.styleAttr = value;
  17956. break;
  17957. default:
  17958. if (typeof value === 'string') {
  17959. attributes[key] = literal(value);
  17960. }
  17961. else {
  17962. attributes[key] = value;
  17963. }
  17964. }
  17965. }
  17966. else if (matches[1 /* Binding */] != null) {
  17967. if (typeof value !== 'string') {
  17968. // TODO(alxhub): make this a diagnostic.
  17969. throw new Error("Property binding must be string");
  17970. }
  17971. // synthetic properties (the ones that have a `@` as a prefix)
  17972. // are still treated the same as regular properties. Therefore
  17973. // there is no point in storing them in a separate map.
  17974. properties[matches[1 /* Binding */]] = value;
  17975. }
  17976. else if (matches[2 /* Event */] != null) {
  17977. if (typeof value !== 'string') {
  17978. // TODO(alxhub): make this a diagnostic.
  17979. throw new Error("Event binding must be string");
  17980. }
  17981. listeners[matches[2 /* Event */]] = value;
  17982. }
  17983. }
  17984. }
  17985. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  17986. finally {
  17987. try {
  17988. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  17989. }
  17990. finally { if (e_4) throw e_4.error; }
  17991. }
  17992. return { attributes: attributes, listeners: listeners, properties: properties, specialAttributes: specialAttributes };
  17993. }
  17994. /**
  17995. * Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
  17996. * given set of host bindings has no errors.
  17997. *
  17998. * @param bindings set of host bindings to verify.
  17999. * @param sourceSpan source span where host bindings were defined.
  18000. * @returns array of errors associated with a given set of host bindings.
  18001. */
  18002. function verifyHostBindings(bindings, sourceSpan) {
  18003. var summary = metadataAsSummary(bindings);
  18004. // TODO: abstract out host bindings verification logic and use it instead of
  18005. // creating events and properties ASTs to detect errors (FW-996)
  18006. var bindingParser = makeBindingParser();
  18007. bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
  18008. bindingParser.createBoundHostProperties(summary, sourceSpan);
  18009. return bindingParser.errors;
  18010. }
  18011. function compileStyles(styles, selector, hostSelector) {
  18012. var shadowCss = new ShadowCss();
  18013. return styles.map(function (style) { return shadowCss.shimCssText(style, selector, hostSelector); });
  18014. }
  18015. /**
  18016. * @license
  18017. * Copyright Google Inc. All Rights Reserved.
  18018. *
  18019. * Use of this source code is governed by an MIT-style license that can be
  18020. * found in the LICENSE file at https://angular.io/license
  18021. */
  18022. /**
  18023. * An interface for retrieving documents by URL that the compiler uses
  18024. * to load templates.
  18025. */
  18026. var ResourceLoader = /** @class */ (function () {
  18027. function ResourceLoader() {
  18028. }
  18029. ResourceLoader.prototype.get = function (url) { return ''; };
  18030. return ResourceLoader;
  18031. }());
  18032. /**
  18033. * @license
  18034. * Copyright Google Inc. All Rights Reserved.
  18035. *
  18036. * Use of this source code is governed by an MIT-style license that can be
  18037. * found in the LICENSE file at https://angular.io/license
  18038. */
  18039. var CompilerFacadeImpl = /** @class */ (function () {
  18040. function CompilerFacadeImpl(jitEvaluator) {
  18041. if (jitEvaluator === void 0) { jitEvaluator = new JitEvaluator(); }
  18042. this.jitEvaluator = jitEvaluator;
  18043. this.R3ResolvedDependencyType = R3ResolvedDependencyType;
  18044. this.ResourceLoader = ResourceLoader;
  18045. this.elementSchemaRegistry = new DomElementSchemaRegistry();
  18046. }
  18047. CompilerFacadeImpl.prototype.compilePipe = function (angularCoreEnv, sourceMapUrl, facade) {
  18048. var res = compilePipeFromMetadata({
  18049. name: facade.name,
  18050. type: new WrappedNodeExpr(facade.type),
  18051. typeArgumentCount: facade.typeArgumentCount,
  18052. deps: convertR3DependencyMetadataArray(facade.deps),
  18053. pipeName: facade.pipeName,
  18054. pure: facade.pure,
  18055. });
  18056. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  18057. };
  18058. CompilerFacadeImpl.prototype.compileInjectable = function (angularCoreEnv, sourceMapUrl, facade) {
  18059. var _a = compileInjectable({
  18060. name: facade.name,
  18061. type: new WrappedNodeExpr(facade.type),
  18062. typeArgumentCount: facade.typeArgumentCount,
  18063. providedIn: computeProvidedIn(facade.providedIn),
  18064. useClass: wrapExpression(facade, USE_CLASS),
  18065. useFactory: wrapExpression(facade, USE_FACTORY),
  18066. useValue: wrapExpression(facade, USE_VALUE),
  18067. useExisting: wrapExpression(facade, USE_EXISTING),
  18068. ctorDeps: convertR3DependencyMetadataArray(facade.ctorDeps),
  18069. userDeps: convertR3DependencyMetadataArray(facade.userDeps) || undefined,
  18070. }), expression = _a.expression, statements = _a.statements;
  18071. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
  18072. };
  18073. CompilerFacadeImpl.prototype.compileInjector = function (angularCoreEnv, sourceMapUrl, facade) {
  18074. var meta = {
  18075. name: facade.name,
  18076. type: new WrappedNodeExpr(facade.type),
  18077. deps: convertR3DependencyMetadataArray(facade.deps),
  18078. providers: new WrappedNodeExpr(facade.providers),
  18079. imports: facade.imports.map(function (i) { return new WrappedNodeExpr(i); }),
  18080. };
  18081. var res = compileInjector(meta);
  18082. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  18083. };
  18084. CompilerFacadeImpl.prototype.compileNgModule = function (angularCoreEnv, sourceMapUrl, facade) {
  18085. var meta = {
  18086. type: new WrappedNodeExpr(facade.type),
  18087. bootstrap: facade.bootstrap.map(wrapReference),
  18088. declarations: facade.declarations.map(wrapReference),
  18089. imports: facade.imports.map(wrapReference),
  18090. exports: facade.exports.map(wrapReference),
  18091. emitInline: true,
  18092. containsForwardDecls: false,
  18093. schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
  18094. id: facade.id ? new WrappedNodeExpr(facade.id) : null,
  18095. };
  18096. var res = compileNgModule(meta);
  18097. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  18098. };
  18099. CompilerFacadeImpl.prototype.compileDirective = function (angularCoreEnv, sourceMapUrl, facade) {
  18100. var constantPool = new ConstantPool();
  18101. var bindingParser = makeBindingParser();
  18102. var meta = convertDirectiveFacadeToMetadata(facade);
  18103. var res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
  18104. var preStatements = __spread(constantPool.statements, res.statements);
  18105. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, preStatements);
  18106. };
  18107. CompilerFacadeImpl.prototype.compileComponent = function (angularCoreEnv, sourceMapUrl, facade) {
  18108. // The ConstantPool is a requirement of the JIT'er.
  18109. var constantPool = new ConstantPool();
  18110. var interpolationConfig = facade.interpolation ?
  18111. InterpolationConfig.fromArray(facade.interpolation) :
  18112. DEFAULT_INTERPOLATION_CONFIG;
  18113. // Parse the template and check for errors.
  18114. var template = parseTemplate(facade.template, sourceMapUrl, { preserveWhitespaces: facade.preserveWhitespaces, interpolationConfig: interpolationConfig });
  18115. if (template.errors !== undefined) {
  18116. var errors = template.errors.map(function (err) { return err.toString(); }).join(', ');
  18117. throw new Error("Errors during JIT compilation of template for " + facade.name + ": " + errors);
  18118. }
  18119. // Compile the component metadata, including template, into an expression.
  18120. // TODO(alxhub): implement inputs, outputs, queries, etc.
  18121. var res = compileComponentFromMetadata(__assign({}, facade, convertDirectiveFacadeToMetadata(facade), { selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(), template: template, wrapDirectivesAndPipesInClosure: false, styles: facade.styles || [], encapsulation: facade.encapsulation, interpolation: interpolationConfig, changeDetection: facade.changeDetection, animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null, viewProviders: facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) :
  18122. null, relativeContextFilePath: '', i18nUseExternalIds: true }), constantPool, makeBindingParser(interpolationConfig));
  18123. var preStatements = __spread(constantPool.statements, res.statements);
  18124. return this.jitExpression(res.expression, angularCoreEnv, "ng:///" + facade.name + ".js", preStatements);
  18125. };
  18126. CompilerFacadeImpl.prototype.compileBase = function (angularCoreEnv, sourceMapUrl, facade) {
  18127. var constantPool = new ConstantPool();
  18128. var typeSourceSpan = this.createParseSourceSpan('Base', facade.name, "ng:///" + facade.name + ".js");
  18129. var meta = __assign({}, facade, { typeSourceSpan: typeSourceSpan, viewQueries: facade.viewQueries ? facade.viewQueries.map(convertToR3QueryMetadata) :
  18130. facade.viewQueries, queries: facade.queries ? facade.queries.map(convertToR3QueryMetadata) : facade.queries, host: extractHostBindings(facade.propMetadata, typeSourceSpan) });
  18131. var res = compileBaseDefFromMetadata(meta, constantPool, makeBindingParser());
  18132. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
  18133. };
  18134. CompilerFacadeImpl.prototype.createParseSourceSpan = function (kind, typeName, sourceUrl) {
  18135. return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
  18136. };
  18137. /**
  18138. * JIT compiles an expression and returns the result of executing that expression.
  18139. *
  18140. * @param def the definition which will be compiled and executed to get the value to patch
  18141. * @param context an object map of @angular/core symbol names to symbols which will be available
  18142. * in the context of the compiled expression
  18143. * @param sourceUrl a URL to use for the source map of the compiled expression
  18144. * @param preStatements a collection of statements that should be evaluated before the expression.
  18145. */
  18146. CompilerFacadeImpl.prototype.jitExpression = function (def, context, sourceUrl, preStatements) {
  18147. // The ConstantPool may contain Statements which declare variables used in the final expression.
  18148. // Therefore, its statements need to precede the actual JIT operation. The final statement is a
  18149. // declaration of $def which is set to the expression being compiled.
  18150. var statements = __spread(preStatements, [
  18151. new DeclareVarStmt('$def', def, undefined, [StmtModifier.Exported]),
  18152. ]);
  18153. var res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
  18154. return res['$def'];
  18155. };
  18156. return CompilerFacadeImpl;
  18157. }());
  18158. var USE_CLASS = Object.keys({ useClass: null })[0];
  18159. var USE_FACTORY = Object.keys({ useFactory: null })[0];
  18160. var USE_VALUE = Object.keys({ useValue: null })[0];
  18161. var USE_EXISTING = Object.keys({ useExisting: null })[0];
  18162. var wrapReference = function (value) {
  18163. var wrapped = new WrappedNodeExpr(value);
  18164. return { value: wrapped, type: wrapped };
  18165. };
  18166. function convertToR3QueryMetadata(facade) {
  18167. return __assign({}, facade, { predicate: Array.isArray(facade.predicate) ? facade.predicate :
  18168. new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static });
  18169. }
  18170. function convertDirectiveFacadeToMetadata(facade) {
  18171. var inputsFromMetadata = parseInputOutputs(facade.inputs || []);
  18172. var outputsFromMetadata = parseInputOutputs(facade.outputs || []);
  18173. var propMetadata = facade.propMetadata;
  18174. var inputsFromType = {};
  18175. var outputsFromType = {};
  18176. var _loop_1 = function (field) {
  18177. if (propMetadata.hasOwnProperty(field)) {
  18178. propMetadata[field].forEach(function (ann) {
  18179. if (isInput(ann)) {
  18180. inputsFromType[field] =
  18181. ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
  18182. }
  18183. else if (isOutput(ann)) {
  18184. outputsFromType[field] = ann.bindingPropertyName || field;
  18185. }
  18186. });
  18187. }
  18188. };
  18189. for (var field in propMetadata) {
  18190. _loop_1(field);
  18191. }
  18192. return __assign({}, facade, { typeSourceSpan: facade.typeSourceSpan, type: new WrappedNodeExpr(facade.type), deps: convertR3DependencyMetadataArray(facade.deps), host: extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host), inputs: __assign({}, inputsFromMetadata, inputsFromType), outputs: __assign({}, outputsFromMetadata, outputsFromType), queries: facade.queries.map(convertToR3QueryMetadata), providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null, viewQueries: facade.viewQueries.map(convertToR3QueryMetadata) });
  18193. }
  18194. function wrapExpression(obj, property) {
  18195. if (obj.hasOwnProperty(property)) {
  18196. return new WrappedNodeExpr(obj[property]);
  18197. }
  18198. else {
  18199. return undefined;
  18200. }
  18201. }
  18202. function computeProvidedIn(providedIn) {
  18203. if (providedIn == null || typeof providedIn === 'string') {
  18204. return new LiteralExpr(providedIn);
  18205. }
  18206. else {
  18207. return new WrappedNodeExpr(providedIn);
  18208. }
  18209. }
  18210. function convertR3DependencyMetadata(facade) {
  18211. var tokenExpr;
  18212. if (facade.token === null) {
  18213. tokenExpr = new LiteralExpr(null);
  18214. }
  18215. else if (facade.resolved === R3ResolvedDependencyType.Attribute) {
  18216. tokenExpr = new LiteralExpr(facade.token);
  18217. }
  18218. else {
  18219. tokenExpr = new WrappedNodeExpr(facade.token);
  18220. }
  18221. return {
  18222. token: tokenExpr,
  18223. resolved: facade.resolved,
  18224. host: facade.host,
  18225. optional: facade.optional,
  18226. self: facade.self,
  18227. skipSelf: facade.skipSelf
  18228. };
  18229. }
  18230. function convertR3DependencyMetadataArray(facades) {
  18231. return facades == null ? null : facades.map(convertR3DependencyMetadata);
  18232. }
  18233. function extractHostBindings(propMetadata, sourceSpan, host) {
  18234. // First parse the declarations from the metadata.
  18235. var bindings = parseHostBindings(host || {});
  18236. // After that check host bindings for errors
  18237. var errors = verifyHostBindings(bindings, sourceSpan);
  18238. if (errors.length) {
  18239. throw new Error(errors.map(function (error) { return error.msg; }).join('\n'));
  18240. }
  18241. var _loop_2 = function (field) {
  18242. if (propMetadata.hasOwnProperty(field)) {
  18243. propMetadata[field].forEach(function (ann) {
  18244. if (isHostBinding(ann)) {
  18245. bindings.properties[ann.hostPropertyName || field] = field;
  18246. }
  18247. else if (isHostListener(ann)) {
  18248. bindings.listeners[ann.eventName || field] = field + "(" + (ann.args || []).join(',') + ")";
  18249. }
  18250. });
  18251. }
  18252. };
  18253. // Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
  18254. for (var field in propMetadata) {
  18255. _loop_2(field);
  18256. }
  18257. return bindings;
  18258. }
  18259. function isHostBinding(value) {
  18260. return value.ngMetadataName === 'HostBinding';
  18261. }
  18262. function isHostListener(value) {
  18263. return value.ngMetadataName === 'HostListener';
  18264. }
  18265. function isInput(value) {
  18266. return value.ngMetadataName === 'Input';
  18267. }
  18268. function isOutput(value) {
  18269. return value.ngMetadataName === 'Output';
  18270. }
  18271. function parseInputOutputs(values) {
  18272. return values.reduce(function (map, value) {
  18273. var _a = __read(value.split(',').map(function (piece) { return piece.trim(); }), 2), field = _a[0], property = _a[1];
  18274. map[field] = property || field;
  18275. return map;
  18276. }, {});
  18277. }
  18278. function publishFacade(global) {
  18279. var ng = global.ng || (global.ng = {});
  18280. ng.ɵcompilerFacade = new CompilerFacadeImpl();
  18281. }
  18282. /**
  18283. * @license
  18284. * Copyright Google Inc. All Rights Reserved.
  18285. *
  18286. * Use of this source code is governed by an MIT-style license that can be
  18287. * found in the LICENSE file at https://angular.io/license
  18288. */
  18289. var VERSION$1 = new Version('8.1.0');
  18290. /**
  18291. * @license
  18292. * Copyright Google Inc. All Rights Reserved.
  18293. *
  18294. * Use of this source code is governed by an MIT-style license that can be
  18295. * found in the LICENSE file at https://angular.io/license
  18296. */
  18297. var CompilerConfig = /** @class */ (function () {
  18298. function CompilerConfig(_a) {
  18299. var _b = _a === void 0 ? {} : _a, _c = _b.defaultEncapsulation, defaultEncapsulation = _c === void 0 ? ViewEncapsulation.Emulated : _c, _d = _b.useJit, useJit = _d === void 0 ? true : _d, _e = _b.jitDevMode, jitDevMode = _e === void 0 ? false : _e, _f = _b.missingTranslation, missingTranslation = _f === void 0 ? null : _f, preserveWhitespaces = _b.preserveWhitespaces, strictInjectionParameters = _b.strictInjectionParameters;
  18300. this.defaultEncapsulation = defaultEncapsulation;
  18301. this.useJit = !!useJit;
  18302. this.jitDevMode = !!jitDevMode;
  18303. this.missingTranslation = missingTranslation;
  18304. this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
  18305. this.strictInjectionParameters = strictInjectionParameters === true;
  18306. }
  18307. return CompilerConfig;
  18308. }());
  18309. function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting) {
  18310. if (defaultSetting === void 0) { defaultSetting = false; }
  18311. return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
  18312. }
  18313. /**
  18314. * @license
  18315. * Copyright Google Inc. All Rights Reserved.
  18316. *
  18317. * Use of this source code is governed by an MIT-style license that can be
  18318. * found in the LICENSE file at https://angular.io/license
  18319. */
  18320. var DirectiveNormalizer = /** @class */ (function () {
  18321. function DirectiveNormalizer(_resourceLoader, _urlResolver, _htmlParser, _config) {
  18322. this._resourceLoader = _resourceLoader;
  18323. this._urlResolver = _urlResolver;
  18324. this._htmlParser = _htmlParser;
  18325. this._config = _config;
  18326. this._resourceLoaderCache = new Map();
  18327. }
  18328. DirectiveNormalizer.prototype.clearCache = function () { this._resourceLoaderCache.clear(); };
  18329. DirectiveNormalizer.prototype.clearCacheFor = function (normalizedDirective) {
  18330. var _this = this;
  18331. if (!normalizedDirective.isComponent) {
  18332. return;
  18333. }
  18334. var template = normalizedDirective.template;
  18335. this._resourceLoaderCache.delete(template.templateUrl);
  18336. template.externalStylesheets.forEach(function (stylesheet) { _this._resourceLoaderCache.delete(stylesheet.moduleUrl); });
  18337. };
  18338. DirectiveNormalizer.prototype._fetch = function (url) {
  18339. var result = this._resourceLoaderCache.get(url);
  18340. if (!result) {
  18341. result = this._resourceLoader.get(url);
  18342. this._resourceLoaderCache.set(url, result);
  18343. }
  18344. return result;
  18345. };
  18346. DirectiveNormalizer.prototype.normalizeTemplate = function (prenormData) {
  18347. var _this = this;
  18348. if (isDefined(prenormData.template)) {
  18349. if (isDefined(prenormData.templateUrl)) {
  18350. throw syntaxError("'" + stringify(prenormData.componentType) + "' component cannot define both template and templateUrl");
  18351. }
  18352. if (typeof prenormData.template !== 'string') {
  18353. throw syntaxError("The template specified for component " + stringify(prenormData.componentType) + " is not a string");
  18354. }
  18355. }
  18356. else if (isDefined(prenormData.templateUrl)) {
  18357. if (typeof prenormData.templateUrl !== 'string') {
  18358. throw syntaxError("The templateUrl specified for component " + stringify(prenormData.componentType) + " is not a string");
  18359. }
  18360. }
  18361. else {
  18362. throw syntaxError("No template specified for component " + stringify(prenormData.componentType));
  18363. }
  18364. if (isDefined(prenormData.preserveWhitespaces) &&
  18365. typeof prenormData.preserveWhitespaces !== 'boolean') {
  18366. throw syntaxError("The preserveWhitespaces option for component " + stringify(prenormData.componentType) + " must be a boolean");
  18367. }
  18368. return SyncAsync.then(this._preParseTemplate(prenormData), function (preparsedTemplate) { return _this._normalizeTemplateMetadata(prenormData, preparsedTemplate); });
  18369. };
  18370. DirectiveNormalizer.prototype._preParseTemplate = function (prenomData) {
  18371. var _this = this;
  18372. var template;
  18373. var templateUrl;
  18374. if (prenomData.template != null) {
  18375. template = prenomData.template;
  18376. templateUrl = prenomData.moduleUrl;
  18377. }
  18378. else {
  18379. templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
  18380. template = this._fetch(templateUrl);
  18381. }
  18382. return SyncAsync.then(template, function (template) { return _this._preparseLoadedTemplate(prenomData, template, templateUrl); });
  18383. };
  18384. DirectiveNormalizer.prototype._preparseLoadedTemplate = function (prenormData, template, templateAbsUrl) {
  18385. var isInline = !!prenormData.template;
  18386. var interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
  18387. var templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline: isInline, templateUrl: templateAbsUrl });
  18388. var rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  18389. if (rootNodesAndErrors.errors.length > 0) {
  18390. var errorString = rootNodesAndErrors.errors.join('\n');
  18391. throw syntaxError("Template parse errors:\n" + errorString);
  18392. }
  18393. var templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
  18394. var visitor = new TemplatePreparseVisitor();
  18395. visitAll$1(visitor, rootNodesAndErrors.rootNodes);
  18396. var templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
  18397. var styles = templateMetadataStyles.styles.concat(templateStyles.styles);
  18398. var inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
  18399. var styleUrls = this
  18400. ._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
  18401. .styleUrls;
  18402. return {
  18403. template: template,
  18404. templateUrl: templateAbsUrl, isInline: isInline,
  18405. htmlAst: rootNodesAndErrors, styles: styles, inlineStyleUrls: inlineStyleUrls, styleUrls: styleUrls,
  18406. ngContentSelectors: visitor.ngContentSelectors,
  18407. };
  18408. };
  18409. DirectiveNormalizer.prototype._normalizeTemplateMetadata = function (prenormData, preparsedTemplate) {
  18410. var _this = this;
  18411. return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), function (externalStylesheets) { return _this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets); });
  18412. };
  18413. DirectiveNormalizer.prototype._normalizeLoadedTemplateMetadata = function (prenormData, preparsedTemplate, stylesheets) {
  18414. // Algorithm:
  18415. // - produce exactly 1 entry per original styleUrl in
  18416. // CompileTemplateMetadata.externalStylesheets with all styles inlined
  18417. // - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
  18418. // Reason: be able to determine how many stylesheets there are even without loading
  18419. // the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
  18420. // (as resource loading may be async)
  18421. var _this = this;
  18422. var styles = __spread(preparsedTemplate.styles);
  18423. this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
  18424. var styleUrls = preparsedTemplate.styleUrls;
  18425. var externalStylesheets = styleUrls.map(function (styleUrl) {
  18426. var stylesheet = stylesheets.get(styleUrl);
  18427. var styles = __spread(stylesheet.styles);
  18428. _this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
  18429. return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
  18430. });
  18431. var encapsulation = prenormData.encapsulation;
  18432. if (encapsulation == null) {
  18433. encapsulation = this._config.defaultEncapsulation;
  18434. }
  18435. if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
  18436. styleUrls.length === 0) {
  18437. encapsulation = ViewEncapsulation.None;
  18438. }
  18439. return new CompileTemplateMetadata({
  18440. encapsulation: encapsulation,
  18441. template: preparsedTemplate.template,
  18442. templateUrl: preparsedTemplate.templateUrl,
  18443. htmlAst: preparsedTemplate.htmlAst, styles: styles, styleUrls: styleUrls,
  18444. ngContentSelectors: preparsedTemplate.ngContentSelectors,
  18445. animations: prenormData.animations,
  18446. interpolation: prenormData.interpolation,
  18447. isInline: preparsedTemplate.isInline, externalStylesheets: externalStylesheets,
  18448. preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
  18449. });
  18450. };
  18451. DirectiveNormalizer.prototype._inlineStyles = function (styleUrls, stylesheets, targetStyles) {
  18452. var _this = this;
  18453. styleUrls.forEach(function (styleUrl) {
  18454. var stylesheet = stylesheets.get(styleUrl);
  18455. stylesheet.styles.forEach(function (style) { return targetStyles.push(style); });
  18456. _this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
  18457. });
  18458. };
  18459. DirectiveNormalizer.prototype._loadMissingExternalStylesheets = function (styleUrls, loadedStylesheets) {
  18460. var _this = this;
  18461. if (loadedStylesheets === void 0) { loadedStylesheets = new Map(); }
  18462. return SyncAsync.then(SyncAsync.all(styleUrls.filter(function (styleUrl) { return !loadedStylesheets.has(styleUrl); })
  18463. .map(function (styleUrl) { return SyncAsync.then(_this._fetch(styleUrl), function (loadedStyle) {
  18464. var stylesheet = _this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
  18465. loadedStylesheets.set(styleUrl, stylesheet);
  18466. return _this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
  18467. }); })), function (_) { return loadedStylesheets; });
  18468. };
  18469. DirectiveNormalizer.prototype._normalizeStylesheet = function (stylesheet) {
  18470. var _this = this;
  18471. var moduleUrl = stylesheet.moduleUrl;
  18472. var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
  18473. .map(function (url) { return _this._urlResolver.resolve(moduleUrl, url); });
  18474. var allStyles = stylesheet.styles.map(function (style) {
  18475. var styleWithImports = extractStyleUrls(_this._urlResolver, moduleUrl, style);
  18476. allStyleUrls.push.apply(allStyleUrls, __spread(styleWithImports.styleUrls));
  18477. return styleWithImports.style;
  18478. });
  18479. return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
  18480. };
  18481. return DirectiveNormalizer;
  18482. }());
  18483. var TemplatePreparseVisitor = /** @class */ (function () {
  18484. function TemplatePreparseVisitor() {
  18485. this.ngContentSelectors = [];
  18486. this.styles = [];
  18487. this.styleUrls = [];
  18488. this.ngNonBindableStackCount = 0;
  18489. }
  18490. TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
  18491. var preparsedElement = preparseElement(ast);
  18492. switch (preparsedElement.type) {
  18493. case PreparsedElementType.NG_CONTENT:
  18494. if (this.ngNonBindableStackCount === 0) {
  18495. this.ngContentSelectors.push(preparsedElement.selectAttr);
  18496. }
  18497. break;
  18498. case PreparsedElementType.STYLE:
  18499. var textContent_1 = '';
  18500. ast.children.forEach(function (child) {
  18501. if (child instanceof Text$3) {
  18502. textContent_1 += child.value;
  18503. }
  18504. });
  18505. this.styles.push(textContent_1);
  18506. break;
  18507. case PreparsedElementType.STYLESHEET:
  18508. this.styleUrls.push(preparsedElement.hrefAttr);
  18509. break;
  18510. default:
  18511. break;
  18512. }
  18513. if (preparsedElement.nonBindable) {
  18514. this.ngNonBindableStackCount++;
  18515. }
  18516. visitAll$1(this, ast.children);
  18517. if (preparsedElement.nonBindable) {
  18518. this.ngNonBindableStackCount--;
  18519. }
  18520. return null;
  18521. };
  18522. TemplatePreparseVisitor.prototype.visitExpansion = function (ast, context) { visitAll$1(this, ast.cases); };
  18523. TemplatePreparseVisitor.prototype.visitExpansionCase = function (ast, context) {
  18524. visitAll$1(this, ast.expression);
  18525. };
  18526. TemplatePreparseVisitor.prototype.visitComment = function (ast, context) { return null; };
  18527. TemplatePreparseVisitor.prototype.visitAttribute = function (ast, context) { return null; };
  18528. TemplatePreparseVisitor.prototype.visitText = function (ast, context) { return null; };
  18529. return TemplatePreparseVisitor;
  18530. }());
  18531. /**
  18532. * @license
  18533. * Copyright Google Inc. All Rights Reserved.
  18534. *
  18535. * Use of this source code is governed by an MIT-style license that can be
  18536. * found in the LICENSE file at https://angular.io/license
  18537. */
  18538. var QUERY_METADATA_IDENTIFIERS = [
  18539. createViewChild,
  18540. createViewChildren,
  18541. createContentChild,
  18542. createContentChildren,
  18543. ];
  18544. /*
  18545. * Resolve a `Type` for {@link Directive}.
  18546. *
  18547. * This interface can be overridden by the application developer to create custom behavior.
  18548. *
  18549. * See {@link Compiler}
  18550. */
  18551. var DirectiveResolver = /** @class */ (function () {
  18552. function DirectiveResolver(_reflector) {
  18553. this._reflector = _reflector;
  18554. }
  18555. DirectiveResolver.prototype.isDirective = function (type) {
  18556. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  18557. return typeMetadata && typeMetadata.some(isDirectiveMetadata);
  18558. };
  18559. DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) {
  18560. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  18561. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  18562. if (typeMetadata) {
  18563. var metadata = findLast(typeMetadata, isDirectiveMetadata);
  18564. if (metadata) {
  18565. var propertyMetadata = this._reflector.propMetadata(type);
  18566. var guards = this._reflector.guards(type);
  18567. return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
  18568. }
  18569. }
  18570. if (throwIfNotFound) {
  18571. throw new Error("No Directive annotation found on " + stringify(type));
  18572. }
  18573. return null;
  18574. };
  18575. DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata, guards, directiveType) {
  18576. var inputs = [];
  18577. var outputs = [];
  18578. var host = {};
  18579. var queries = {};
  18580. Object.keys(propertyMetadata).forEach(function (propName) {
  18581. var input = findLast(propertyMetadata[propName], function (a) { return createInput.isTypeOf(a); });
  18582. if (input) {
  18583. if (input.bindingPropertyName) {
  18584. inputs.push(propName + ": " + input.bindingPropertyName);
  18585. }
  18586. else {
  18587. inputs.push(propName);
  18588. }
  18589. }
  18590. var output = findLast(propertyMetadata[propName], function (a) { return createOutput.isTypeOf(a); });
  18591. if (output) {
  18592. if (output.bindingPropertyName) {
  18593. outputs.push(propName + ": " + output.bindingPropertyName);
  18594. }
  18595. else {
  18596. outputs.push(propName);
  18597. }
  18598. }
  18599. var hostBindings = propertyMetadata[propName].filter(function (a) { return createHostBinding.isTypeOf(a); });
  18600. hostBindings.forEach(function (hostBinding) {
  18601. if (hostBinding.hostPropertyName) {
  18602. var startWith = hostBinding.hostPropertyName[0];
  18603. if (startWith === '(') {
  18604. throw new Error("@HostBinding can not bind to events. Use @HostListener instead.");
  18605. }
  18606. else if (startWith === '[') {
  18607. throw new Error("@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.");
  18608. }
  18609. host["[" + hostBinding.hostPropertyName + "]"] = propName;
  18610. }
  18611. else {
  18612. host["[" + propName + "]"] = propName;
  18613. }
  18614. });
  18615. var hostListeners = propertyMetadata[propName].filter(function (a) { return createHostListener.isTypeOf(a); });
  18616. hostListeners.forEach(function (hostListener) {
  18617. var args = hostListener.args || [];
  18618. host["(" + hostListener.eventName + ")"] = propName + "(" + args.join(',') + ")";
  18619. });
  18620. var query = findLast(propertyMetadata[propName], function (a) { return QUERY_METADATA_IDENTIFIERS.some(function (i) { return i.isTypeOf(a); }); });
  18621. if (query) {
  18622. queries[propName] = query;
  18623. }
  18624. });
  18625. return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
  18626. };
  18627. DirectiveResolver.prototype._extractPublicName = function (def) { return splitAtColon(def, [null, def])[1].trim(); };
  18628. DirectiveResolver.prototype._dedupeBindings = function (bindings) {
  18629. var names = new Set();
  18630. var publicNames = new Set();
  18631. var reversedResult = [];
  18632. // go last to first to allow later entries to overwrite previous entries
  18633. for (var i = bindings.length - 1; i >= 0; i--) {
  18634. var binding = bindings[i];
  18635. var name_1 = this._extractPublicName(binding);
  18636. publicNames.add(name_1);
  18637. if (!names.has(name_1)) {
  18638. names.add(name_1);
  18639. reversedResult.push(binding);
  18640. }
  18641. }
  18642. return reversedResult.reverse();
  18643. };
  18644. DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, guards, directiveType) {
  18645. var mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
  18646. var mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
  18647. var mergedHost = directive.host ? __assign({}, directive.host, host) : host;
  18648. var mergedQueries = directive.queries ? __assign({}, directive.queries, queries) : queries;
  18649. if (createComponent.isTypeOf(directive)) {
  18650. var comp = directive;
  18651. return createComponent({
  18652. selector: comp.selector,
  18653. inputs: mergedInputs,
  18654. outputs: mergedOutputs,
  18655. host: mergedHost,
  18656. exportAs: comp.exportAs,
  18657. moduleId: comp.moduleId,
  18658. queries: mergedQueries,
  18659. changeDetection: comp.changeDetection,
  18660. providers: comp.providers,
  18661. viewProviders: comp.viewProviders,
  18662. entryComponents: comp.entryComponents,
  18663. template: comp.template,
  18664. templateUrl: comp.templateUrl,
  18665. styles: comp.styles,
  18666. styleUrls: comp.styleUrls,
  18667. encapsulation: comp.encapsulation,
  18668. animations: comp.animations,
  18669. interpolation: comp.interpolation,
  18670. preserveWhitespaces: directive.preserveWhitespaces,
  18671. });
  18672. }
  18673. else {
  18674. return createDirective({
  18675. selector: directive.selector,
  18676. inputs: mergedInputs,
  18677. outputs: mergedOutputs,
  18678. host: mergedHost,
  18679. exportAs: directive.exportAs,
  18680. queries: mergedQueries,
  18681. providers: directive.providers, guards: guards
  18682. });
  18683. }
  18684. };
  18685. return DirectiveResolver;
  18686. }());
  18687. function isDirectiveMetadata(type) {
  18688. return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
  18689. }
  18690. function findLast(arr, condition) {
  18691. for (var i = arr.length - 1; i >= 0; i--) {
  18692. if (condition(arr[i])) {
  18693. return arr[i];
  18694. }
  18695. }
  18696. return null;
  18697. }
  18698. /**
  18699. * @license
  18700. * Copyright Google Inc. All Rights Reserved.
  18701. *
  18702. * Use of this source code is governed by an MIT-style license that can be
  18703. * found in the LICENSE file at https://angular.io/license
  18704. */
  18705. /**
  18706. * An i18n error.
  18707. */
  18708. var I18nError = /** @class */ (function (_super) {
  18709. __extends(I18nError, _super);
  18710. function I18nError(span, msg) {
  18711. return _super.call(this, span, msg) || this;
  18712. }
  18713. return I18nError;
  18714. }(ParseError));
  18715. /**
  18716. * @license
  18717. * Copyright Google Inc. All Rights Reserved.
  18718. *
  18719. * Use of this source code is governed by an MIT-style license that can be
  18720. * found in the LICENSE file at https://angular.io/license
  18721. */
  18722. var _I18N_ATTR = 'i18n';
  18723. var _I18N_ATTR_PREFIX = 'i18n-';
  18724. var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
  18725. var MEANING_SEPARATOR = '|';
  18726. var ID_SEPARATOR = '@@';
  18727. var i18nCommentsWarned = false;
  18728. /**
  18729. * Extract translatable messages from an html AST
  18730. */
  18731. function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
  18732. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  18733. return visitor.extract(nodes, interpolationConfig);
  18734. }
  18735. function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
  18736. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  18737. return visitor.merge(nodes, translations, interpolationConfig);
  18738. }
  18739. var ExtractionResult = /** @class */ (function () {
  18740. function ExtractionResult(messages, errors) {
  18741. this.messages = messages;
  18742. this.errors = errors;
  18743. }
  18744. return ExtractionResult;
  18745. }());
  18746. var _VisitorMode;
  18747. (function (_VisitorMode) {
  18748. _VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
  18749. _VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
  18750. })(_VisitorMode || (_VisitorMode = {}));
  18751. /**
  18752. * This Visitor is used:
  18753. * 1. to extract all the translatable strings from an html AST (see `extract()`),
  18754. * 2. to replace the translatable strings with the actual translations (see `merge()`)
  18755. *
  18756. * @internal
  18757. */
  18758. var _Visitor$2 = /** @class */ (function () {
  18759. function _Visitor(_implicitTags, _implicitAttrs) {
  18760. this._implicitTags = _implicitTags;
  18761. this._implicitAttrs = _implicitAttrs;
  18762. }
  18763. /**
  18764. * Extracts the messages from the tree
  18765. */
  18766. _Visitor.prototype.extract = function (nodes, interpolationConfig) {
  18767. var _this = this;
  18768. this._init(_VisitorMode.Extract, interpolationConfig);
  18769. nodes.forEach(function (node) { return node.visit(_this, null); });
  18770. if (this._inI18nBlock) {
  18771. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  18772. }
  18773. return new ExtractionResult(this._messages, this._errors);
  18774. };
  18775. /**
  18776. * Returns a tree where all translatable nodes are translated
  18777. */
  18778. _Visitor.prototype.merge = function (nodes, translations, interpolationConfig) {
  18779. this._init(_VisitorMode.Merge, interpolationConfig);
  18780. this._translations = translations;
  18781. // Construct a single fake root element
  18782. var wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
  18783. var translatedNode = wrapper.visit(this, null);
  18784. if (this._inI18nBlock) {
  18785. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  18786. }
  18787. return new ParseTreeResult(translatedNode.children, this._errors);
  18788. };
  18789. _Visitor.prototype.visitExpansionCase = function (icuCase, context) {
  18790. // Parse cases for translatable html attributes
  18791. var expression = visitAll$1(this, icuCase.expression, context);
  18792. if (this._mode === _VisitorMode.Merge) {
  18793. return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
  18794. }
  18795. };
  18796. _Visitor.prototype.visitExpansion = function (icu, context) {
  18797. this._mayBeAddBlockChildren(icu);
  18798. var wasInIcu = this._inIcu;
  18799. if (!this._inIcu) {
  18800. // nested ICU messages should not be extracted but top-level translated as a whole
  18801. if (this._isInTranslatableSection) {
  18802. this._addMessage([icu]);
  18803. }
  18804. this._inIcu = true;
  18805. }
  18806. var cases = visitAll$1(this, icu.cases, context);
  18807. if (this._mode === _VisitorMode.Merge) {
  18808. icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
  18809. }
  18810. this._inIcu = wasInIcu;
  18811. return icu;
  18812. };
  18813. _Visitor.prototype.visitComment = function (comment, context) {
  18814. var isOpening = _isOpeningComment(comment);
  18815. if (isOpening && this._isInTranslatableSection) {
  18816. this._reportError(comment, 'Could not start a block inside a translatable section');
  18817. return;
  18818. }
  18819. var isClosing = _isClosingComment(comment);
  18820. if (isClosing && !this._inI18nBlock) {
  18821. this._reportError(comment, 'Trying to close an unopened block');
  18822. return;
  18823. }
  18824. if (!this._inI18nNode && !this._inIcu) {
  18825. if (!this._inI18nBlock) {
  18826. if (isOpening) {
  18827. // deprecated from v5 you should use <ng-container i18n> instead of i18n comments
  18828. if (!i18nCommentsWarned && console && console.warn) {
  18829. i18nCommentsWarned = true;
  18830. var details = comment.sourceSpan.details ? ", " + comment.sourceSpan.details : '';
  18831. // TODO(ocombe): use a log service once there is a public one available
  18832. console.warn("I18n comments are deprecated, use an <ng-container> element instead (" + comment.sourceSpan.start + details + ")");
  18833. }
  18834. this._inI18nBlock = true;
  18835. this._blockStartDepth = this._depth;
  18836. this._blockChildren = [];
  18837. this._blockMeaningAndDesc =
  18838. comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
  18839. this._openTranslatableSection(comment);
  18840. }
  18841. }
  18842. else {
  18843. if (isClosing) {
  18844. if (this._depth == this._blockStartDepth) {
  18845. this._closeTranslatableSection(comment, this._blockChildren);
  18846. this._inI18nBlock = false;
  18847. var message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
  18848. // merge attributes in sections
  18849. var nodes = this._translateMessage(comment, message);
  18850. return visitAll$1(this, nodes);
  18851. }
  18852. else {
  18853. this._reportError(comment, 'I18N blocks should not cross element boundaries');
  18854. return;
  18855. }
  18856. }
  18857. }
  18858. }
  18859. };
  18860. _Visitor.prototype.visitText = function (text, context) {
  18861. if (this._isInTranslatableSection) {
  18862. this._mayBeAddBlockChildren(text);
  18863. }
  18864. return text;
  18865. };
  18866. _Visitor.prototype.visitElement = function (el, context) {
  18867. var _this = this;
  18868. this._mayBeAddBlockChildren(el);
  18869. this._depth++;
  18870. var wasInI18nNode = this._inI18nNode;
  18871. var wasInImplicitNode = this._inImplicitNode;
  18872. var childNodes = [];
  18873. var translatedChildNodes = undefined;
  18874. // Extract:
  18875. // - top level nodes with the (implicit) "i18n" attribute if not already in a section
  18876. // - ICU messages
  18877. var i18nAttr = _getI18nAttr(el);
  18878. var i18nMeta = i18nAttr ? i18nAttr.value : '';
  18879. var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
  18880. !this._isInTranslatableSection;
  18881. var isTopLevelImplicit = !wasInImplicitNode && isImplicit;
  18882. this._inImplicitNode = wasInImplicitNode || isImplicit;
  18883. if (!this._isInTranslatableSection && !this._inIcu) {
  18884. if (i18nAttr || isTopLevelImplicit) {
  18885. this._inI18nNode = true;
  18886. var message = this._addMessage(el.children, i18nMeta);
  18887. translatedChildNodes = this._translateMessage(el, message);
  18888. }
  18889. if (this._mode == _VisitorMode.Extract) {
  18890. var isTranslatable = i18nAttr || isTopLevelImplicit;
  18891. if (isTranslatable)
  18892. this._openTranslatableSection(el);
  18893. visitAll$1(this, el.children);
  18894. if (isTranslatable)
  18895. this._closeTranslatableSection(el, el.children);
  18896. }
  18897. }
  18898. else {
  18899. if (i18nAttr || isTopLevelImplicit) {
  18900. this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
  18901. }
  18902. if (this._mode == _VisitorMode.Extract) {
  18903. // Descend into child nodes for extraction
  18904. visitAll$1(this, el.children);
  18905. }
  18906. }
  18907. if (this._mode === _VisitorMode.Merge) {
  18908. var visitNodes = translatedChildNodes || el.children;
  18909. visitNodes.forEach(function (child) {
  18910. var visited = child.visit(_this, context);
  18911. if (visited && !_this._isInTranslatableSection) {
  18912. // Do not add the children from translatable sections (= i18n blocks here)
  18913. // They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
  18914. childNodes = childNodes.concat(visited);
  18915. }
  18916. });
  18917. }
  18918. this._visitAttributesOf(el);
  18919. this._depth--;
  18920. this._inI18nNode = wasInI18nNode;
  18921. this._inImplicitNode = wasInImplicitNode;
  18922. if (this._mode === _VisitorMode.Merge) {
  18923. var translatedAttrs = this._translateAttributes(el);
  18924. return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
  18925. }
  18926. return null;
  18927. };
  18928. _Visitor.prototype.visitAttribute = function (attribute, context) {
  18929. throw new Error('unreachable code');
  18930. };
  18931. _Visitor.prototype._init = function (mode, interpolationConfig) {
  18932. this._mode = mode;
  18933. this._inI18nBlock = false;
  18934. this._inI18nNode = false;
  18935. this._depth = 0;
  18936. this._inIcu = false;
  18937. this._msgCountAtSectionStart = undefined;
  18938. this._errors = [];
  18939. this._messages = [];
  18940. this._inImplicitNode = false;
  18941. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  18942. };
  18943. // looks for translatable attributes
  18944. _Visitor.prototype._visitAttributesOf = function (el) {
  18945. var _this = this;
  18946. var explicitAttrNameToValue = {};
  18947. var implicitAttrNames = this._implicitAttrs[el.name] || [];
  18948. el.attrs.filter(function (attr) { return attr.name.startsWith(_I18N_ATTR_PREFIX); })
  18949. .forEach(function (attr) { return explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  18950. attr.value; });
  18951. el.attrs.forEach(function (attr) {
  18952. if (attr.name in explicitAttrNameToValue) {
  18953. _this._addMessage([attr], explicitAttrNameToValue[attr.name]);
  18954. }
  18955. else if (implicitAttrNames.some(function (name) { return attr.name === name; })) {
  18956. _this._addMessage([attr]);
  18957. }
  18958. });
  18959. };
  18960. // add a translatable message
  18961. _Visitor.prototype._addMessage = function (ast, msgMeta) {
  18962. if (ast.length == 0 ||
  18963. ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
  18964. // Do not create empty messages
  18965. return null;
  18966. }
  18967. var _a = _parseMessageMeta(msgMeta), meaning = _a.meaning, description = _a.description, id = _a.id;
  18968. var message = this._createI18nMessage(ast, meaning, description, id);
  18969. this._messages.push(message);
  18970. return message;
  18971. };
  18972. // Translates the given message given the `TranslationBundle`
  18973. // This is used for translating elements / blocks - see `_translateAttributes` for attributes
  18974. // no-op when called in extraction mode (returns [])
  18975. _Visitor.prototype._translateMessage = function (el, message) {
  18976. if (message && this._mode === _VisitorMode.Merge) {
  18977. var nodes = this._translations.get(message);
  18978. if (nodes) {
  18979. return nodes;
  18980. }
  18981. this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
  18982. }
  18983. return [];
  18984. };
  18985. // translate the attributes of an element and remove i18n specific attributes
  18986. _Visitor.prototype._translateAttributes = function (el) {
  18987. var _this = this;
  18988. var attributes = el.attrs;
  18989. var i18nParsedMessageMeta = {};
  18990. attributes.forEach(function (attr) {
  18991. if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  18992. i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  18993. _parseMessageMeta(attr.value);
  18994. }
  18995. });
  18996. var translatedAttributes = [];
  18997. attributes.forEach(function (attr) {
  18998. if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  18999. // strip i18n specific attributes
  19000. return;
  19001. }
  19002. if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
  19003. var _a = i18nParsedMessageMeta[attr.name], meaning = _a.meaning, description = _a.description, id = _a.id;
  19004. var message = _this._createI18nMessage([attr], meaning, description, id);
  19005. var nodes = _this._translations.get(message);
  19006. if (nodes) {
  19007. if (nodes.length == 0) {
  19008. translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan));
  19009. }
  19010. else if (nodes[0] instanceof Text$3) {
  19011. var value = nodes[0].value;
  19012. translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan));
  19013. }
  19014. else {
  19015. _this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  19016. }
  19017. }
  19018. else {
  19019. _this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  19020. }
  19021. }
  19022. else {
  19023. translatedAttributes.push(attr);
  19024. }
  19025. });
  19026. return translatedAttributes;
  19027. };
  19028. /**
  19029. * Add the node as a child of the block when:
  19030. * - we are in a block,
  19031. * - we are not inside a ICU message (those are handled separately),
  19032. * - the node is a "direct child" of the block
  19033. */
  19034. _Visitor.prototype._mayBeAddBlockChildren = function (node) {
  19035. if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
  19036. this._blockChildren.push(node);
  19037. }
  19038. };
  19039. /**
  19040. * Marks the start of a section, see `_closeTranslatableSection`
  19041. */
  19042. _Visitor.prototype._openTranslatableSection = function (node) {
  19043. if (this._isInTranslatableSection) {
  19044. this._reportError(node, 'Unexpected section start');
  19045. }
  19046. else {
  19047. this._msgCountAtSectionStart = this._messages.length;
  19048. }
  19049. };
  19050. Object.defineProperty(_Visitor.prototype, "_isInTranslatableSection", {
  19051. /**
  19052. * A translatable section could be:
  19053. * - the content of translatable element,
  19054. * - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
  19055. */
  19056. get: function () {
  19057. return this._msgCountAtSectionStart !== void 0;
  19058. },
  19059. enumerable: true,
  19060. configurable: true
  19061. });
  19062. /**
  19063. * Terminates a section.
  19064. *
  19065. * If a section has only one significant children (comments not significant) then we should not
  19066. * keep the message from this children:
  19067. *
  19068. * `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
  19069. * - one for the <p> content with meaning and description,
  19070. * - another one for the ICU message.
  19071. *
  19072. * In this case the last message is discarded as it contains less information (the AST is
  19073. * otherwise identical).
  19074. *
  19075. * Note that we should still keep messages extracted from attributes inside the section (ie in the
  19076. * ICU message here)
  19077. */
  19078. _Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
  19079. if (!this._isInTranslatableSection) {
  19080. this._reportError(node, 'Unexpected section end');
  19081. return;
  19082. }
  19083. var startIndex = this._msgCountAtSectionStart;
  19084. var significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment ? 0 : 1); }, 0);
  19085. if (significantChildren == 1) {
  19086. for (var i = this._messages.length - 1; i >= startIndex; i--) {
  19087. var ast = this._messages[i].nodes;
  19088. if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
  19089. this._messages.splice(i, 1);
  19090. break;
  19091. }
  19092. }
  19093. }
  19094. this._msgCountAtSectionStart = undefined;
  19095. };
  19096. _Visitor.prototype._reportError = function (node, msg) {
  19097. this._errors.push(new I18nError(node.sourceSpan, msg));
  19098. };
  19099. return _Visitor;
  19100. }());
  19101. function _isOpeningComment(n) {
  19102. return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
  19103. }
  19104. function _isClosingComment(n) {
  19105. return !!(n instanceof Comment && n.value && n.value === '/i18n');
  19106. }
  19107. function _getI18nAttr(p) {
  19108. return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
  19109. }
  19110. function _parseMessageMeta(i18n) {
  19111. if (!i18n)
  19112. return { meaning: '', description: '', id: '' };
  19113. var idIndex = i18n.indexOf(ID_SEPARATOR);
  19114. var descIndex = i18n.indexOf(MEANING_SEPARATOR);
  19115. var _a = __read((idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  19116. var _b = __read((descIndex > -1) ?
  19117. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  19118. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  19119. return { meaning: meaning, description: description, id: id };
  19120. }
  19121. /**
  19122. * @license
  19123. * Copyright Google Inc. All Rights Reserved.
  19124. *
  19125. * Use of this source code is governed by an MIT-style license that can be
  19126. * found in the LICENSE file at https://angular.io/license
  19127. */
  19128. var XmlTagDefinition = /** @class */ (function () {
  19129. function XmlTagDefinition() {
  19130. this.closedByParent = false;
  19131. this.contentType = TagContentType.PARSABLE_DATA;
  19132. this.isVoid = false;
  19133. this.ignoreFirstLf = false;
  19134. this.canSelfClose = true;
  19135. }
  19136. XmlTagDefinition.prototype.requireExtraParent = function (currentParent) { return false; };
  19137. XmlTagDefinition.prototype.isClosedByChild = function (name) { return false; };
  19138. return XmlTagDefinition;
  19139. }());
  19140. var _TAG_DEFINITION = new XmlTagDefinition();
  19141. function getXmlTagDefinition(tagName) {
  19142. return _TAG_DEFINITION;
  19143. }
  19144. /**
  19145. * @license
  19146. * Copyright Google Inc. All Rights Reserved.
  19147. *
  19148. * Use of this source code is governed by an MIT-style license that can be
  19149. * found in the LICENSE file at https://angular.io/license
  19150. */
  19151. var XmlParser = /** @class */ (function (_super) {
  19152. __extends(XmlParser, _super);
  19153. function XmlParser() {
  19154. return _super.call(this, getXmlTagDefinition) || this;
  19155. }
  19156. XmlParser.prototype.parse = function (source, url, options) {
  19157. return _super.prototype.parse.call(this, source, url, options);
  19158. };
  19159. return XmlParser;
  19160. }(Parser));
  19161. /**
  19162. * @license
  19163. * Copyright Google Inc. All Rights Reserved.
  19164. *
  19165. * Use of this source code is governed by an MIT-style license that can be
  19166. * found in the LICENSE file at https://angular.io/license
  19167. */
  19168. var _VERSION = '1.2';
  19169. var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
  19170. // TODO(vicb): make this a param (s/_/-/)
  19171. var _DEFAULT_SOURCE_LANG = 'en';
  19172. var _PLACEHOLDER_TAG$1 = 'x';
  19173. var _MARKER_TAG = 'mrk';
  19174. var _FILE_TAG = 'file';
  19175. var _SOURCE_TAG$1 = 'source';
  19176. var _SEGMENT_SOURCE_TAG = 'seg-source';
  19177. var _TARGET_TAG = 'target';
  19178. var _UNIT_TAG = 'trans-unit';
  19179. var _CONTEXT_GROUP_TAG = 'context-group';
  19180. var _CONTEXT_TAG = 'context';
  19181. // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
  19182. // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
  19183. var Xliff = /** @class */ (function (_super) {
  19184. __extends(Xliff, _super);
  19185. function Xliff() {
  19186. return _super !== null && _super.apply(this, arguments) || this;
  19187. }
  19188. Xliff.prototype.write = function (messages, locale) {
  19189. var visitor = new _WriteVisitor();
  19190. var transUnits = [];
  19191. messages.forEach(function (message) {
  19192. var _a;
  19193. var contextTags = [];
  19194. message.sources.forEach(function (source) {
  19195. var contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
  19196. 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));
  19197. contextTags.push(new CR(8), contextGroupTag);
  19198. });
  19199. var transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
  19200. (_a = transUnit.children).push.apply(_a, __spread([new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes))], contextTags));
  19201. if (message.description) {
  19202. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
  19203. }
  19204. if (message.meaning) {
  19205. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
  19206. }
  19207. transUnit.children.push(new CR(6));
  19208. transUnits.push(new CR(6), transUnit);
  19209. });
  19210. var body = new Tag('body', {}, __spread(transUnits, [new CR(4)]));
  19211. var file = new Tag('file', {
  19212. 'source-language': locale || _DEFAULT_SOURCE_LANG,
  19213. datatype: 'plaintext',
  19214. original: 'ng2.template',
  19215. }, [new CR(4), body, new CR(2)]);
  19216. var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
  19217. return serialize([
  19218. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  19219. ]);
  19220. };
  19221. Xliff.prototype.load = function (content, url) {
  19222. // xliff to xml nodes
  19223. var xliffParser = new XliffParser();
  19224. var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19225. // xml nodes to i18n nodes
  19226. var i18nNodesByMsgId = {};
  19227. var converter = new XmlToI18n();
  19228. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19229. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  19230. errors.push.apply(errors, __spread(e));
  19231. i18nNodesByMsgId[msgId] = i18nNodes;
  19232. });
  19233. if (errors.length) {
  19234. throw new Error("xliff parse errors:\n" + errors.join('\n'));
  19235. }
  19236. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19237. };
  19238. Xliff.prototype.digest = function (message) { return digest(message); };
  19239. return Xliff;
  19240. }(Serializer));
  19241. var _WriteVisitor = /** @class */ (function () {
  19242. function _WriteVisitor() {
  19243. }
  19244. _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  19245. _WriteVisitor.prototype.visitContainer = function (container, context) {
  19246. var _this = this;
  19247. var nodes = [];
  19248. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  19249. return nodes;
  19250. };
  19251. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  19252. var _this = this;
  19253. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  19254. Object.keys(icu.cases).forEach(function (c) {
  19255. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  19256. });
  19257. nodes.push(new Text$2("}"));
  19258. return nodes;
  19259. };
  19260. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19261. var ctype = getCtypeForTag(ph.tag);
  19262. if (ph.isVoid) {
  19263. // void tags have no children nor closing tags
  19264. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + "/>" })];
  19265. }
  19266. var startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + ">" });
  19267. var closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype: ctype, 'equiv-text': "</" + ph.tag + ">" });
  19268. return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
  19269. };
  19270. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  19271. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': "{{" + ph.value + "}}" })];
  19272. };
  19273. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  19274. var equivText = "{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}";
  19275. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
  19276. };
  19277. _WriteVisitor.prototype.serialize = function (nodes) {
  19278. var _this = this;
  19279. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  19280. };
  19281. return _WriteVisitor;
  19282. }());
  19283. // TODO(vicb): add error management (structure)
  19284. // Extract messages as xml nodes from the xliff file
  19285. var XliffParser = /** @class */ (function () {
  19286. function XliffParser() {
  19287. this._locale = null;
  19288. }
  19289. XliffParser.prototype.parse = function (xliff, url) {
  19290. this._unitMlString = null;
  19291. this._msgIdToHtml = {};
  19292. var xml = new XmlParser().parse(xliff, url);
  19293. this._errors = xml.errors;
  19294. visitAll$1(this, xml.rootNodes, null);
  19295. return {
  19296. msgIdToHtml: this._msgIdToHtml,
  19297. errors: this._errors,
  19298. locale: this._locale,
  19299. };
  19300. };
  19301. XliffParser.prototype.visitElement = function (element, context) {
  19302. switch (element.name) {
  19303. case _UNIT_TAG:
  19304. this._unitMlString = null;
  19305. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19306. if (!idAttr) {
  19307. this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
  19308. }
  19309. else {
  19310. var id = idAttr.value;
  19311. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19312. this._addError(element, "Duplicated translations for msg " + id);
  19313. }
  19314. else {
  19315. visitAll$1(this, element.children, null);
  19316. if (typeof this._unitMlString === 'string') {
  19317. this._msgIdToHtml[id] = this._unitMlString;
  19318. }
  19319. else {
  19320. this._addError(element, "Message " + id + " misses a translation");
  19321. }
  19322. }
  19323. }
  19324. break;
  19325. // ignore those tags
  19326. case _SOURCE_TAG$1:
  19327. case _SEGMENT_SOURCE_TAG:
  19328. break;
  19329. case _TARGET_TAG:
  19330. var innerTextStart = element.startSourceSpan.end.offset;
  19331. var innerTextEnd = element.endSourceSpan.start.offset;
  19332. var content = element.startSourceSpan.start.file.content;
  19333. var innerText = content.slice(innerTextStart, innerTextEnd);
  19334. this._unitMlString = innerText;
  19335. break;
  19336. case _FILE_TAG:
  19337. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
  19338. if (localeAttr) {
  19339. this._locale = localeAttr.value;
  19340. }
  19341. visitAll$1(this, element.children, null);
  19342. break;
  19343. default:
  19344. // TODO(vicb): assert file structure, xliff version
  19345. // For now only recurse on unhandled nodes
  19346. visitAll$1(this, element.children, null);
  19347. }
  19348. };
  19349. XliffParser.prototype.visitAttribute = function (attribute, context) { };
  19350. XliffParser.prototype.visitText = function (text, context) { };
  19351. XliffParser.prototype.visitComment = function (comment, context) { };
  19352. XliffParser.prototype.visitExpansion = function (expansion, context) { };
  19353. XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19354. XliffParser.prototype._addError = function (node, message) {
  19355. this._errors.push(new I18nError(node.sourceSpan, message));
  19356. };
  19357. return XliffParser;
  19358. }());
  19359. // Convert ml nodes (xliff syntax) to i18n nodes
  19360. var XmlToI18n = /** @class */ (function () {
  19361. function XmlToI18n() {
  19362. }
  19363. XmlToI18n.prototype.convert = function (message, url) {
  19364. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19365. this._errors = xmlIcu.errors;
  19366. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19367. [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
  19368. return {
  19369. i18nNodes: i18nNodes,
  19370. errors: this._errors,
  19371. };
  19372. };
  19373. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19374. XmlToI18n.prototype.visitElement = function (el, context) {
  19375. if (el.name === _PLACEHOLDER_TAG$1) {
  19376. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
  19377. if (nameAttr) {
  19378. return new Placeholder('', nameAttr.value, el.sourceSpan);
  19379. }
  19380. this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"id\" attribute");
  19381. return null;
  19382. }
  19383. if (el.name === _MARKER_TAG) {
  19384. return [].concat.apply([], __spread(visitAll$1(this, el.children)));
  19385. }
  19386. this._addError(el, "Unexpected tag");
  19387. return null;
  19388. };
  19389. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19390. var caseMap = {};
  19391. visitAll$1(this, icu.cases).forEach(function (c) {
  19392. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19393. });
  19394. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19395. };
  19396. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19397. return {
  19398. value: icuCase.value,
  19399. nodes: visitAll$1(this, icuCase.expression),
  19400. };
  19401. };
  19402. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19403. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19404. XmlToI18n.prototype._addError = function (node, message) {
  19405. this._errors.push(new I18nError(node.sourceSpan, message));
  19406. };
  19407. return XmlToI18n;
  19408. }());
  19409. function getCtypeForTag(tag) {
  19410. switch (tag.toLowerCase()) {
  19411. case 'br':
  19412. return 'lb';
  19413. case 'img':
  19414. return 'image';
  19415. default:
  19416. return "x-" + tag;
  19417. }
  19418. }
  19419. /**
  19420. * @license
  19421. * Copyright Google Inc. All Rights Reserved.
  19422. *
  19423. * Use of this source code is governed by an MIT-style license that can be
  19424. * found in the LICENSE file at https://angular.io/license
  19425. */
  19426. var _VERSION$1 = '2.0';
  19427. var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
  19428. // TODO(vicb): make this a param (s/_/-/)
  19429. var _DEFAULT_SOURCE_LANG$1 = 'en';
  19430. var _PLACEHOLDER_TAG$2 = 'ph';
  19431. var _PLACEHOLDER_SPANNING_TAG = 'pc';
  19432. var _MARKER_TAG$1 = 'mrk';
  19433. var _XLIFF_TAG = 'xliff';
  19434. var _SOURCE_TAG$2 = 'source';
  19435. var _TARGET_TAG$1 = 'target';
  19436. var _UNIT_TAG$1 = 'unit';
  19437. // http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
  19438. var Xliff2 = /** @class */ (function (_super) {
  19439. __extends(Xliff2, _super);
  19440. function Xliff2() {
  19441. return _super !== null && _super.apply(this, arguments) || this;
  19442. }
  19443. Xliff2.prototype.write = function (messages, locale) {
  19444. var visitor = new _WriteVisitor$1();
  19445. var units = [];
  19446. messages.forEach(function (message) {
  19447. var unit = new Tag(_UNIT_TAG$1, { id: message.id });
  19448. var notes = new Tag('notes');
  19449. if (message.description || message.meaning) {
  19450. if (message.description) {
  19451. notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
  19452. }
  19453. if (message.meaning) {
  19454. notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
  19455. }
  19456. }
  19457. message.sources.forEach(function (source) {
  19458. notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
  19459. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  19460. ]));
  19461. });
  19462. notes.children.push(new CR(6));
  19463. unit.children.push(new CR(6), notes);
  19464. var segment = new Tag('segment');
  19465. segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
  19466. unit.children.push(new CR(6), segment, new CR(4));
  19467. units.push(new CR(4), unit);
  19468. });
  19469. var file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, __spread(units, [new CR(2)]));
  19470. var xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
  19471. return serialize([
  19472. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  19473. ]);
  19474. };
  19475. Xliff2.prototype.load = function (content, url) {
  19476. // xliff to xml nodes
  19477. var xliff2Parser = new Xliff2Parser();
  19478. var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19479. // xml nodes to i18n nodes
  19480. var i18nNodesByMsgId = {};
  19481. var converter = new XmlToI18n$1();
  19482. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19483. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  19484. errors.push.apply(errors, __spread(e));
  19485. i18nNodesByMsgId[msgId] = i18nNodes;
  19486. });
  19487. if (errors.length) {
  19488. throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
  19489. }
  19490. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19491. };
  19492. Xliff2.prototype.digest = function (message) { return decimalDigest(message); };
  19493. return Xliff2;
  19494. }(Serializer));
  19495. var _WriteVisitor$1 = /** @class */ (function () {
  19496. function _WriteVisitor() {
  19497. }
  19498. _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  19499. _WriteVisitor.prototype.visitContainer = function (container, context) {
  19500. var _this = this;
  19501. var nodes = [];
  19502. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  19503. return nodes;
  19504. };
  19505. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  19506. var _this = this;
  19507. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  19508. Object.keys(icu.cases).forEach(function (c) {
  19509. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  19510. });
  19511. nodes.push(new Text$2("}"));
  19512. return nodes;
  19513. };
  19514. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19515. var _this = this;
  19516. var type = getTypeForTag(ph.tag);
  19517. if (ph.isVoid) {
  19518. var tagPh = new Tag(_PLACEHOLDER_TAG$2, {
  19519. id: (this._nextPlaceholderId++).toString(),
  19520. equiv: ph.startName,
  19521. type: type,
  19522. disp: "<" + ph.tag + "/>",
  19523. });
  19524. return [tagPh];
  19525. }
  19526. var tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
  19527. id: (this._nextPlaceholderId++).toString(),
  19528. equivStart: ph.startName,
  19529. equivEnd: ph.closeName,
  19530. type: type,
  19531. dispStart: "<" + ph.tag + ">",
  19532. dispEnd: "</" + ph.tag + ">",
  19533. });
  19534. var nodes = [].concat.apply([], __spread(ph.children.map(function (node) { return node.visit(_this); })));
  19535. if (nodes.length) {
  19536. nodes.forEach(function (node) { return tagPc.children.push(node); });
  19537. }
  19538. else {
  19539. tagPc.children.push(new Text$2(''));
  19540. }
  19541. return [tagPc];
  19542. };
  19543. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  19544. var idStr = (this._nextPlaceholderId++).toString();
  19545. return [new Tag(_PLACEHOLDER_TAG$2, {
  19546. id: idStr,
  19547. equiv: ph.name,
  19548. disp: "{{" + ph.value + "}}",
  19549. })];
  19550. };
  19551. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  19552. var cases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  19553. var idStr = (this._nextPlaceholderId++).toString();
  19554. return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: "{" + ph.value.expression + ", " + ph.value.type + ", " + cases + "}" })];
  19555. };
  19556. _WriteVisitor.prototype.serialize = function (nodes) {
  19557. var _this = this;
  19558. this._nextPlaceholderId = 0;
  19559. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  19560. };
  19561. return _WriteVisitor;
  19562. }());
  19563. // Extract messages as xml nodes from the xliff file
  19564. var Xliff2Parser = /** @class */ (function () {
  19565. function Xliff2Parser() {
  19566. this._locale = null;
  19567. }
  19568. Xliff2Parser.prototype.parse = function (xliff, url) {
  19569. this._unitMlString = null;
  19570. this._msgIdToHtml = {};
  19571. var xml = new XmlParser().parse(xliff, url);
  19572. this._errors = xml.errors;
  19573. visitAll$1(this, xml.rootNodes, null);
  19574. return {
  19575. msgIdToHtml: this._msgIdToHtml,
  19576. errors: this._errors,
  19577. locale: this._locale,
  19578. };
  19579. };
  19580. Xliff2Parser.prototype.visitElement = function (element, context) {
  19581. switch (element.name) {
  19582. case _UNIT_TAG$1:
  19583. this._unitMlString = null;
  19584. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19585. if (!idAttr) {
  19586. this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
  19587. }
  19588. else {
  19589. var id = idAttr.value;
  19590. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19591. this._addError(element, "Duplicated translations for msg " + id);
  19592. }
  19593. else {
  19594. visitAll$1(this, element.children, null);
  19595. if (typeof this._unitMlString === 'string') {
  19596. this._msgIdToHtml[id] = this._unitMlString;
  19597. }
  19598. else {
  19599. this._addError(element, "Message " + id + " misses a translation");
  19600. }
  19601. }
  19602. }
  19603. break;
  19604. case _SOURCE_TAG$2:
  19605. // ignore source message
  19606. break;
  19607. case _TARGET_TAG$1:
  19608. var innerTextStart = element.startSourceSpan.end.offset;
  19609. var innerTextEnd = element.endSourceSpan.start.offset;
  19610. var content = element.startSourceSpan.start.file.content;
  19611. var innerText = content.slice(innerTextStart, innerTextEnd);
  19612. this._unitMlString = innerText;
  19613. break;
  19614. case _XLIFF_TAG:
  19615. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
  19616. if (localeAttr) {
  19617. this._locale = localeAttr.value;
  19618. }
  19619. var versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
  19620. if (versionAttr) {
  19621. var version = versionAttr.value;
  19622. if (version !== '2.0') {
  19623. this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
  19624. }
  19625. else {
  19626. visitAll$1(this, element.children, null);
  19627. }
  19628. }
  19629. break;
  19630. default:
  19631. visitAll$1(this, element.children, null);
  19632. }
  19633. };
  19634. Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
  19635. Xliff2Parser.prototype.visitText = function (text, context) { };
  19636. Xliff2Parser.prototype.visitComment = function (comment, context) { };
  19637. Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
  19638. Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19639. Xliff2Parser.prototype._addError = function (node, message) {
  19640. this._errors.push(new I18nError(node.sourceSpan, message));
  19641. };
  19642. return Xliff2Parser;
  19643. }());
  19644. // Convert ml nodes (xliff syntax) to i18n nodes
  19645. var XmlToI18n$1 = /** @class */ (function () {
  19646. function XmlToI18n() {
  19647. }
  19648. XmlToI18n.prototype.convert = function (message, url) {
  19649. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19650. this._errors = xmlIcu.errors;
  19651. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19652. [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
  19653. return {
  19654. i18nNodes: i18nNodes,
  19655. errors: this._errors,
  19656. };
  19657. };
  19658. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19659. XmlToI18n.prototype.visitElement = function (el, context) {
  19660. var _this = this;
  19661. switch (el.name) {
  19662. case _PLACEHOLDER_TAG$2:
  19663. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
  19664. if (nameAttr) {
  19665. return [new Placeholder('', nameAttr.value, el.sourceSpan)];
  19666. }
  19667. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equiv\" attribute");
  19668. break;
  19669. case _PLACEHOLDER_SPANNING_TAG:
  19670. var startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
  19671. var endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
  19672. if (!startAttr) {
  19673. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivStart\" attribute");
  19674. }
  19675. else if (!endAttr) {
  19676. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivEnd\" attribute");
  19677. }
  19678. else {
  19679. var startId = startAttr.value;
  19680. var endId = endAttr.value;
  19681. var nodes = [];
  19682. return nodes.concat.apply(nodes, __spread([new Placeholder('', startId, el.sourceSpan)], el.children.map(function (node) { return node.visit(_this, null); }), [new Placeholder('', endId, el.sourceSpan)]));
  19683. }
  19684. break;
  19685. case _MARKER_TAG$1:
  19686. return [].concat.apply([], __spread(visitAll$1(this, el.children)));
  19687. default:
  19688. this._addError(el, "Unexpected tag");
  19689. }
  19690. return null;
  19691. };
  19692. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19693. var caseMap = {};
  19694. visitAll$1(this, icu.cases).forEach(function (c) {
  19695. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19696. });
  19697. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19698. };
  19699. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19700. return {
  19701. value: icuCase.value,
  19702. nodes: [].concat.apply([], __spread(visitAll$1(this, icuCase.expression))),
  19703. };
  19704. };
  19705. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19706. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19707. XmlToI18n.prototype._addError = function (node, message) {
  19708. this._errors.push(new I18nError(node.sourceSpan, message));
  19709. };
  19710. return XmlToI18n;
  19711. }());
  19712. function getTypeForTag(tag) {
  19713. switch (tag.toLowerCase()) {
  19714. case 'br':
  19715. case 'b':
  19716. case 'i':
  19717. case 'u':
  19718. return 'fmt';
  19719. case 'img':
  19720. return 'image';
  19721. case 'a':
  19722. return 'link';
  19723. default:
  19724. return 'other';
  19725. }
  19726. }
  19727. /**
  19728. * @license
  19729. * Copyright Google Inc. All Rights Reserved.
  19730. *
  19731. * Use of this source code is governed by an MIT-style license that can be
  19732. * found in the LICENSE file at https://angular.io/license
  19733. */
  19734. var _TRANSLATIONS_TAG = 'translationbundle';
  19735. var _TRANSLATION_TAG = 'translation';
  19736. var _PLACEHOLDER_TAG$3 = 'ph';
  19737. var Xtb = /** @class */ (function (_super) {
  19738. __extends(Xtb, _super);
  19739. function Xtb() {
  19740. return _super !== null && _super.apply(this, arguments) || this;
  19741. }
  19742. Xtb.prototype.write = function (messages, locale) { throw new Error('Unsupported'); };
  19743. Xtb.prototype.load = function (content, url) {
  19744. // xtb to xml nodes
  19745. var xtbParser = new XtbParser();
  19746. var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19747. // xml nodes to i18n nodes
  19748. var i18nNodesByMsgId = {};
  19749. var converter = new XmlToI18n$2();
  19750. // Because we should be able to load xtb files that rely on features not supported by angular,
  19751. // we need to delay the conversion of html to i18n nodes so that non angular messages are not
  19752. // converted
  19753. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19754. var valueFn = function () {
  19755. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
  19756. if (errors.length) {
  19757. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  19758. }
  19759. return i18nNodes;
  19760. };
  19761. createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
  19762. });
  19763. if (errors.length) {
  19764. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  19765. }
  19766. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19767. };
  19768. Xtb.prototype.digest = function (message) { return digest$1(message); };
  19769. Xtb.prototype.createNameMapper = function (message) {
  19770. return new SimplePlaceholderMapper(message, toPublicName);
  19771. };
  19772. return Xtb;
  19773. }(Serializer));
  19774. function createLazyProperty(messages, id, valueFn) {
  19775. Object.defineProperty(messages, id, {
  19776. configurable: true,
  19777. enumerable: true,
  19778. get: function () {
  19779. var value = valueFn();
  19780. Object.defineProperty(messages, id, { enumerable: true, value: value });
  19781. return value;
  19782. },
  19783. set: function (_) { throw new Error('Could not overwrite an XTB translation'); },
  19784. });
  19785. }
  19786. // Extract messages as xml nodes from the xtb file
  19787. var XtbParser = /** @class */ (function () {
  19788. function XtbParser() {
  19789. this._locale = null;
  19790. }
  19791. XtbParser.prototype.parse = function (xtb, url) {
  19792. this._bundleDepth = 0;
  19793. this._msgIdToHtml = {};
  19794. // We can not parse the ICU messages at this point as some messages might not originate
  19795. // from Angular that could not be lex'd.
  19796. var xml = new XmlParser().parse(xtb, url);
  19797. this._errors = xml.errors;
  19798. visitAll$1(this, xml.rootNodes);
  19799. return {
  19800. msgIdToHtml: this._msgIdToHtml,
  19801. errors: this._errors,
  19802. locale: this._locale,
  19803. };
  19804. };
  19805. XtbParser.prototype.visitElement = function (element, context) {
  19806. switch (element.name) {
  19807. case _TRANSLATIONS_TAG:
  19808. this._bundleDepth++;
  19809. if (this._bundleDepth > 1) {
  19810. this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
  19811. }
  19812. var langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
  19813. if (langAttr) {
  19814. this._locale = langAttr.value;
  19815. }
  19816. visitAll$1(this, element.children, null);
  19817. this._bundleDepth--;
  19818. break;
  19819. case _TRANSLATION_TAG:
  19820. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19821. if (!idAttr) {
  19822. this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
  19823. }
  19824. else {
  19825. var id = idAttr.value;
  19826. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19827. this._addError(element, "Duplicated translations for msg " + id);
  19828. }
  19829. else {
  19830. var innerTextStart = element.startSourceSpan.end.offset;
  19831. var innerTextEnd = element.endSourceSpan.start.offset;
  19832. var content = element.startSourceSpan.start.file.content;
  19833. var innerText = content.slice(innerTextStart, innerTextEnd);
  19834. this._msgIdToHtml[id] = innerText;
  19835. }
  19836. }
  19837. break;
  19838. default:
  19839. this._addError(element, 'Unexpected tag');
  19840. }
  19841. };
  19842. XtbParser.prototype.visitAttribute = function (attribute, context) { };
  19843. XtbParser.prototype.visitText = function (text, context) { };
  19844. XtbParser.prototype.visitComment = function (comment, context) { };
  19845. XtbParser.prototype.visitExpansion = function (expansion, context) { };
  19846. XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19847. XtbParser.prototype._addError = function (node, message) {
  19848. this._errors.push(new I18nError(node.sourceSpan, message));
  19849. };
  19850. return XtbParser;
  19851. }());
  19852. // Convert ml nodes (xtb syntax) to i18n nodes
  19853. var XmlToI18n$2 = /** @class */ (function () {
  19854. function XmlToI18n() {
  19855. }
  19856. XmlToI18n.prototype.convert = function (message, url) {
  19857. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19858. this._errors = xmlIcu.errors;
  19859. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19860. [] :
  19861. visitAll$1(this, xmlIcu.rootNodes);
  19862. return {
  19863. i18nNodes: i18nNodes,
  19864. errors: this._errors,
  19865. };
  19866. };
  19867. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19868. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19869. var caseMap = {};
  19870. visitAll$1(this, icu.cases).forEach(function (c) {
  19871. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19872. });
  19873. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19874. };
  19875. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19876. return {
  19877. value: icuCase.value,
  19878. nodes: visitAll$1(this, icuCase.expression),
  19879. };
  19880. };
  19881. XmlToI18n.prototype.visitElement = function (el, context) {
  19882. if (el.name === _PLACEHOLDER_TAG$3) {
  19883. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
  19884. if (nameAttr) {
  19885. return new Placeholder('', nameAttr.value, el.sourceSpan);
  19886. }
  19887. this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
  19888. }
  19889. else {
  19890. this._addError(el, "Unexpected tag");
  19891. }
  19892. return null;
  19893. };
  19894. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19895. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19896. XmlToI18n.prototype._addError = function (node, message) {
  19897. this._errors.push(new I18nError(node.sourceSpan, message));
  19898. };
  19899. return XmlToI18n;
  19900. }());
  19901. /**
  19902. * @license
  19903. * Copyright Google Inc. All Rights Reserved.
  19904. *
  19905. * Use of this source code is governed by an MIT-style license that can be
  19906. * found in the LICENSE file at https://angular.io/license
  19907. */
  19908. /**
  19909. * A container for translated messages
  19910. */
  19911. var TranslationBundle = /** @class */ (function () {
  19912. function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
  19913. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  19914. if (missingTranslationStrategy === void 0) { missingTranslationStrategy = MissingTranslationStrategy.Warning; }
  19915. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  19916. this.digest = digest;
  19917. this.mapperFactory = mapperFactory;
  19918. this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
  19919. }
  19920. // Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
  19921. TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
  19922. var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
  19923. var digestFn = function (m) { return serializer.digest(m); };
  19924. var mapperFactory = function (m) { return serializer.createNameMapper(m); };
  19925. return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
  19926. };
  19927. // Returns the translation as HTML nodes from the given source message.
  19928. TranslationBundle.prototype.get = function (srcMsg) {
  19929. var html = this._i18nToHtml.convert(srcMsg);
  19930. if (html.errors.length) {
  19931. throw new Error(html.errors.join('\n'));
  19932. }
  19933. return html.nodes;
  19934. };
  19935. TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
  19936. return TranslationBundle;
  19937. }());
  19938. var I18nToHtmlVisitor = /** @class */ (function () {
  19939. function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
  19940. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  19941. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  19942. this._locale = _locale;
  19943. this._digest = _digest;
  19944. this._mapperFactory = _mapperFactory;
  19945. this._missingTranslationStrategy = _missingTranslationStrategy;
  19946. this._console = _console;
  19947. this._contextStack = [];
  19948. this._errors = [];
  19949. }
  19950. I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
  19951. this._contextStack.length = 0;
  19952. this._errors.length = 0;
  19953. // i18n to text
  19954. var text = this._convertToText(srcMsg);
  19955. // text to html
  19956. var url = srcMsg.nodes[0].sourceSpan.start.file.url;
  19957. var html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
  19958. return {
  19959. nodes: html.rootNodes,
  19960. errors: __spread(this._errors, html.errors),
  19961. };
  19962. };
  19963. I18nToHtmlVisitor.prototype.visitText = function (text, context) {
  19964. // `convert()` uses an `HtmlParser` to return `html.Node`s
  19965. // we should then make sure that any special characters are escaped
  19966. return escapeXml(text.value);
  19967. };
  19968. I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
  19969. var _this = this;
  19970. return container.children.map(function (n) { return n.visit(_this); }).join('');
  19971. };
  19972. I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
  19973. var _this = this;
  19974. var cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  19975. // TODO(vicb): Once all format switch to using expression placeholders
  19976. // we should throw when the placeholder is not in the source message
  19977. var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
  19978. this._srcMsg.placeholders[icu.expression] :
  19979. icu.expression;
  19980. return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
  19981. };
  19982. I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
  19983. var phName = this._mapper(ph.name);
  19984. if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
  19985. return this._srcMsg.placeholders[phName];
  19986. }
  19987. if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
  19988. return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
  19989. }
  19990. this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
  19991. return '';
  19992. };
  19993. // Loaded message contains only placeholders (vs tag and icu placeholders).
  19994. // However when a translation can not be found, we need to serialize the source message
  19995. // which can contain tag placeholders
  19996. I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19997. var _this = this;
  19998. var tag = "" + ph.tag;
  19999. var attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
  20000. if (ph.isVoid) {
  20001. return "<" + tag + " " + attrs + "/>";
  20002. }
  20003. var children = ph.children.map(function (c) { return c.visit(_this); }).join('');
  20004. return "<" + tag + " " + attrs + ">" + children + "</" + tag + ">";
  20005. };
  20006. // Loaded message contains only placeholders (vs tag and icu placeholders).
  20007. // However when a translation can not be found, we need to serialize the source message
  20008. // which can contain tag placeholders
  20009. I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  20010. // An ICU placeholder references the source message to be serialized
  20011. return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
  20012. };
  20013. /**
  20014. * Convert a source message to a translated text string:
  20015. * - text nodes are replaced with their translation,
  20016. * - placeholders are replaced with their content,
  20017. * - ICU nodes are converted to ICU expressions.
  20018. */
  20019. I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
  20020. var _this = this;
  20021. var id = this._digest(srcMsg);
  20022. var mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
  20023. var nodes;
  20024. this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
  20025. this._srcMsg = srcMsg;
  20026. if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
  20027. // When there is a translation use its nodes as the source
  20028. // And create a mapper to convert serialized placeholder names to internal names
  20029. nodes = this._i18nNodesByMsgId[id];
  20030. this._mapper = function (name) { return mapper ? mapper.toInternalName(name) : name; };
  20031. }
  20032. else {
  20033. // When no translation has been found
  20034. // - report an error / a warning / nothing,
  20035. // - use the nodes from the original message
  20036. // - placeholders are already internal and need no mapper
  20037. if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
  20038. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  20039. this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
  20040. }
  20041. else if (this._console &&
  20042. this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
  20043. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  20044. this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
  20045. }
  20046. nodes = srcMsg.nodes;
  20047. this._mapper = function (name) { return name; };
  20048. }
  20049. var text = nodes.map(function (node) { return node.visit(_this); }).join('');
  20050. var context = this._contextStack.pop();
  20051. this._srcMsg = context.msg;
  20052. this._mapper = context.mapper;
  20053. return text;
  20054. };
  20055. I18nToHtmlVisitor.prototype._addError = function (el, msg) {
  20056. this._errors.push(new I18nError(el.sourceSpan, msg));
  20057. };
  20058. return I18nToHtmlVisitor;
  20059. }());
  20060. /**
  20061. * @license
  20062. * Copyright Google Inc. All Rights Reserved.
  20063. *
  20064. * Use of this source code is governed by an MIT-style license that can be
  20065. * found in the LICENSE file at https://angular.io/license
  20066. */
  20067. var I18NHtmlParser = /** @class */ (function () {
  20068. function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
  20069. if (missingTranslation === void 0) { missingTranslation = MissingTranslationStrategy.Warning; }
  20070. this._htmlParser = _htmlParser;
  20071. if (translations) {
  20072. var serializer = createSerializer(translationsFormat);
  20073. this._translationBundle =
  20074. TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
  20075. }
  20076. else {
  20077. this._translationBundle =
  20078. new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
  20079. }
  20080. }
  20081. I18NHtmlParser.prototype.parse = function (source, url, options) {
  20082. if (options === void 0) { options = {}; }
  20083. var interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  20084. var parseResult = this._htmlParser.parse(source, url, __assign({ interpolationConfig: interpolationConfig }, options));
  20085. if (parseResult.errors.length) {
  20086. return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
  20087. }
  20088. return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
  20089. };
  20090. return I18NHtmlParser;
  20091. }());
  20092. function createSerializer(format) {
  20093. format = (format || 'xlf').toLowerCase();
  20094. switch (format) {
  20095. case 'xmb':
  20096. return new Xmb();
  20097. case 'xtb':
  20098. return new Xtb();
  20099. case 'xliff2':
  20100. case 'xlf2':
  20101. return new Xliff2();
  20102. case 'xliff':
  20103. case 'xlf':
  20104. default:
  20105. return new Xliff();
  20106. }
  20107. }
  20108. /**
  20109. * @license
  20110. * Copyright Google Inc. All Rights Reserved.
  20111. *
  20112. * Use of this source code is governed by an MIT-style license that can be
  20113. * found in the LICENSE file at https://angular.io/license
  20114. */
  20115. var QUOTED_KEYS = '$quoted$';
  20116. function convertValueToOutputAst(ctx, value, type) {
  20117. if (type === void 0) { type = null; }
  20118. return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
  20119. }
  20120. var _ValueOutputAstTransformer = /** @class */ (function () {
  20121. function _ValueOutputAstTransformer(ctx) {
  20122. this.ctx = ctx;
  20123. }
  20124. _ValueOutputAstTransformer.prototype.visitArray = function (arr, type) {
  20125. var _this = this;
  20126. return literalArr(arr.map(function (value) { return visitValue(value, _this, null); }), type);
  20127. };
  20128. _ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) {
  20129. var _this = this;
  20130. var entries = [];
  20131. var quotedSet = new Set(map && map[QUOTED_KEYS]);
  20132. Object.keys(map).forEach(function (key) {
  20133. entries.push(new LiteralMapEntry(key, visitValue(map[key], _this, null), quotedSet.has(key)));
  20134. });
  20135. return new LiteralMapExpr(entries, type);
  20136. };
  20137. _ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) { return literal(value, type); };
  20138. _ValueOutputAstTransformer.prototype.visitOther = function (value, type) {
  20139. if (value instanceof Expression) {
  20140. return value;
  20141. }
  20142. else {
  20143. return this.ctx.importExpr(value);
  20144. }
  20145. };
  20146. return _ValueOutputAstTransformer;
  20147. }());
  20148. /**
  20149. * @license
  20150. * Copyright Google Inc. All Rights Reserved.
  20151. *
  20152. * Use of this source code is governed by an MIT-style license that can be
  20153. * found in the LICENSE file at https://angular.io/license
  20154. */
  20155. function mapEntry(key, value) {
  20156. return { key: key, value: value, quoted: false };
  20157. }
  20158. var InjectableCompiler = /** @class */ (function () {
  20159. function InjectableCompiler(reflector, alwaysGenerateDef) {
  20160. this.reflector = reflector;
  20161. this.alwaysGenerateDef = alwaysGenerateDef;
  20162. this.tokenInjector = reflector.resolveExternalReference(Identifiers.Injector);
  20163. }
  20164. InjectableCompiler.prototype.depsArray = function (deps, ctx) {
  20165. var _this = this;
  20166. return deps.map(function (dep) {
  20167. var token = dep;
  20168. var args = [token];
  20169. var flags = 0 /* Default */;
  20170. if (Array.isArray(dep)) {
  20171. for (var i = 0; i < dep.length; i++) {
  20172. var v = dep[i];
  20173. if (v) {
  20174. if (v.ngMetadataName === 'Optional') {
  20175. flags |= 8 /* Optional */;
  20176. }
  20177. else if (v.ngMetadataName === 'SkipSelf') {
  20178. flags |= 4 /* SkipSelf */;
  20179. }
  20180. else if (v.ngMetadataName === 'Self') {
  20181. flags |= 2 /* Self */;
  20182. }
  20183. else if (v.ngMetadataName === 'Inject') {
  20184. token = v.token;
  20185. }
  20186. else {
  20187. token = v;
  20188. }
  20189. }
  20190. }
  20191. }
  20192. var tokenExpr;
  20193. if (typeof token === 'string') {
  20194. tokenExpr = literal(token);
  20195. }
  20196. else if (token === _this.tokenInjector) {
  20197. tokenExpr = importExpr(Identifiers.INJECTOR);
  20198. }
  20199. else {
  20200. tokenExpr = ctx.importExpr(token);
  20201. }
  20202. if (flags !== 0 /* Default */) {
  20203. args = [tokenExpr, literal(flags)];
  20204. }
  20205. else {
  20206. args = [tokenExpr];
  20207. }
  20208. return importExpr(Identifiers.inject).callFn(args);
  20209. });
  20210. };
  20211. InjectableCompiler.prototype.factoryFor = function (injectable, ctx) {
  20212. var retValue;
  20213. if (injectable.useExisting) {
  20214. retValue = importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
  20215. }
  20216. else if (injectable.useFactory) {
  20217. var deps = injectable.deps || [];
  20218. if (deps.length > 0) {
  20219. retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
  20220. }
  20221. else {
  20222. return ctx.importExpr(injectable.useFactory);
  20223. }
  20224. }
  20225. else if (injectable.useValue) {
  20226. retValue = convertValueToOutputAst(ctx, injectable.useValue);
  20227. }
  20228. else {
  20229. var clazz = injectable.useClass || injectable.symbol;
  20230. var depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
  20231. retValue = new InstantiateExpr(ctx.importExpr(clazz), depArgs);
  20232. }
  20233. return fn([], [new ReturnStatement(retValue)], undefined, undefined, injectable.symbol.name + '_Factory');
  20234. };
  20235. InjectableCompiler.prototype.injectableDef = function (injectable, ctx) {
  20236. var providedIn = NULL_EXPR;
  20237. if (injectable.providedIn !== undefined) {
  20238. if (injectable.providedIn === null) {
  20239. providedIn = NULL_EXPR;
  20240. }
  20241. else if (typeof injectable.providedIn === 'string') {
  20242. providedIn = literal(injectable.providedIn);
  20243. }
  20244. else {
  20245. providedIn = ctx.importExpr(injectable.providedIn);
  20246. }
  20247. }
  20248. var def = [
  20249. mapEntry('factory', this.factoryFor(injectable, ctx)),
  20250. mapEntry('token', ctx.importExpr(injectable.type.reference)),
  20251. mapEntry('providedIn', providedIn),
  20252. ];
  20253. return importExpr(Identifiers.ɵɵdefineInjectable).callFn([literalMap(def)]);
  20254. };
  20255. InjectableCompiler.prototype.compile = function (injectable, ctx) {
  20256. if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
  20257. var className = identifierName(injectable.type);
  20258. var clazz = new ClassStmt(className, null, [
  20259. new ClassField('ngInjectableDef', INFERRED_TYPE, [StmtModifier.Static], this.injectableDef(injectable, ctx)),
  20260. ], [], new ClassMethod(null, [], []), []);
  20261. ctx.statements.push(clazz);
  20262. }
  20263. };
  20264. return InjectableCompiler;
  20265. }());
  20266. /**
  20267. * @license
  20268. * Copyright Google Inc. All Rights Reserved.
  20269. *
  20270. * Use of this source code is governed by an MIT-style license that can be
  20271. * found in the LICENSE file at https://angular.io/license
  20272. */
  20273. var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
  20274. var GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
  20275. var JIT_SUMMARY_FILE = /\.ngsummary\./;
  20276. var JIT_SUMMARY_NAME = /NgSummary$/;
  20277. function ngfactoryFilePath(filePath, forceSourceFile) {
  20278. if (forceSourceFile === void 0) { forceSourceFile = false; }
  20279. var urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
  20280. return urlWithSuffix[0] + ".ngfactory" + normalizeGenFileSuffix(urlWithSuffix[1]);
  20281. }
  20282. function stripGeneratedFileSuffix(filePath) {
  20283. return filePath.replace(GENERATED_FILE, '.');
  20284. }
  20285. function isGeneratedFile(filePath) {
  20286. return GENERATED_FILE.test(filePath);
  20287. }
  20288. function splitTypescriptSuffix(path, forceSourceFile) {
  20289. if (forceSourceFile === void 0) { forceSourceFile = false; }
  20290. if (path.endsWith('.d.ts')) {
  20291. return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
  20292. }
  20293. var lastDot = path.lastIndexOf('.');
  20294. if (lastDot !== -1) {
  20295. return [path.substring(0, lastDot), path.substring(lastDot)];
  20296. }
  20297. return [path, ''];
  20298. }
  20299. function normalizeGenFileSuffix(srcFileSuffix) {
  20300. return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
  20301. }
  20302. function summaryFileName(fileName) {
  20303. var fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
  20304. return fileNameWithoutSuffix + ".ngsummary.json";
  20305. }
  20306. function summaryForJitFileName(fileName, forceSourceFile) {
  20307. if (forceSourceFile === void 0) { forceSourceFile = false; }
  20308. var urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
  20309. return urlWithSuffix[0] + ".ngsummary" + urlWithSuffix[1];
  20310. }
  20311. function stripSummaryForJitFileSuffix(filePath) {
  20312. return filePath.replace(JIT_SUMMARY_FILE, '.');
  20313. }
  20314. function summaryForJitName(symbolName) {
  20315. return symbolName + "NgSummary";
  20316. }
  20317. function stripSummaryForJitNameSuffix(symbolName) {
  20318. return symbolName.replace(JIT_SUMMARY_NAME, '');
  20319. }
  20320. var LOWERED_SYMBOL = /\u0275\d+/;
  20321. function isLoweredSymbol(name) {
  20322. return LOWERED_SYMBOL.test(name);
  20323. }
  20324. function createLoweredSymbol(id) {
  20325. return "\u0275" + id;
  20326. }
  20327. /**
  20328. * @license
  20329. * Copyright Google Inc. All Rights Reserved.
  20330. *
  20331. * Use of this source code is governed by an MIT-style license that can be
  20332. * found in the LICENSE file at https://angular.io/license
  20333. */
  20334. var LifecycleHooks;
  20335. (function (LifecycleHooks) {
  20336. LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
  20337. LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
  20338. LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
  20339. LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
  20340. LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
  20341. LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
  20342. LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
  20343. LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
  20344. })(LifecycleHooks || (LifecycleHooks = {}));
  20345. var LIFECYCLE_HOOKS_VALUES = [
  20346. LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
  20347. LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
  20348. LifecycleHooks.AfterViewChecked
  20349. ];
  20350. function hasLifecycleHook(reflector, hook, token) {
  20351. return reflector.hasLifecycleHook(token, getHookName(hook));
  20352. }
  20353. function getAllLifecycleHooks(reflector, token) {
  20354. return LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return hasLifecycleHook(reflector, hook, token); });
  20355. }
  20356. function getHookName(hook) {
  20357. switch (hook) {
  20358. case LifecycleHooks.OnInit:
  20359. return 'ngOnInit';
  20360. case LifecycleHooks.OnDestroy:
  20361. return 'ngOnDestroy';
  20362. case LifecycleHooks.DoCheck:
  20363. return 'ngDoCheck';
  20364. case LifecycleHooks.OnChanges:
  20365. return 'ngOnChanges';
  20366. case LifecycleHooks.AfterContentInit:
  20367. return 'ngAfterContentInit';
  20368. case LifecycleHooks.AfterContentChecked:
  20369. return 'ngAfterContentChecked';
  20370. case LifecycleHooks.AfterViewInit:
  20371. return 'ngAfterViewInit';
  20372. case LifecycleHooks.AfterViewChecked:
  20373. return 'ngAfterViewChecked';
  20374. default:
  20375. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  20376. // However Closure Compiler does not understand that and reports an error in typed mode.
  20377. // The `throw new Error` below works around the problem, and the unexpected: never variable
  20378. // makes sure tsc still checks this code is unreachable.
  20379. var unexpected = hook;
  20380. throw new Error("unexpected " + unexpected);
  20381. }
  20382. }
  20383. /**
  20384. * @license
  20385. * Copyright Google Inc. All Rights Reserved.
  20386. *
  20387. * Use of this source code is governed by an MIT-style license that can be
  20388. * found in the LICENSE file at https://angular.io/license
  20389. */
  20390. var ERROR_COMPONENT_TYPE = 'ngComponentType';
  20391. // Design notes:
  20392. // - don't lazily create metadata:
  20393. // For some metadata, we need to do async work sometimes,
  20394. // so the user has to kick off this loading.
  20395. // But we want to report errors even when the async work is
  20396. // not required to check that the user would have been able
  20397. // to wait correctly.
  20398. var CompileMetadataResolver = /** @class */ (function () {
  20399. function CompileMetadataResolver(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
  20400. this._config = _config;
  20401. this._htmlParser = _htmlParser;
  20402. this._ngModuleResolver = _ngModuleResolver;
  20403. this._directiveResolver = _directiveResolver;
  20404. this._pipeResolver = _pipeResolver;
  20405. this._summaryResolver = _summaryResolver;
  20406. this._schemaRegistry = _schemaRegistry;
  20407. this._directiveNormalizer = _directiveNormalizer;
  20408. this._console = _console;
  20409. this._staticSymbolCache = _staticSymbolCache;
  20410. this._reflector = _reflector;
  20411. this._errorCollector = _errorCollector;
  20412. this._nonNormalizedDirectiveCache = new Map();
  20413. this._directiveCache = new Map();
  20414. this._summaryCache = new Map();
  20415. this._pipeCache = new Map();
  20416. this._ngModuleCache = new Map();
  20417. this._ngModuleOfTypes = new Map();
  20418. this._shallowModuleCache = new Map();
  20419. }
  20420. CompileMetadataResolver.prototype.getReflector = function () { return this._reflector; };
  20421. CompileMetadataResolver.prototype.clearCacheFor = function (type) {
  20422. var dirMeta = this._directiveCache.get(type);
  20423. this._directiveCache.delete(type);
  20424. this._nonNormalizedDirectiveCache.delete(type);
  20425. this._summaryCache.delete(type);
  20426. this._pipeCache.delete(type);
  20427. this._ngModuleOfTypes.delete(type);
  20428. // Clear all of the NgModule as they contain transitive information!
  20429. this._ngModuleCache.clear();
  20430. if (dirMeta) {
  20431. this._directiveNormalizer.clearCacheFor(dirMeta);
  20432. }
  20433. };
  20434. CompileMetadataResolver.prototype.clearCache = function () {
  20435. this._directiveCache.clear();
  20436. this._nonNormalizedDirectiveCache.clear();
  20437. this._summaryCache.clear();
  20438. this._pipeCache.clear();
  20439. this._ngModuleCache.clear();
  20440. this._ngModuleOfTypes.clear();
  20441. this._directiveNormalizer.clearCache();
  20442. };
  20443. CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
  20444. var delegate = null;
  20445. var proxyClass = function () {
  20446. if (!delegate) {
  20447. throw new Error("Illegal state: Class " + name + " for type " + stringify(baseType) + " is not compiled yet!");
  20448. }
  20449. return delegate.apply(this, arguments);
  20450. };
  20451. proxyClass.setDelegate = function (d) {
  20452. delegate = d;
  20453. proxyClass.prototype = d.prototype;
  20454. };
  20455. // Make stringify work correctly
  20456. proxyClass.overriddenName = name;
  20457. return proxyClass;
  20458. };
  20459. CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
  20460. if (dirType instanceof StaticSymbol) {
  20461. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
  20462. }
  20463. else {
  20464. return this._createProxyClass(dirType, name);
  20465. }
  20466. };
  20467. CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
  20468. return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
  20469. };
  20470. CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
  20471. return this.getGeneratedClass(dirType, hostViewClassName(dirType));
  20472. };
  20473. CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
  20474. var name = identifierName({ reference: dirType }) + "_Host";
  20475. if (dirType instanceof StaticSymbol) {
  20476. return this._staticSymbolCache.get(dirType.filePath, name);
  20477. }
  20478. return this._createProxyClass(dirType, name);
  20479. };
  20480. CompileMetadataResolver.prototype.getRendererType = function (dirType) {
  20481. if (dirType instanceof StaticSymbol) {
  20482. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
  20483. }
  20484. else {
  20485. // returning an object as proxy,
  20486. // that we fill later during runtime compilation.
  20487. return {};
  20488. }
  20489. };
  20490. CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
  20491. if (dirType instanceof StaticSymbol) {
  20492. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
  20493. }
  20494. else {
  20495. var hostView = this.getHostComponentViewClass(dirType);
  20496. // Note: ngContentSelectors will be filled later once the template is
  20497. // loaded.
  20498. var createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
  20499. return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
  20500. }
  20501. };
  20502. CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
  20503. var _a;
  20504. if (!(factory instanceof StaticSymbol)) {
  20505. (_a = factory.ngContentSelectors).push.apply(_a, __spread(ngContentSelectors));
  20506. }
  20507. };
  20508. CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
  20509. var typeSummary = this._summaryCache.get(type);
  20510. if (!typeSummary) {
  20511. var summary = this._summaryResolver.resolveSummary(type);
  20512. typeSummary = summary ? summary.type : null;
  20513. this._summaryCache.set(type, typeSummary || null);
  20514. }
  20515. return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
  20516. };
  20517. CompileMetadataResolver.prototype.getHostComponentMetadata = function (compMeta, hostViewType) {
  20518. var hostType = this.getHostComponentType(compMeta.type.reference);
  20519. if (!hostViewType) {
  20520. hostViewType = this.getHostComponentViewClass(hostType);
  20521. }
  20522. // Note: ! is ok here as this method should only be called with normalized directive
  20523. // metadata, which always fills in the selector.
  20524. var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
  20525. var templateUrl = '';
  20526. var htmlAst = this._htmlParser.parse(template, templateUrl);
  20527. return CompileDirectiveMetadata.create({
  20528. isHost: true,
  20529. type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
  20530. template: new CompileTemplateMetadata({
  20531. encapsulation: ViewEncapsulation.None,
  20532. template: template,
  20533. templateUrl: templateUrl,
  20534. htmlAst: htmlAst,
  20535. styles: [],
  20536. styleUrls: [],
  20537. ngContentSelectors: [],
  20538. animations: [],
  20539. isInline: true,
  20540. externalStylesheets: [],
  20541. interpolation: null,
  20542. preserveWhitespaces: false,
  20543. }),
  20544. exportAs: null,
  20545. changeDetection: ChangeDetectionStrategy.Default,
  20546. inputs: [],
  20547. outputs: [],
  20548. host: {},
  20549. isComponent: true,
  20550. selector: '*',
  20551. providers: [],
  20552. viewProviders: [],
  20553. queries: [],
  20554. guards: {},
  20555. viewQueries: [],
  20556. componentViewType: hostViewType,
  20557. rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
  20558. entryComponents: [],
  20559. componentFactory: null
  20560. });
  20561. };
  20562. CompileMetadataResolver.prototype.loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
  20563. var _this = this;
  20564. if (this._directiveCache.has(directiveType)) {
  20565. return null;
  20566. }
  20567. directiveType = resolveForwardRef(directiveType);
  20568. var _a = this.getNonNormalizedDirectiveMetadata(directiveType), annotation = _a.annotation, metadata = _a.metadata;
  20569. var createDirectiveMetadata = function (templateMetadata) {
  20570. var normalizedDirMeta = new CompileDirectiveMetadata({
  20571. isHost: false,
  20572. type: metadata.type,
  20573. isComponent: metadata.isComponent,
  20574. selector: metadata.selector,
  20575. exportAs: metadata.exportAs,
  20576. changeDetection: metadata.changeDetection,
  20577. inputs: metadata.inputs,
  20578. outputs: metadata.outputs,
  20579. hostListeners: metadata.hostListeners,
  20580. hostProperties: metadata.hostProperties,
  20581. hostAttributes: metadata.hostAttributes,
  20582. providers: metadata.providers,
  20583. viewProviders: metadata.viewProviders,
  20584. queries: metadata.queries,
  20585. guards: metadata.guards,
  20586. viewQueries: metadata.viewQueries,
  20587. entryComponents: metadata.entryComponents,
  20588. componentViewType: metadata.componentViewType,
  20589. rendererType: metadata.rendererType,
  20590. componentFactory: metadata.componentFactory,
  20591. template: templateMetadata
  20592. });
  20593. if (templateMetadata) {
  20594. _this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
  20595. }
  20596. _this._directiveCache.set(directiveType, normalizedDirMeta);
  20597. _this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
  20598. return null;
  20599. };
  20600. if (metadata.isComponent) {
  20601. var template = metadata.template;
  20602. var templateMeta = this._directiveNormalizer.normalizeTemplate({
  20603. ngModuleType: ngModuleType,
  20604. componentType: directiveType,
  20605. moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
  20606. encapsulation: template.encapsulation,
  20607. template: template.template,
  20608. templateUrl: template.templateUrl,
  20609. styles: template.styles,
  20610. styleUrls: template.styleUrls,
  20611. animations: template.animations,
  20612. interpolation: template.interpolation,
  20613. preserveWhitespaces: template.preserveWhitespaces
  20614. });
  20615. if (isPromise(templateMeta) && isSync) {
  20616. this._reportError(componentStillLoadingError(directiveType), directiveType);
  20617. return null;
  20618. }
  20619. return SyncAsync.then(templateMeta, createDirectiveMetadata);
  20620. }
  20621. else {
  20622. // directive
  20623. createDirectiveMetadata(null);
  20624. return null;
  20625. }
  20626. };
  20627. CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
  20628. var _this = this;
  20629. directiveType = resolveForwardRef(directiveType);
  20630. if (!directiveType) {
  20631. return null;
  20632. }
  20633. var cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
  20634. if (cacheEntry) {
  20635. return cacheEntry;
  20636. }
  20637. var dirMeta = this._directiveResolver.resolve(directiveType, false);
  20638. if (!dirMeta) {
  20639. return null;
  20640. }
  20641. var nonNormalizedTemplateMetadata = undefined;
  20642. if (createComponent.isTypeOf(dirMeta)) {
  20643. // component
  20644. var compMeta = dirMeta;
  20645. assertArrayOfStrings('styles', compMeta.styles);
  20646. assertArrayOfStrings('styleUrls', compMeta.styleUrls);
  20647. assertInterpolationSymbols('interpolation', compMeta.interpolation);
  20648. var animations = compMeta.animations;
  20649. nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
  20650. encapsulation: noUndefined(compMeta.encapsulation),
  20651. template: noUndefined(compMeta.template),
  20652. templateUrl: noUndefined(compMeta.templateUrl),
  20653. htmlAst: null,
  20654. styles: compMeta.styles || [],
  20655. styleUrls: compMeta.styleUrls || [],
  20656. animations: animations || [],
  20657. interpolation: noUndefined(compMeta.interpolation),
  20658. isInline: !!compMeta.template,
  20659. externalStylesheets: [],
  20660. ngContentSelectors: [],
  20661. preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
  20662. });
  20663. }
  20664. var changeDetectionStrategy = null;
  20665. var viewProviders = [];
  20666. var entryComponentMetadata = [];
  20667. var selector = dirMeta.selector;
  20668. if (createComponent.isTypeOf(dirMeta)) {
  20669. // Component
  20670. var compMeta = dirMeta;
  20671. changeDetectionStrategy = compMeta.changeDetection;
  20672. if (compMeta.viewProviders) {
  20673. viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  20674. }
  20675. if (compMeta.entryComponents) {
  20676. entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
  20677. .map(function (type) { return _this._getEntryComponentMetadata(type); })
  20678. .concat(entryComponentMetadata);
  20679. }
  20680. if (!selector) {
  20681. selector = this._schemaRegistry.getDefaultComponentElementName();
  20682. }
  20683. }
  20684. else {
  20685. // Directive
  20686. if (!selector) {
  20687. this._reportError(syntaxError("Directive " + stringifyType(directiveType) + " has no selector, please add it!"), directiveType);
  20688. selector = 'error';
  20689. }
  20690. }
  20691. var providers = [];
  20692. if (dirMeta.providers != null) {
  20693. providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  20694. }
  20695. var queries = [];
  20696. var viewQueries = [];
  20697. if (dirMeta.queries != null) {
  20698. queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
  20699. viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
  20700. }
  20701. var metadata = CompileDirectiveMetadata.create({
  20702. isHost: false,
  20703. selector: selector,
  20704. exportAs: noUndefined(dirMeta.exportAs),
  20705. isComponent: !!nonNormalizedTemplateMetadata,
  20706. type: this._getTypeMetadata(directiveType),
  20707. template: nonNormalizedTemplateMetadata,
  20708. changeDetection: changeDetectionStrategy,
  20709. inputs: dirMeta.inputs || [],
  20710. outputs: dirMeta.outputs || [],
  20711. host: dirMeta.host || {},
  20712. providers: providers || [],
  20713. viewProviders: viewProviders || [],
  20714. queries: queries || [],
  20715. guards: dirMeta.guards || {},
  20716. viewQueries: viewQueries || [],
  20717. entryComponents: entryComponentMetadata,
  20718. componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
  20719. null,
  20720. rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
  20721. componentFactory: null
  20722. });
  20723. if (nonNormalizedTemplateMetadata) {
  20724. metadata.componentFactory =
  20725. this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
  20726. }
  20727. cacheEntry = { metadata: metadata, annotation: dirMeta };
  20728. this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
  20729. return cacheEntry;
  20730. };
  20731. /**
  20732. * Gets the metadata for the given directive.
  20733. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  20734. */
  20735. CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
  20736. var dirMeta = this._directiveCache.get(directiveType);
  20737. if (!dirMeta) {
  20738. this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
  20739. }
  20740. return dirMeta;
  20741. };
  20742. CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
  20743. var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
  20744. if (!dirSummary) {
  20745. this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
  20746. }
  20747. return dirSummary;
  20748. };
  20749. CompileMetadataResolver.prototype.isDirective = function (type) {
  20750. return !!this._loadSummary(type, CompileSummaryKind.Directive) ||
  20751. this._directiveResolver.isDirective(type);
  20752. };
  20753. CompileMetadataResolver.prototype.isPipe = function (type) {
  20754. return !!this._loadSummary(type, CompileSummaryKind.Pipe) ||
  20755. this._pipeResolver.isPipe(type);
  20756. };
  20757. CompileMetadataResolver.prototype.isNgModule = function (type) {
  20758. return !!this._loadSummary(type, CompileSummaryKind.NgModule) ||
  20759. this._ngModuleResolver.isNgModule(type);
  20760. };
  20761. CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType, alreadyCollecting) {
  20762. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  20763. var moduleSummary = this._loadSummary(moduleType, CompileSummaryKind.NgModule);
  20764. if (!moduleSummary) {
  20765. var moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
  20766. moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
  20767. if (moduleSummary) {
  20768. this._summaryCache.set(moduleType, moduleSummary);
  20769. }
  20770. }
  20771. return moduleSummary;
  20772. };
  20773. /**
  20774. * Loads the declared directives and pipes of an NgModule.
  20775. */
  20776. CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
  20777. var _this = this;
  20778. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20779. var ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
  20780. var loading = [];
  20781. if (ngModule) {
  20782. ngModule.declaredDirectives.forEach(function (id) {
  20783. var promise = _this.loadDirectiveMetadata(moduleType, id.reference, isSync);
  20784. if (promise) {
  20785. loading.push(promise);
  20786. }
  20787. });
  20788. ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
  20789. }
  20790. return Promise.all(loading);
  20791. };
  20792. CompileMetadataResolver.prototype.getShallowModuleMetadata = function (moduleType) {
  20793. var compileMeta = this._shallowModuleCache.get(moduleType);
  20794. if (compileMeta) {
  20795. return compileMeta;
  20796. }
  20797. var ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
  20798. compileMeta = {
  20799. type: this._getTypeMetadata(moduleType),
  20800. rawExports: ngModuleMeta.exports,
  20801. rawImports: ngModuleMeta.imports,
  20802. rawProviders: ngModuleMeta.providers,
  20803. };
  20804. this._shallowModuleCache.set(moduleType, compileMeta);
  20805. return compileMeta;
  20806. };
  20807. CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound, alreadyCollecting) {
  20808. var _this = this;
  20809. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20810. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  20811. moduleType = resolveForwardRef(moduleType);
  20812. var compileMeta = this._ngModuleCache.get(moduleType);
  20813. if (compileMeta) {
  20814. return compileMeta;
  20815. }
  20816. var meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
  20817. if (!meta) {
  20818. return null;
  20819. }
  20820. var declaredDirectives = [];
  20821. var exportedNonModuleIdentifiers = [];
  20822. var declaredPipes = [];
  20823. var importedModules = [];
  20824. var exportedModules = [];
  20825. var providers = [];
  20826. var entryComponents = [];
  20827. var bootstrapComponents = [];
  20828. var schemas = [];
  20829. if (meta.imports) {
  20830. flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
  20831. var importedModuleType = undefined;
  20832. if (isValidType(importedType)) {
  20833. importedModuleType = importedType;
  20834. }
  20835. else if (importedType && importedType.ngModule) {
  20836. var moduleWithProviders = importedType;
  20837. importedModuleType = moduleWithProviders.ngModule;
  20838. if (moduleWithProviders.providers) {
  20839. providers.push.apply(providers, __spread(_this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType)));
  20840. }
  20841. }
  20842. if (importedModuleType) {
  20843. if (_this._checkSelfImport(moduleType, importedModuleType))
  20844. return;
  20845. if (!alreadyCollecting)
  20846. alreadyCollecting = new Set();
  20847. if (alreadyCollecting.has(importedModuleType)) {
  20848. _this._reportError(syntaxError(_this._getTypeDescriptor(importedModuleType) + " '" + stringifyType(importedType) + "' is imported recursively by the module '" + stringifyType(moduleType) + "'."), moduleType);
  20849. return;
  20850. }
  20851. alreadyCollecting.add(importedModuleType);
  20852. var importedModuleSummary = _this.getNgModuleSummary(importedModuleType, alreadyCollecting);
  20853. alreadyCollecting.delete(importedModuleType);
  20854. if (!importedModuleSummary) {
  20855. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation."), moduleType);
  20856. return;
  20857. }
  20858. importedModules.push(importedModuleSummary);
  20859. }
  20860. else {
  20861. _this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20862. return;
  20863. }
  20864. });
  20865. }
  20866. if (meta.exports) {
  20867. flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
  20868. if (!isValidType(exportedType)) {
  20869. _this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20870. return;
  20871. }
  20872. if (!alreadyCollecting)
  20873. alreadyCollecting = new Set();
  20874. if (alreadyCollecting.has(exportedType)) {
  20875. _this._reportError(syntaxError(_this._getTypeDescriptor(exportedType) + " '" + stringify(exportedType) + "' is exported recursively by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20876. return;
  20877. }
  20878. alreadyCollecting.add(exportedType);
  20879. var exportedModuleSummary = _this.getNgModuleSummary(exportedType, alreadyCollecting);
  20880. alreadyCollecting.delete(exportedType);
  20881. if (exportedModuleSummary) {
  20882. exportedModules.push(exportedModuleSummary);
  20883. }
  20884. else {
  20885. exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
  20886. }
  20887. });
  20888. }
  20889. // Note: This will be modified later, so we rely on
  20890. // getting a new instance every time!
  20891. var transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
  20892. if (meta.declarations) {
  20893. flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
  20894. if (!isValidType(declaredType)) {
  20895. _this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20896. return;
  20897. }
  20898. var declaredIdentifier = _this._getIdentifierMetadata(declaredType);
  20899. if (_this.isDirective(declaredType)) {
  20900. transitiveModule.addDirective(declaredIdentifier);
  20901. declaredDirectives.push(declaredIdentifier);
  20902. _this._addTypeToModule(declaredType, moduleType);
  20903. }
  20904. else if (_this.isPipe(declaredType)) {
  20905. transitiveModule.addPipe(declaredIdentifier);
  20906. transitiveModule.pipes.push(declaredIdentifier);
  20907. declaredPipes.push(declaredIdentifier);
  20908. _this._addTypeToModule(declaredType, moduleType);
  20909. }
  20910. else {
  20911. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
  20912. return;
  20913. }
  20914. });
  20915. }
  20916. var exportedDirectives = [];
  20917. var exportedPipes = [];
  20918. exportedNonModuleIdentifiers.forEach(function (exportedId) {
  20919. if (transitiveModule.directivesSet.has(exportedId.reference)) {
  20920. exportedDirectives.push(exportedId);
  20921. transitiveModule.addExportedDirective(exportedId);
  20922. }
  20923. else if (transitiveModule.pipesSet.has(exportedId.reference)) {
  20924. exportedPipes.push(exportedId);
  20925. transitiveModule.addExportedPipe(exportedId);
  20926. }
  20927. else {
  20928. _this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
  20929. return;
  20930. }
  20931. });
  20932. // The providers of the module have to go last
  20933. // so that they overwrite any other provider we already added.
  20934. if (meta.providers) {
  20935. providers.push.apply(providers, __spread(this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType)));
  20936. }
  20937. if (meta.entryComponents) {
  20938. entryComponents.push.apply(entryComponents, __spread(flattenAndDedupeArray(meta.entryComponents)
  20939. .map(function (type) { return _this._getEntryComponentMetadata(type); })));
  20940. }
  20941. if (meta.bootstrap) {
  20942. flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
  20943. if (!isValidType(type)) {
  20944. _this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
  20945. return;
  20946. }
  20947. bootstrapComponents.push(_this._getIdentifierMetadata(type));
  20948. });
  20949. }
  20950. entryComponents.push.apply(entryComponents, __spread(bootstrapComponents.map(function (type) { return _this._getEntryComponentMetadata(type.reference); })));
  20951. if (meta.schemas) {
  20952. schemas.push.apply(schemas, __spread(flattenAndDedupeArray(meta.schemas)));
  20953. }
  20954. compileMeta = new CompileNgModuleMetadata({
  20955. type: this._getTypeMetadata(moduleType),
  20956. providers: providers,
  20957. entryComponents: entryComponents,
  20958. bootstrapComponents: bootstrapComponents,
  20959. schemas: schemas,
  20960. declaredDirectives: declaredDirectives,
  20961. exportedDirectives: exportedDirectives,
  20962. declaredPipes: declaredPipes,
  20963. exportedPipes: exportedPipes,
  20964. importedModules: importedModules,
  20965. exportedModules: exportedModules,
  20966. transitiveModule: transitiveModule,
  20967. id: meta.id || null,
  20968. });
  20969. entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
  20970. providers.forEach(function (provider) { return transitiveModule.addProvider(provider, compileMeta.type); });
  20971. transitiveModule.addModule(compileMeta.type);
  20972. this._ngModuleCache.set(moduleType, compileMeta);
  20973. return compileMeta;
  20974. };
  20975. CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
  20976. if (moduleType === importedModuleType) {
  20977. this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
  20978. return true;
  20979. }
  20980. return false;
  20981. };
  20982. CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
  20983. if (isValidType(type)) {
  20984. if (this.isDirective(type)) {
  20985. return 'directive';
  20986. }
  20987. if (this.isPipe(type)) {
  20988. return 'pipe';
  20989. }
  20990. if (this.isNgModule(type)) {
  20991. return 'module';
  20992. }
  20993. }
  20994. if (type.provide) {
  20995. return 'provider';
  20996. }
  20997. return 'value';
  20998. };
  20999. CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
  21000. var oldModule = this._ngModuleOfTypes.get(type);
  21001. if (oldModule && oldModule !== moduleType) {
  21002. this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
  21003. ("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
  21004. ("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
  21005. return;
  21006. }
  21007. this._ngModuleOfTypes.set(type, moduleType);
  21008. };
  21009. CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
  21010. // collect `providers` / `entryComponents` from all imported and all exported modules
  21011. var result = new TransitiveCompileNgModuleMetadata();
  21012. var modulesByToken = new Map();
  21013. importedModules.concat(exportedModules).forEach(function (modSummary) {
  21014. modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
  21015. modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
  21016. var addedTokens = new Set();
  21017. modSummary.providers.forEach(function (entry) {
  21018. var tokenRef = tokenReference(entry.provider.token);
  21019. var prevModules = modulesByToken.get(tokenRef);
  21020. if (!prevModules) {
  21021. prevModules = new Set();
  21022. modulesByToken.set(tokenRef, prevModules);
  21023. }
  21024. var moduleRef = entry.module.reference;
  21025. // Note: the providers of one module may still contain multiple providers
  21026. // per token (e.g. for multi providers), and we need to preserve these.
  21027. if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
  21028. prevModules.add(moduleRef);
  21029. addedTokens.add(tokenRef);
  21030. result.addProvider(entry.provider, entry.module);
  21031. }
  21032. });
  21033. });
  21034. exportedModules.forEach(function (modSummary) {
  21035. modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
  21036. modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
  21037. });
  21038. importedModules.forEach(function (modSummary) {
  21039. modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
  21040. modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
  21041. });
  21042. return result;
  21043. };
  21044. CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
  21045. type = resolveForwardRef(type);
  21046. return { reference: type };
  21047. };
  21048. CompileMetadataResolver.prototype.isInjectable = function (type) {
  21049. var annotations = this._reflector.tryAnnotations(type);
  21050. return annotations.some(function (ann) { return createInjectable.isTypeOf(ann); });
  21051. };
  21052. CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
  21053. return {
  21054. summaryKind: CompileSummaryKind.Injectable,
  21055. type: this._getTypeMetadata(type, null, false)
  21056. };
  21057. };
  21058. CompileMetadataResolver.prototype.getInjectableMetadata = function (type, dependencies, throwOnUnknownDeps) {
  21059. if (dependencies === void 0) { dependencies = null; }
  21060. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  21061. var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
  21062. var typeMetadata = typeSummary ?
  21063. typeSummary.type :
  21064. this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
  21065. var annotations = this._reflector.annotations(type).filter(function (ann) { return createInjectable.isTypeOf(ann); });
  21066. if (annotations.length === 0) {
  21067. return null;
  21068. }
  21069. var meta = annotations[annotations.length - 1];
  21070. return {
  21071. symbol: type,
  21072. type: typeMetadata,
  21073. providedIn: meta.providedIn,
  21074. useValue: meta.useValue,
  21075. useClass: meta.useClass,
  21076. useExisting: meta.useExisting,
  21077. useFactory: meta.useFactory,
  21078. deps: meta.deps,
  21079. };
  21080. };
  21081. CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
  21082. if (dependencies === void 0) { dependencies = null; }
  21083. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  21084. var identifier = this._getIdentifierMetadata(type);
  21085. return {
  21086. reference: identifier.reference,
  21087. diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
  21088. lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
  21089. };
  21090. };
  21091. CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
  21092. if (dependencies === void 0) { dependencies = null; }
  21093. factory = resolveForwardRef(factory);
  21094. return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
  21095. };
  21096. /**
  21097. * Gets the metadata for the given pipe.
  21098. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  21099. */
  21100. CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
  21101. var pipeMeta = this._pipeCache.get(pipeType);
  21102. if (!pipeMeta) {
  21103. this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
  21104. }
  21105. return pipeMeta || null;
  21106. };
  21107. CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
  21108. var pipeSummary = this._loadSummary(pipeType, CompileSummaryKind.Pipe);
  21109. if (!pipeSummary) {
  21110. this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
  21111. }
  21112. return pipeSummary;
  21113. };
  21114. CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
  21115. var pipeMeta = this._pipeCache.get(pipeType);
  21116. if (!pipeMeta) {
  21117. pipeMeta = this._loadPipeMetadata(pipeType);
  21118. }
  21119. return pipeMeta;
  21120. };
  21121. CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
  21122. pipeType = resolveForwardRef(pipeType);
  21123. var pipeAnnotation = this._pipeResolver.resolve(pipeType);
  21124. var pipeMeta = new CompilePipeMetadata({
  21125. type: this._getTypeMetadata(pipeType),
  21126. name: pipeAnnotation.name,
  21127. pure: !!pipeAnnotation.pure
  21128. });
  21129. this._pipeCache.set(pipeType, pipeMeta);
  21130. this._summaryCache.set(pipeType, pipeMeta.toSummary());
  21131. return pipeMeta;
  21132. };
  21133. CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
  21134. var _this = this;
  21135. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  21136. var hasUnknownDeps = false;
  21137. var params = dependencies || this._reflector.parameters(typeOrFunc) || [];
  21138. var dependenciesMetadata = params.map(function (param) {
  21139. var isAttribute = false;
  21140. var isHost = false;
  21141. var isSelf = false;
  21142. var isSkipSelf = false;
  21143. var isOptional = false;
  21144. var token = null;
  21145. if (Array.isArray(param)) {
  21146. param.forEach(function (paramEntry) {
  21147. if (createHost.isTypeOf(paramEntry)) {
  21148. isHost = true;
  21149. }
  21150. else if (createSelf.isTypeOf(paramEntry)) {
  21151. isSelf = true;
  21152. }
  21153. else if (createSkipSelf.isTypeOf(paramEntry)) {
  21154. isSkipSelf = true;
  21155. }
  21156. else if (createOptional.isTypeOf(paramEntry)) {
  21157. isOptional = true;
  21158. }
  21159. else if (createAttribute.isTypeOf(paramEntry)) {
  21160. isAttribute = true;
  21161. token = paramEntry.attributeName;
  21162. }
  21163. else if (createInject.isTypeOf(paramEntry)) {
  21164. token = paramEntry.token;
  21165. }
  21166. else if (createInjectionToken.isTypeOf(paramEntry) ||
  21167. paramEntry instanceof StaticSymbol) {
  21168. token = paramEntry;
  21169. }
  21170. else if (isValidType(paramEntry) && token == null) {
  21171. token = paramEntry;
  21172. }
  21173. });
  21174. }
  21175. else {
  21176. token = param;
  21177. }
  21178. if (token == null) {
  21179. hasUnknownDeps = true;
  21180. return {};
  21181. }
  21182. return {
  21183. isAttribute: isAttribute,
  21184. isHost: isHost,
  21185. isSelf: isSelf,
  21186. isSkipSelf: isSkipSelf,
  21187. isOptional: isOptional,
  21188. token: _this._getTokenMetadata(token)
  21189. };
  21190. });
  21191. if (hasUnknownDeps) {
  21192. var depsTokens = dependenciesMetadata.map(function (dep) { return dep.token ? stringifyType(dep.token) : '?'; }).join(', ');
  21193. var message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
  21194. if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
  21195. this._reportError(syntaxError(message), typeOrFunc);
  21196. }
  21197. else {
  21198. this._console.warn("Warning: " + message + " This will become an error in Angular v6.x");
  21199. }
  21200. }
  21201. return dependenciesMetadata;
  21202. };
  21203. CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
  21204. token = resolveForwardRef(token);
  21205. var compileToken;
  21206. if (typeof token === 'string') {
  21207. compileToken = { value: token };
  21208. }
  21209. else {
  21210. compileToken = { identifier: { reference: token } };
  21211. }
  21212. return compileToken;
  21213. };
  21214. CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
  21215. var _this = this;
  21216. if (compileProviders === void 0) { compileProviders = []; }
  21217. providers.forEach(function (provider, providerIdx) {
  21218. if (Array.isArray(provider)) {
  21219. _this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
  21220. }
  21221. else {
  21222. provider = resolveForwardRef(provider);
  21223. var providerMeta = undefined;
  21224. if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
  21225. _this._validateProvider(provider);
  21226. providerMeta = new ProviderMeta(provider.provide, provider);
  21227. }
  21228. else if (isValidType(provider)) {
  21229. providerMeta = new ProviderMeta(provider, { useClass: provider });
  21230. }
  21231. else if (provider === void 0) {
  21232. _this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."));
  21233. return;
  21234. }
  21235. else {
  21236. var providersInfo = providers.reduce(function (soFar, seenProvider, seenProviderIdx) {
  21237. if (seenProviderIdx < providerIdx) {
  21238. soFar.push("" + stringifyType(seenProvider));
  21239. }
  21240. else if (seenProviderIdx == providerIdx) {
  21241. soFar.push("?" + stringifyType(seenProvider) + "?");
  21242. }
  21243. else if (seenProviderIdx == providerIdx + 1) {
  21244. soFar.push('...');
  21245. }
  21246. return soFar;
  21247. }, [])
  21248. .join(', ');
  21249. _this._reportError(syntaxError("Invalid " + (debugInfo ? debugInfo : 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
  21250. return;
  21251. }
  21252. if (providerMeta.token ===
  21253. _this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
  21254. targetEntryComponents.push.apply(targetEntryComponents, __spread(_this._getEntryComponentsFromProvider(providerMeta, type)));
  21255. }
  21256. else {
  21257. compileProviders.push(_this.getProviderMetadata(providerMeta));
  21258. }
  21259. }
  21260. });
  21261. return compileProviders;
  21262. };
  21263. CompileMetadataResolver.prototype._validateProvider = function (provider) {
  21264. if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
  21265. this._reportError(syntaxError("Invalid provider for " + stringifyType(provider.provide) + ". useClass cannot be " + provider.useClass + ".\n Usually it happens when:\n 1. There's a circular dependency (might be caused by using index.ts (barrel) files).\n 2. Class was used before it was declared. Use forwardRef in this case."));
  21266. }
  21267. };
  21268. CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
  21269. var _this = this;
  21270. var components = [];
  21271. var collectedIdentifiers = [];
  21272. if (provider.useFactory || provider.useExisting || provider.useClass) {
  21273. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
  21274. return [];
  21275. }
  21276. if (!provider.multi) {
  21277. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
  21278. return [];
  21279. }
  21280. extractIdentifiers(provider.useValue, collectedIdentifiers);
  21281. collectedIdentifiers.forEach(function (identifier) {
  21282. var entry = _this._getEntryComponentMetadata(identifier.reference, false);
  21283. if (entry) {
  21284. components.push(entry);
  21285. }
  21286. });
  21287. return components;
  21288. };
  21289. CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
  21290. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  21291. var dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
  21292. if (dirMeta && dirMeta.metadata.isComponent) {
  21293. return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
  21294. }
  21295. var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
  21296. if (dirSummary && dirSummary.isComponent) {
  21297. return { componentType: dirType, componentFactory: dirSummary.componentFactory };
  21298. }
  21299. if (throwIfNotFound) {
  21300. throw syntaxError(dirType.name + " cannot be used as an entry component.");
  21301. }
  21302. return null;
  21303. };
  21304. CompileMetadataResolver.prototype._getInjectableTypeMetadata = function (type, dependencies) {
  21305. if (dependencies === void 0) { dependencies = null; }
  21306. var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
  21307. if (typeSummary) {
  21308. return typeSummary.type;
  21309. }
  21310. return this._getTypeMetadata(type, dependencies);
  21311. };
  21312. CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
  21313. var compileDeps = undefined;
  21314. var compileTypeMetadata = null;
  21315. var compileFactoryMetadata = null;
  21316. var token = this._getTokenMetadata(provider.token);
  21317. if (provider.useClass) {
  21318. compileTypeMetadata =
  21319. this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
  21320. compileDeps = compileTypeMetadata.diDeps;
  21321. if (provider.token === provider.useClass) {
  21322. // use the compileTypeMetadata as it contains information about lifecycleHooks...
  21323. token = { identifier: compileTypeMetadata };
  21324. }
  21325. }
  21326. else if (provider.useFactory) {
  21327. compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
  21328. compileDeps = compileFactoryMetadata.diDeps;
  21329. }
  21330. return {
  21331. token: token,
  21332. useClass: compileTypeMetadata,
  21333. useValue: provider.useValue,
  21334. useFactory: compileFactoryMetadata,
  21335. useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
  21336. deps: compileDeps,
  21337. multi: provider.multi
  21338. };
  21339. };
  21340. CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
  21341. var _this = this;
  21342. var res = [];
  21343. Object.keys(queries).forEach(function (propertyName) {
  21344. var query = queries[propertyName];
  21345. if (query.isViewQuery === isViewQuery) {
  21346. res.push(_this._getQueryMetadata(query, propertyName, directiveType));
  21347. }
  21348. });
  21349. return res;
  21350. };
  21351. CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); };
  21352. CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
  21353. var _this = this;
  21354. var selectors;
  21355. if (typeof q.selector === 'string') {
  21356. selectors =
  21357. this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
  21358. }
  21359. else {
  21360. if (!q.selector) {
  21361. this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
  21362. selectors = [];
  21363. }
  21364. else {
  21365. selectors = [this._getTokenMetadata(q.selector)];
  21366. }
  21367. }
  21368. return {
  21369. selectors: selectors,
  21370. first: q.first,
  21371. descendants: q.descendants, propertyName: propertyName,
  21372. read: q.read ? this._getTokenMetadata(q.read) : null,
  21373. static: q.static
  21374. };
  21375. };
  21376. CompileMetadataResolver.prototype._reportError = function (error, type, otherType) {
  21377. if (this._errorCollector) {
  21378. this._errorCollector(error, type);
  21379. if (otherType) {
  21380. this._errorCollector(error, otherType);
  21381. }
  21382. }
  21383. else {
  21384. throw error;
  21385. }
  21386. };
  21387. return CompileMetadataResolver;
  21388. }());
  21389. function flattenArray(tree, out) {
  21390. if (out === void 0) { out = []; }
  21391. if (tree) {
  21392. for (var i = 0; i < tree.length; i++) {
  21393. var item = resolveForwardRef(tree[i]);
  21394. if (Array.isArray(item)) {
  21395. flattenArray(item, out);
  21396. }
  21397. else {
  21398. out.push(item);
  21399. }
  21400. }
  21401. }
  21402. return out;
  21403. }
  21404. function dedupeArray(array) {
  21405. if (array) {
  21406. return Array.from(new Set(array));
  21407. }
  21408. return [];
  21409. }
  21410. function flattenAndDedupeArray(tree) {
  21411. return dedupeArray(flattenArray(tree));
  21412. }
  21413. function isValidType(value) {
  21414. return (value instanceof StaticSymbol) || (value instanceof Type);
  21415. }
  21416. function extractIdentifiers(value, targetIdentifiers) {
  21417. visitValue(value, new _CompileValueConverter(), targetIdentifiers);
  21418. }
  21419. var _CompileValueConverter = /** @class */ (function (_super) {
  21420. __extends(_CompileValueConverter, _super);
  21421. function _CompileValueConverter() {
  21422. return _super !== null && _super.apply(this, arguments) || this;
  21423. }
  21424. _CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
  21425. targetIdentifiers.push({ reference: value });
  21426. };
  21427. return _CompileValueConverter;
  21428. }(ValueTransformer));
  21429. function stringifyType(type) {
  21430. if (type instanceof StaticSymbol) {
  21431. return type.name + " in " + type.filePath;
  21432. }
  21433. else {
  21434. return stringify(type);
  21435. }
  21436. }
  21437. /**
  21438. * Indicates that a component is still being loaded in a synchronous compile.
  21439. */
  21440. function componentStillLoadingError(compType) {
  21441. var error = Error("Can't compile synchronously as " + stringify(compType) + " is still being loaded!");
  21442. error[ERROR_COMPONENT_TYPE] = compType;
  21443. return error;
  21444. }
  21445. /**
  21446. * @license
  21447. * Copyright Google Inc. All Rights Reserved.
  21448. *
  21449. * Use of this source code is governed by an MIT-style license that can be
  21450. * found in the LICENSE file at https://angular.io/license
  21451. */
  21452. function providerDef(ctx, providerAst) {
  21453. var flags = 0 /* None */;
  21454. if (!providerAst.eager) {
  21455. flags |= 4096 /* LazyProvider */;
  21456. }
  21457. if (providerAst.providerType === ProviderAstType.PrivateService) {
  21458. flags |= 8192 /* PrivateProvider */;
  21459. }
  21460. if (providerAst.isModule) {
  21461. flags |= 1073741824 /* TypeModuleProvider */;
  21462. }
  21463. providerAst.lifecycleHooks.forEach(function (lifecycleHook) {
  21464. // for regular providers, we only support ngOnDestroy
  21465. if (lifecycleHook === LifecycleHooks.OnDestroy ||
  21466. providerAst.providerType === ProviderAstType.Directive ||
  21467. providerAst.providerType === ProviderAstType.Component) {
  21468. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  21469. }
  21470. });
  21471. var _a = providerAst.multiProvider ?
  21472. multiProviderDef(ctx, flags, providerAst.providers) :
  21473. singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
  21474. return {
  21475. providerExpr: providerExpr,
  21476. flags: providerFlags, depsExpr: depsExpr,
  21477. tokenExpr: tokenExpr(ctx, providerAst.token),
  21478. };
  21479. }
  21480. function multiProviderDef(ctx, flags, providers) {
  21481. var allDepDefs = [];
  21482. var allParams = [];
  21483. var exprs = providers.map(function (provider, providerIndex) {
  21484. var expr;
  21485. if (provider.useClass) {
  21486. var depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
  21487. expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
  21488. }
  21489. else if (provider.useFactory) {
  21490. var depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
  21491. expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
  21492. }
  21493. else if (provider.useExisting) {
  21494. var depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
  21495. expr = depExprs[0];
  21496. }
  21497. else {
  21498. expr = convertValueToOutputAst(ctx, provider.useValue);
  21499. }
  21500. return expr;
  21501. });
  21502. var providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
  21503. return {
  21504. providerExpr: providerExpr,
  21505. flags: flags | 1024 /* TypeFactoryProvider */,
  21506. depsExpr: literalArr(allDepDefs)
  21507. };
  21508. function convertDeps(providerIndex, deps) {
  21509. return deps.map(function (dep, depIndex) {
  21510. var paramName = "p" + providerIndex + "_" + depIndex;
  21511. allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
  21512. allDepDefs.push(depDef(ctx, dep));
  21513. return variable(paramName);
  21514. });
  21515. }
  21516. }
  21517. function singleProviderDef(ctx, flags, providerType, providerMeta) {
  21518. var providerExpr;
  21519. var deps;
  21520. if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {
  21521. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  21522. flags |= 16384 /* TypeDirective */;
  21523. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  21524. }
  21525. else {
  21526. if (providerMeta.useClass) {
  21527. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  21528. flags |= 512 /* TypeClassProvider */;
  21529. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  21530. }
  21531. else if (providerMeta.useFactory) {
  21532. providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
  21533. flags |= 1024 /* TypeFactoryProvider */;
  21534. deps = providerMeta.deps || providerMeta.useFactory.diDeps;
  21535. }
  21536. else if (providerMeta.useExisting) {
  21537. providerExpr = NULL_EXPR;
  21538. flags |= 2048 /* TypeUseExistingProvider */;
  21539. deps = [{ token: providerMeta.useExisting }];
  21540. }
  21541. else {
  21542. providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
  21543. flags |= 256 /* TypeValueProvider */;
  21544. deps = [];
  21545. }
  21546. }
  21547. var depsExpr = literalArr(deps.map(function (dep) { return depDef(ctx, dep); }));
  21548. return { providerExpr: providerExpr, flags: flags, depsExpr: depsExpr };
  21549. }
  21550. function tokenExpr(ctx, tokenMeta) {
  21551. return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
  21552. literal(tokenMeta.value);
  21553. }
  21554. function depDef(ctx, dep) {
  21555. // Note: the following fields have already been normalized out by provider_analyzer:
  21556. // - isAttribute, isHost
  21557. var expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
  21558. var flags = 0 /* None */;
  21559. if (dep.isSkipSelf) {
  21560. flags |= 1 /* SkipSelf */;
  21561. }
  21562. if (dep.isOptional) {
  21563. flags |= 2 /* Optional */;
  21564. }
  21565. if (dep.isSelf) {
  21566. flags |= 4 /* Self */;
  21567. }
  21568. if (dep.isValue) {
  21569. flags |= 8 /* Value */;
  21570. }
  21571. return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
  21572. }
  21573. function lifecycleHookToNodeFlag(lifecycleHook) {
  21574. var nodeFlag = 0 /* None */;
  21575. switch (lifecycleHook) {
  21576. case LifecycleHooks.AfterContentChecked:
  21577. nodeFlag = 2097152 /* AfterContentChecked */;
  21578. break;
  21579. case LifecycleHooks.AfterContentInit:
  21580. nodeFlag = 1048576 /* AfterContentInit */;
  21581. break;
  21582. case LifecycleHooks.AfterViewChecked:
  21583. nodeFlag = 8388608 /* AfterViewChecked */;
  21584. break;
  21585. case LifecycleHooks.AfterViewInit:
  21586. nodeFlag = 4194304 /* AfterViewInit */;
  21587. break;
  21588. case LifecycleHooks.DoCheck:
  21589. nodeFlag = 262144 /* DoCheck */;
  21590. break;
  21591. case LifecycleHooks.OnChanges:
  21592. nodeFlag = 524288 /* OnChanges */;
  21593. break;
  21594. case LifecycleHooks.OnDestroy:
  21595. nodeFlag = 131072 /* OnDestroy */;
  21596. break;
  21597. case LifecycleHooks.OnInit:
  21598. nodeFlag = 65536 /* OnInit */;
  21599. break;
  21600. }
  21601. return nodeFlag;
  21602. }
  21603. function componentFactoryResolverProviderDef(reflector, ctx, flags, entryComponents) {
  21604. var entryComponentFactories = entryComponents.map(function (entryComponent) { return ctx.importExpr(entryComponent.componentFactory); });
  21605. var token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
  21606. var classMeta = {
  21607. diDeps: [
  21608. { isValue: true, value: literalArr(entryComponentFactories) },
  21609. { token: token, isSkipSelf: true, isOptional: true },
  21610. { token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef) },
  21611. ],
  21612. lifecycleHooks: [],
  21613. reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
  21614. };
  21615. var _a = singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {
  21616. token: token,
  21617. multi: false,
  21618. useClass: classMeta,
  21619. }), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
  21620. return { providerExpr: providerExpr, flags: providerFlags, depsExpr: depsExpr, tokenExpr: tokenExpr(ctx, token) };
  21621. }
  21622. /**
  21623. * @license
  21624. * Copyright Google Inc. All Rights Reserved.
  21625. *
  21626. * Use of this source code is governed by an MIT-style license that can be
  21627. * found in the LICENSE file at https://angular.io/license
  21628. */
  21629. var NgModuleCompileResult = /** @class */ (function () {
  21630. function NgModuleCompileResult(ngModuleFactoryVar) {
  21631. this.ngModuleFactoryVar = ngModuleFactoryVar;
  21632. }
  21633. return NgModuleCompileResult;
  21634. }());
  21635. var LOG_VAR = variable('_l');
  21636. var NgModuleCompiler = /** @class */ (function () {
  21637. function NgModuleCompiler(reflector) {
  21638. this.reflector = reflector;
  21639. }
  21640. NgModuleCompiler.prototype.compile = function (ctx, ngModuleMeta, extraProviders) {
  21641. var sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
  21642. var entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
  21643. var bootstrapComponents = ngModuleMeta.bootstrapComponents;
  21644. var providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
  21645. var providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
  21646. .concat(providerParser.parse().map(function (provider) { return providerDef(ctx, provider); }))
  21647. .map(function (_a) {
  21648. var providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
  21649. return importExpr(Identifiers.moduleProviderDef).callFn([
  21650. literal(flags), tokenExpr, providerExpr, depsExpr
  21651. ]);
  21652. });
  21653. var ngModuleDef = importExpr(Identifiers.moduleDef).callFn([literalArr(providerDefs)]);
  21654. var ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
  21655. var ngModuleFactoryVar = identifierName(ngModuleMeta.type) + "NgFactory";
  21656. this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers.createModuleFactory).callFn([
  21657. ctx.importExpr(ngModuleMeta.type.reference),
  21658. literalArr(bootstrapComponents.map(function (id) { return ctx.importExpr(id.reference); })),
  21659. ngModuleDefFactory
  21660. ]));
  21661. if (ngModuleMeta.id) {
  21662. var id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
  21663. ctx.importExpr(ngModuleMeta.id);
  21664. var registerFactoryStmt = importExpr(Identifiers.RegisterModuleFactoryFn)
  21665. .callFn([id, variable(ngModuleFactoryVar)])
  21666. .toStmt();
  21667. ctx.statements.push(registerFactoryStmt);
  21668. }
  21669. return new NgModuleCompileResult(ngModuleFactoryVar);
  21670. };
  21671. NgModuleCompiler.prototype.createStub = function (ctx, ngModuleReference) {
  21672. this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
  21673. };
  21674. NgModuleCompiler.prototype._createNgModuleFactory = function (ctx, reference, value) {
  21675. var ngModuleFactoryVar = identifierName({ reference: reference }) + "NgFactory";
  21676. var ngModuleFactoryStmt = variable(ngModuleFactoryVar)
  21677. .set(value)
  21678. .toDeclStmt(importType(Identifiers.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]);
  21679. ctx.statements.push(ngModuleFactoryStmt);
  21680. };
  21681. return NgModuleCompiler;
  21682. }());
  21683. /**
  21684. * @license
  21685. * Copyright Google Inc. All Rights Reserved.
  21686. *
  21687. * Use of this source code is governed by an MIT-style license that can be
  21688. * found in the LICENSE file at https://angular.io/license
  21689. */
  21690. /**
  21691. * Resolves types to {@link NgModule}.
  21692. */
  21693. var NgModuleResolver = /** @class */ (function () {
  21694. function NgModuleResolver(_reflector) {
  21695. this._reflector = _reflector;
  21696. }
  21697. NgModuleResolver.prototype.isNgModule = function (type) { return this._reflector.annotations(type).some(createNgModule.isTypeOf); };
  21698. NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
  21699. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  21700. var ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
  21701. if (ngModuleMeta) {
  21702. return ngModuleMeta;
  21703. }
  21704. else {
  21705. if (throwIfNotFound) {
  21706. throw new Error("No NgModule metadata found for '" + stringify(type) + "'.");
  21707. }
  21708. return null;
  21709. }
  21710. };
  21711. return NgModuleResolver;
  21712. }());
  21713. /**
  21714. * @license
  21715. * Copyright Google Inc. All Rights Reserved.
  21716. *
  21717. * Use of this source code is governed by an MIT-style license that can be
  21718. * found in the LICENSE file at https://angular.io/license
  21719. */
  21720. function debugOutputAstAsTypeScript(ast) {
  21721. var converter = new _TsEmitterVisitor();
  21722. var ctx = EmitterVisitorContext.createRoot();
  21723. var asts = Array.isArray(ast) ? ast : [ast];
  21724. asts.forEach(function (ast) {
  21725. if (ast instanceof Statement) {
  21726. ast.visitStatement(converter, ctx);
  21727. }
  21728. else if (ast instanceof Expression) {
  21729. ast.visitExpression(converter, ctx);
  21730. }
  21731. else if (ast instanceof Type$1) {
  21732. ast.visitType(converter, ctx);
  21733. }
  21734. else {
  21735. throw new Error("Don't know how to print debug info for " + ast);
  21736. }
  21737. });
  21738. return ctx.toSource();
  21739. }
  21740. var TypeScriptEmitter = /** @class */ (function () {
  21741. function TypeScriptEmitter() {
  21742. }
  21743. TypeScriptEmitter.prototype.emitStatementsAndContext = function (genFilePath, stmts, preamble, emitSourceMaps, referenceFilter, importFilter) {
  21744. if (preamble === void 0) { preamble = ''; }
  21745. if (emitSourceMaps === void 0) { emitSourceMaps = true; }
  21746. var converter = new _TsEmitterVisitor(referenceFilter, importFilter);
  21747. var ctx = EmitterVisitorContext.createRoot();
  21748. converter.visitAllStatements(stmts, ctx);
  21749. var preambleLines = preamble ? preamble.split('\n') : [];
  21750. converter.reexports.forEach(function (reexports, exportedModuleName) {
  21751. var reexportsCode = reexports.map(function (reexport) { return reexport.name + " as " + reexport.as; }).join(',');
  21752. preambleLines.push("export {" + reexportsCode + "} from '" + exportedModuleName + "';");
  21753. });
  21754. converter.importsWithPrefixes.forEach(function (prefix, importedModuleName) {
  21755. // Note: can't write the real word for import as it screws up system.js auto detection...
  21756. preambleLines.push("imp" +
  21757. ("ort * as " + prefix + " from '" + importedModuleName + "';"));
  21758. });
  21759. var sm = emitSourceMaps ?
  21760. ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
  21761. '';
  21762. var lines = __spread(preambleLines, [ctx.toSource(), sm]);
  21763. if (sm) {
  21764. // always add a newline at the end, as some tools have bugs without it.
  21765. lines.push('');
  21766. }
  21767. ctx.setPreambleLineCount(preambleLines.length);
  21768. return { sourceText: lines.join('\n'), context: ctx };
  21769. };
  21770. TypeScriptEmitter.prototype.emitStatements = function (genFilePath, stmts, preamble) {
  21771. if (preamble === void 0) { preamble = ''; }
  21772. return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
  21773. };
  21774. return TypeScriptEmitter;
  21775. }());
  21776. var _TsEmitterVisitor = /** @class */ (function (_super) {
  21777. __extends(_TsEmitterVisitor, _super);
  21778. function _TsEmitterVisitor(referenceFilter, importFilter) {
  21779. var _this = _super.call(this, false) || this;
  21780. _this.referenceFilter = referenceFilter;
  21781. _this.importFilter = importFilter;
  21782. _this.typeExpression = 0;
  21783. _this.importsWithPrefixes = new Map();
  21784. _this.reexports = new Map();
  21785. return _this;
  21786. }
  21787. _TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
  21788. if (defaultType === void 0) { defaultType = 'any'; }
  21789. if (t) {
  21790. this.typeExpression++;
  21791. t.visitType(this, ctx);
  21792. this.typeExpression--;
  21793. }
  21794. else {
  21795. ctx.print(null, defaultType);
  21796. }
  21797. };
  21798. _TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  21799. var value = ast.value;
  21800. if (value == null && ast.type != INFERRED_TYPE) {
  21801. ctx.print(ast, "(" + value + " as any)");
  21802. return null;
  21803. }
  21804. return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
  21805. };
  21806. // Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
  21807. // In SNC mode, [] have the type never[], so we cast here to any[].
  21808. // TODO: narrow the cast to a more explicit type, or use a pattern that does not
  21809. // start with [].concat. see https://github.com/angular/angular/pull/11846
  21810. _TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  21811. if (ast.entries.length === 0) {
  21812. ctx.print(ast, '(');
  21813. }
  21814. var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
  21815. if (ast.entries.length === 0) {
  21816. ctx.print(ast, ' as any[])');
  21817. }
  21818. return result;
  21819. };
  21820. _TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  21821. this._visitIdentifier(ast.value, ast.typeParams, ctx);
  21822. return null;
  21823. };
  21824. _TsEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  21825. var result = _super.prototype.visitAssertNotNullExpr.call(this, ast, ctx);
  21826. ctx.print(ast, '!');
  21827. return result;
  21828. };
  21829. _TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  21830. if (stmt.hasModifier(StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
  21831. !stmt.type) {
  21832. // check for a reexport
  21833. var _a = stmt.value.value, name_1 = _a.name, moduleName = _a.moduleName;
  21834. if (moduleName) {
  21835. var reexports = this.reexports.get(moduleName);
  21836. if (!reexports) {
  21837. reexports = [];
  21838. this.reexports.set(moduleName, reexports);
  21839. }
  21840. reexports.push({ name: name_1, as: stmt.name });
  21841. return null;
  21842. }
  21843. }
  21844. if (stmt.hasModifier(StmtModifier.Exported)) {
  21845. ctx.print(stmt, "export ");
  21846. }
  21847. if (stmt.hasModifier(StmtModifier.Final)) {
  21848. ctx.print(stmt, "const");
  21849. }
  21850. else {
  21851. ctx.print(stmt, "var");
  21852. }
  21853. ctx.print(stmt, " " + stmt.name);
  21854. this._printColonType(stmt.type, ctx);
  21855. if (stmt.value) {
  21856. ctx.print(stmt, " = ");
  21857. stmt.value.visitExpression(this, ctx);
  21858. }
  21859. ctx.println(stmt, ";");
  21860. return null;
  21861. };
  21862. _TsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  21863. throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
  21864. };
  21865. _TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  21866. ctx.print(ast, "(<");
  21867. ast.type.visitType(this, ctx);
  21868. ctx.print(ast, ">");
  21869. ast.value.visitExpression(this, ctx);
  21870. ctx.print(ast, ")");
  21871. return null;
  21872. };
  21873. _TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  21874. ctx.print(ast, "new ");
  21875. this.typeExpression++;
  21876. ast.classExpr.visitExpression(this, ctx);
  21877. this.typeExpression--;
  21878. ctx.print(ast, "(");
  21879. this.visitAllExpressions(ast.args, ctx, ',');
  21880. ctx.print(ast, ")");
  21881. return null;
  21882. };
  21883. _TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  21884. var _this = this;
  21885. ctx.pushClass(stmt);
  21886. if (stmt.hasModifier(StmtModifier.Exported)) {
  21887. ctx.print(stmt, "export ");
  21888. }
  21889. ctx.print(stmt, "class " + stmt.name);
  21890. if (stmt.parent != null) {
  21891. ctx.print(stmt, " extends ");
  21892. this.typeExpression++;
  21893. stmt.parent.visitExpression(this, ctx);
  21894. this.typeExpression--;
  21895. }
  21896. ctx.println(stmt, " {");
  21897. ctx.incIndent();
  21898. stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
  21899. if (stmt.constructorMethod != null) {
  21900. this._visitClassConstructor(stmt, ctx);
  21901. }
  21902. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
  21903. stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
  21904. ctx.decIndent();
  21905. ctx.println(stmt, "}");
  21906. ctx.popClass();
  21907. return null;
  21908. };
  21909. _TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
  21910. if (field.hasModifier(StmtModifier.Private)) {
  21911. // comment out as a workaround for #10967
  21912. ctx.print(null, "/*private*/ ");
  21913. }
  21914. if (field.hasModifier(StmtModifier.Static)) {
  21915. ctx.print(null, 'static ');
  21916. }
  21917. ctx.print(null, field.name);
  21918. this._printColonType(field.type, ctx);
  21919. if (field.initializer) {
  21920. ctx.print(null, ' = ');
  21921. field.initializer.visitExpression(this, ctx);
  21922. }
  21923. ctx.println(null, ";");
  21924. };
  21925. _TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
  21926. if (getter.hasModifier(StmtModifier.Private)) {
  21927. ctx.print(null, "private ");
  21928. }
  21929. ctx.print(null, "get " + getter.name + "()");
  21930. this._printColonType(getter.type, ctx);
  21931. ctx.println(null, " {");
  21932. ctx.incIndent();
  21933. this.visitAllStatements(getter.body, ctx);
  21934. ctx.decIndent();
  21935. ctx.println(null, "}");
  21936. };
  21937. _TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  21938. ctx.print(stmt, "constructor(");
  21939. this._visitParams(stmt.constructorMethod.params, ctx);
  21940. ctx.println(stmt, ") {");
  21941. ctx.incIndent();
  21942. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  21943. ctx.decIndent();
  21944. ctx.println(stmt, "}");
  21945. };
  21946. _TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
  21947. if (method.hasModifier(StmtModifier.Private)) {
  21948. ctx.print(null, "private ");
  21949. }
  21950. ctx.print(null, method.name + "(");
  21951. this._visitParams(method.params, ctx);
  21952. ctx.print(null, ")");
  21953. this._printColonType(method.type, ctx, 'void');
  21954. ctx.println(null, " {");
  21955. ctx.incIndent();
  21956. this.visitAllStatements(method.body, ctx);
  21957. ctx.decIndent();
  21958. ctx.println(null, "}");
  21959. };
  21960. _TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  21961. if (ast.name) {
  21962. ctx.print(ast, 'function ');
  21963. ctx.print(ast, ast.name);
  21964. }
  21965. ctx.print(ast, "(");
  21966. this._visitParams(ast.params, ctx);
  21967. ctx.print(ast, ")");
  21968. this._printColonType(ast.type, ctx, 'void');
  21969. if (!ast.name) {
  21970. ctx.print(ast, " => ");
  21971. }
  21972. ctx.println(ast, '{');
  21973. ctx.incIndent();
  21974. this.visitAllStatements(ast.statements, ctx);
  21975. ctx.decIndent();
  21976. ctx.print(ast, "}");
  21977. return null;
  21978. };
  21979. _TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  21980. if (stmt.hasModifier(StmtModifier.Exported)) {
  21981. ctx.print(stmt, "export ");
  21982. }
  21983. ctx.print(stmt, "function " + stmt.name + "(");
  21984. this._visitParams(stmt.params, ctx);
  21985. ctx.print(stmt, ")");
  21986. this._printColonType(stmt.type, ctx, 'void');
  21987. ctx.println(stmt, " {");
  21988. ctx.incIndent();
  21989. this.visitAllStatements(stmt.statements, ctx);
  21990. ctx.decIndent();
  21991. ctx.println(stmt, "}");
  21992. return null;
  21993. };
  21994. _TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  21995. ctx.println(stmt, "try {");
  21996. ctx.incIndent();
  21997. this.visitAllStatements(stmt.bodyStmts, ctx);
  21998. ctx.decIndent();
  21999. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  22000. ctx.incIndent();
  22001. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
  22002. StmtModifier.Final
  22003. ])].concat(stmt.catchStmts);
  22004. this.visitAllStatements(catchStmts, ctx);
  22005. ctx.decIndent();
  22006. ctx.println(stmt, "}");
  22007. return null;
  22008. };
  22009. _TsEmitterVisitor.prototype.visitBuiltinType = function (type, ctx) {
  22010. var typeStr;
  22011. switch (type.name) {
  22012. case BuiltinTypeName.Bool:
  22013. typeStr = 'boolean';
  22014. break;
  22015. case BuiltinTypeName.Dynamic:
  22016. typeStr = 'any';
  22017. break;
  22018. case BuiltinTypeName.Function:
  22019. typeStr = 'Function';
  22020. break;
  22021. case BuiltinTypeName.Number:
  22022. typeStr = 'number';
  22023. break;
  22024. case BuiltinTypeName.Int:
  22025. typeStr = 'number';
  22026. break;
  22027. case BuiltinTypeName.String:
  22028. typeStr = 'string';
  22029. break;
  22030. case BuiltinTypeName.None:
  22031. typeStr = 'never';
  22032. break;
  22033. default:
  22034. throw new Error("Unsupported builtin type " + type.name);
  22035. }
  22036. ctx.print(null, typeStr);
  22037. return null;
  22038. };
  22039. _TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
  22040. var _this = this;
  22041. ast.value.visitExpression(this, ctx);
  22042. if (ast.typeParams !== null) {
  22043. ctx.print(null, '<');
  22044. this.visitAllObjects(function (type) { return _this.visitType(type, ctx); }, ast.typeParams, ctx, ',');
  22045. ctx.print(null, '>');
  22046. }
  22047. return null;
  22048. };
  22049. _TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
  22050. this.visitType(type.of, ctx);
  22051. ctx.print(null, "[]");
  22052. return null;
  22053. };
  22054. _TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
  22055. ctx.print(null, "{[key: string]:");
  22056. this.visitType(type.valueType, ctx);
  22057. ctx.print(null, "}");
  22058. return null;
  22059. };
  22060. _TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  22061. var name;
  22062. switch (method) {
  22063. case BuiltinMethod.ConcatArray:
  22064. name = 'concat';
  22065. break;
  22066. case BuiltinMethod.SubscribeObservable:
  22067. name = 'subscribe';
  22068. break;
  22069. case BuiltinMethod.Bind:
  22070. name = 'bind';
  22071. break;
  22072. default:
  22073. throw new Error("Unknown builtin method: " + method);
  22074. }
  22075. return name;
  22076. };
  22077. _TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  22078. var _this = this;
  22079. this.visitAllObjects(function (param) {
  22080. ctx.print(null, param.name);
  22081. _this._printColonType(param.type, ctx);
  22082. }, params, ctx, ',');
  22083. };
  22084. _TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
  22085. var _this = this;
  22086. var name = value.name, moduleName = value.moduleName;
  22087. if (this.referenceFilter && this.referenceFilter(value)) {
  22088. ctx.print(null, '(null as any)');
  22089. return;
  22090. }
  22091. if (moduleName && (!this.importFilter || !this.importFilter(value))) {
  22092. var prefix = this.importsWithPrefixes.get(moduleName);
  22093. if (prefix == null) {
  22094. prefix = "i" + this.importsWithPrefixes.size;
  22095. this.importsWithPrefixes.set(moduleName, prefix);
  22096. }
  22097. ctx.print(null, prefix + ".");
  22098. }
  22099. ctx.print(null, name);
  22100. if (this.typeExpression > 0) {
  22101. // If we are in a type expression that refers to a generic type then supply
  22102. // the required type parameters. If there were not enough type parameters
  22103. // supplied, supply any as the type. Outside a type expression the reference
  22104. // should not supply type parameters and be treated as a simple value reference
  22105. // to the constructor function itself.
  22106. var suppliedParameters = typeParams || [];
  22107. if (suppliedParameters.length > 0) {
  22108. ctx.print(null, "<");
  22109. this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, typeParams, ctx, ',');
  22110. ctx.print(null, ">");
  22111. }
  22112. }
  22113. };
  22114. _TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
  22115. if (type !== INFERRED_TYPE) {
  22116. ctx.print(null, ':');
  22117. this.visitType(type, ctx, defaultType);
  22118. }
  22119. };
  22120. return _TsEmitterVisitor;
  22121. }(AbstractEmitterVisitor));
  22122. /**
  22123. * @license
  22124. * Copyright Google Inc. All Rights Reserved.
  22125. *
  22126. * Use of this source code is governed by an MIT-style license that can be
  22127. * found in the LICENSE file at https://angular.io/license
  22128. */
  22129. /**
  22130. * Resolve a `Type` for {@link Pipe}.
  22131. *
  22132. * This interface can be overridden by the application developer to create custom behavior.
  22133. *
  22134. * See {@link Compiler}
  22135. */
  22136. var PipeResolver = /** @class */ (function () {
  22137. function PipeResolver(_reflector) {
  22138. this._reflector = _reflector;
  22139. }
  22140. PipeResolver.prototype.isPipe = function (type) {
  22141. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  22142. return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
  22143. };
  22144. /**
  22145. * Return {@link Pipe} for a given `Type`.
  22146. */
  22147. PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
  22148. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  22149. var metas = this._reflector.annotations(resolveForwardRef(type));
  22150. if (metas) {
  22151. var annotation = findLast(metas, createPipe.isTypeOf);
  22152. if (annotation) {
  22153. return annotation;
  22154. }
  22155. }
  22156. if (throwIfNotFound) {
  22157. throw new Error("No Pipe decorator found on " + stringify(type));
  22158. }
  22159. return null;
  22160. };
  22161. return PipeResolver;
  22162. }());
  22163. /**
  22164. * @license
  22165. * Copyright Google Inc. All Rights Reserved.
  22166. *
  22167. * Use of this source code is governed by an MIT-style license that can be
  22168. * found in the LICENSE file at https://angular.io/license
  22169. */
  22170. /**
  22171. * Generates code that is used to type check templates.
  22172. */
  22173. var TypeCheckCompiler = /** @class */ (function () {
  22174. function TypeCheckCompiler(options, reflector) {
  22175. this.options = options;
  22176. this.reflector = reflector;
  22177. }
  22178. /**
  22179. * Important notes:
  22180. * - This must not produce new `import` statements, but only refer to types outside
  22181. * of the file via the variables provided via externalReferenceVars.
  22182. * This allows Typescript to reuse the old program's structure as no imports have changed.
  22183. * - This must not produce any exports, as this would pollute the .d.ts file
  22184. * and also violate the point above.
  22185. */
  22186. TypeCheckCompiler.prototype.compileComponent = function (componentId, component, template, usedPipes, externalReferenceVars, ctx) {
  22187. var _this = this;
  22188. var pipes = new Map();
  22189. usedPipes.forEach(function (p) { return pipes.set(p.name, p.type.reference); });
  22190. var embeddedViewCount = 0;
  22191. var viewBuilderFactory = function (parent, guards) {
  22192. var embeddedViewIndex = embeddedViewCount++;
  22193. return new ViewBuilder(_this.options, _this.reflector, externalReferenceVars, parent, component.type.reference, component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
  22194. };
  22195. var visitor = viewBuilderFactory(null, []);
  22196. visitor.visitAll([], template);
  22197. return visitor.build(componentId);
  22198. };
  22199. return TypeCheckCompiler;
  22200. }());
  22201. var DYNAMIC_VAR_NAME = '_any';
  22202. var TypeCheckLocalResolver = /** @class */ (function () {
  22203. function TypeCheckLocalResolver() {
  22204. }
  22205. TypeCheckLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  22206. TypeCheckLocalResolver.prototype.getLocal = function (name) {
  22207. if (name === EventHandlerVars.event.name) {
  22208. // References to the event should not be type-checked.
  22209. // TODO(chuckj): determine a better type for the event.
  22210. return variable(DYNAMIC_VAR_NAME);
  22211. }
  22212. return null;
  22213. };
  22214. return TypeCheckLocalResolver;
  22215. }());
  22216. var defaultResolver = new TypeCheckLocalResolver();
  22217. var ViewBuilder = /** @class */ (function () {
  22218. function ViewBuilder(options, reflector, externalReferenceVars, parent, component, isHostComponent, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory) {
  22219. this.options = options;
  22220. this.reflector = reflector;
  22221. this.externalReferenceVars = externalReferenceVars;
  22222. this.parent = parent;
  22223. this.component = component;
  22224. this.isHostComponent = isHostComponent;
  22225. this.embeddedViewIndex = embeddedViewIndex;
  22226. this.pipes = pipes;
  22227. this.guards = guards;
  22228. this.ctx = ctx;
  22229. this.viewBuilderFactory = viewBuilderFactory;
  22230. this.refOutputVars = new Map();
  22231. this.variables = [];
  22232. this.children = [];
  22233. this.updates = [];
  22234. this.actions = [];
  22235. }
  22236. ViewBuilder.prototype.getOutputVar = function (type) {
  22237. var varName;
  22238. if (type === this.component && this.isHostComponent) {
  22239. varName = DYNAMIC_VAR_NAME;
  22240. }
  22241. else if (type instanceof StaticSymbol) {
  22242. varName = this.externalReferenceVars.get(type);
  22243. }
  22244. else {
  22245. varName = DYNAMIC_VAR_NAME;
  22246. }
  22247. if (!varName) {
  22248. throw new Error("Illegal State: referring to a type without a variable " + JSON.stringify(type));
  22249. }
  22250. return varName;
  22251. };
  22252. ViewBuilder.prototype.getTypeGuardExpressions = function (ast) {
  22253. var e_1, _a, e_2, _b;
  22254. var result = __spread(this.guards);
  22255. try {
  22256. for (var _c = __values(ast.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
  22257. var directive = _d.value;
  22258. try {
  22259. for (var _e = __values(directive.inputs), _f = _e.next(); !_f.done; _f = _e.next()) {
  22260. var input = _f.value;
  22261. var guard = directive.directive.guards[input.directiveName];
  22262. if (guard) {
  22263. var useIf = guard === 'UseIf';
  22264. result.push({
  22265. guard: guard,
  22266. useIf: useIf,
  22267. expression: { context: this.component, value: input.value }
  22268. });
  22269. }
  22270. }
  22271. }
  22272. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  22273. finally {
  22274. try {
  22275. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  22276. }
  22277. finally { if (e_2) throw e_2.error; }
  22278. }
  22279. }
  22280. }
  22281. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  22282. finally {
  22283. try {
  22284. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  22285. }
  22286. finally { if (e_1) throw e_1.error; }
  22287. }
  22288. return result;
  22289. };
  22290. ViewBuilder.prototype.visitAll = function (variables, astNodes) {
  22291. this.variables = variables;
  22292. templateVisitAll(this, astNodes);
  22293. };
  22294. ViewBuilder.prototype.build = function (componentId, targetStatements) {
  22295. var _this = this;
  22296. var e_3, _a;
  22297. if (targetStatements === void 0) { targetStatements = []; }
  22298. this.children.forEach(function (child) { return child.build(componentId, targetStatements); });
  22299. var viewStmts = [variable(DYNAMIC_VAR_NAME).set(NULL_EXPR).toDeclStmt(DYNAMIC_TYPE)];
  22300. var bindingCount = 0;
  22301. this.updates.forEach(function (expression) {
  22302. var _a = _this.preprocessUpdateExpression(expression), sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  22303. var bindingId = "" + bindingCount++;
  22304. var nameResolver = context === _this.component ? _this : defaultResolver;
  22305. var _b = convertPropertyBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
  22306. stmts.push(new ExpressionStatement(currValExpr));
  22307. viewStmts.push.apply(viewStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
  22308. });
  22309. this.actions.forEach(function (_a) {
  22310. var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  22311. var bindingId = "" + bindingCount++;
  22312. var nameResolver = context === _this.component ? _this : defaultResolver;
  22313. var stmts = convertActionBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId).stmts;
  22314. viewStmts.push.apply(viewStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
  22315. });
  22316. if (this.guards.length) {
  22317. var guardExpression = undefined;
  22318. try {
  22319. for (var _b = __values(this.guards), _c = _b.next(); !_c.done; _c = _b.next()) {
  22320. var guard = _c.value;
  22321. var _d = this.preprocessUpdateExpression(guard.expression), context = _d.context, value = _d.value;
  22322. var bindingId = "" + bindingCount++;
  22323. var nameResolver = context === this.component ? this : defaultResolver;
  22324. // We only support support simple expressions and ignore others as they
  22325. // are unlikely to affect type narrowing.
  22326. var _e = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.TrySimple), stmts = _e.stmts, currValExpr = _e.currValExpr;
  22327. if (stmts.length == 0) {
  22328. var guardClause = guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
  22329. guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
  22330. }
  22331. }
  22332. }
  22333. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  22334. finally {
  22335. try {
  22336. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  22337. }
  22338. finally { if (e_3) throw e_3.error; }
  22339. }
  22340. if (guardExpression) {
  22341. viewStmts = [new IfStmt(guardExpression, viewStmts)];
  22342. }
  22343. }
  22344. var viewName = "_View_" + componentId + "_" + this.embeddedViewIndex;
  22345. var viewFactory = new DeclareFunctionStmt(viewName, [], viewStmts);
  22346. targetStatements.push(viewFactory);
  22347. return targetStatements;
  22348. };
  22349. ViewBuilder.prototype.visitBoundText = function (ast, context) {
  22350. var _this = this;
  22351. var astWithSource = ast.value;
  22352. var inter = astWithSource.ast;
  22353. inter.expressions.forEach(function (expr) {
  22354. return _this.updates.push({ context: _this.component, value: expr, sourceSpan: ast.sourceSpan });
  22355. });
  22356. };
  22357. ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
  22358. this.visitElementOrTemplate(ast);
  22359. // Note: The old view compiler used to use an `any` type
  22360. // for the context in any embedded view.
  22361. // We keep this behaivor behind a flag for now.
  22362. if (this.options.fullTemplateTypeCheck) {
  22363. // Find any applicable type guards. For example, NgIf has a type guard on ngIf
  22364. // (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
  22365. // stamped out if ngIf is truthy so any bindings in the template can assume that,
  22366. // if a nullable type is used for ngIf, that expression is not null or undefined.
  22367. var guards = this.getTypeGuardExpressions(ast);
  22368. var childVisitor = this.viewBuilderFactory(this, guards);
  22369. this.children.push(childVisitor);
  22370. childVisitor.visitAll(ast.variables, ast.children);
  22371. }
  22372. };
  22373. ViewBuilder.prototype.visitElement = function (ast, context) {
  22374. var _this = this;
  22375. this.visitElementOrTemplate(ast);
  22376. ast.inputs.forEach(function (inputAst) {
  22377. _this.updates.push({ context: _this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan });
  22378. });
  22379. templateVisitAll(this, ast.children);
  22380. };
  22381. ViewBuilder.prototype.visitElementOrTemplate = function (ast) {
  22382. var _this = this;
  22383. ast.directives.forEach(function (dirAst) { _this.visitDirective(dirAst); });
  22384. ast.references.forEach(function (ref) {
  22385. var outputVarType = null;
  22386. // Note: The old view compiler used to use an `any` type
  22387. // for directives exposed via `exportAs`.
  22388. // We keep this behaivor behind a flag for now.
  22389. if (ref.value && ref.value.identifier && _this.options.fullTemplateTypeCheck) {
  22390. outputVarType = ref.value.identifier.reference;
  22391. }
  22392. else {
  22393. outputVarType = BuiltinTypeName.Dynamic;
  22394. }
  22395. _this.refOutputVars.set(ref.name, outputVarType);
  22396. });
  22397. ast.outputs.forEach(function (outputAst) {
  22398. _this.actions.push({ context: _this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan });
  22399. });
  22400. };
  22401. ViewBuilder.prototype.visitDirective = function (dirAst) {
  22402. var _this = this;
  22403. var dirType = dirAst.directive.type.reference;
  22404. dirAst.inputs.forEach(function (input) { return _this.updates.push({ context: _this.component, value: input.value, sourceSpan: input.sourceSpan }); });
  22405. // Note: The old view compiler used to use an `any` type
  22406. // for expressions in host properties / events.
  22407. // We keep this behaivor behind a flag for now.
  22408. if (this.options.fullTemplateTypeCheck) {
  22409. dirAst.hostProperties.forEach(function (inputAst) { return _this.updates.push({ context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan }); });
  22410. dirAst.hostEvents.forEach(function (hostEventAst) { return _this.actions.push({
  22411. context: dirType,
  22412. value: hostEventAst.handler,
  22413. sourceSpan: hostEventAst.sourceSpan
  22414. }); });
  22415. }
  22416. };
  22417. ViewBuilder.prototype.notifyImplicitReceiverUse = function () { };
  22418. ViewBuilder.prototype.getLocal = function (name) {
  22419. if (name == EventHandlerVars.event.name) {
  22420. return variable(this.getOutputVar(BuiltinTypeName.Dynamic));
  22421. }
  22422. for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent) {
  22423. var outputVarType = void 0;
  22424. // check references
  22425. outputVarType = currBuilder.refOutputVars.get(name);
  22426. if (outputVarType == null) {
  22427. // check variables
  22428. var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
  22429. if (varAst) {
  22430. outputVarType = BuiltinTypeName.Dynamic;
  22431. }
  22432. }
  22433. if (outputVarType != null) {
  22434. return variable(this.getOutputVar(outputVarType));
  22435. }
  22436. }
  22437. return null;
  22438. };
  22439. ViewBuilder.prototype.pipeOutputVar = function (name) {
  22440. var pipe = this.pipes.get(name);
  22441. if (!pipe) {
  22442. throw new Error("Illegal State: Could not find pipe " + name + " in template of " + this.component);
  22443. }
  22444. return this.getOutputVar(pipe);
  22445. };
  22446. ViewBuilder.prototype.preprocessUpdateExpression = function (expression) {
  22447. var _this = this;
  22448. return {
  22449. sourceSpan: expression.sourceSpan,
  22450. context: expression.context,
  22451. value: convertPropertyBindingBuiltins({
  22452. createLiteralArrayConverter: function (argCount) { return function (args) {
  22453. var arr = literalArr(args);
  22454. // Note: The old view compiler used to use an `any` type
  22455. // for arrays.
  22456. return _this.options.fullTemplateTypeCheck ? arr : arr.cast(DYNAMIC_TYPE);
  22457. }; },
  22458. createLiteralMapConverter: function (keys) { return function (values) {
  22459. var entries = keys.map(function (k, i) { return ({
  22460. key: k.key,
  22461. value: values[i],
  22462. quoted: k.quoted,
  22463. }); });
  22464. var map = literalMap(entries);
  22465. // Note: The old view compiler used to use an `any` type
  22466. // for maps.
  22467. return _this.options.fullTemplateTypeCheck ? map : map.cast(DYNAMIC_TYPE);
  22468. }; },
  22469. createPipeConverter: function (name, argCount) { return function (args) {
  22470. // Note: The old view compiler used to use an `any` type
  22471. // for pipes.
  22472. var pipeExpr = _this.options.fullTemplateTypeCheck ?
  22473. variable(_this.pipeOutputVar(name)) :
  22474. variable(_this.getOutputVar(BuiltinTypeName.Dynamic));
  22475. return pipeExpr.callMethod('transform', args);
  22476. }; },
  22477. }, expression.value)
  22478. };
  22479. };
  22480. ViewBuilder.prototype.visitNgContent = function (ast, context) { };
  22481. ViewBuilder.prototype.visitText = function (ast, context) { };
  22482. ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
  22483. ViewBuilder.prototype.visitReference = function (ast, context) { };
  22484. ViewBuilder.prototype.visitVariable = function (ast, context) { };
  22485. ViewBuilder.prototype.visitEvent = function (ast, context) { };
  22486. ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
  22487. ViewBuilder.prototype.visitAttr = function (ast, context) { };
  22488. return ViewBuilder;
  22489. }());
  22490. /**
  22491. * @license
  22492. * Copyright Google Inc. All Rights Reserved.
  22493. *
  22494. * Use of this source code is governed by an MIT-style license that can be
  22495. * found in the LICENSE file at https://angular.io/license
  22496. */
  22497. var CLASS_ATTR$1 = 'class';
  22498. var STYLE_ATTR = 'style';
  22499. var IMPLICIT_TEMPLATE_VAR = '\$implicit';
  22500. var ViewCompileResult = /** @class */ (function () {
  22501. function ViewCompileResult(viewClassVar, rendererTypeVar) {
  22502. this.viewClassVar = viewClassVar;
  22503. this.rendererTypeVar = rendererTypeVar;
  22504. }
  22505. return ViewCompileResult;
  22506. }());
  22507. var ViewCompiler = /** @class */ (function () {
  22508. function ViewCompiler(_reflector) {
  22509. this._reflector = _reflector;
  22510. }
  22511. ViewCompiler.prototype.compileComponent = function (outputCtx, component, template, styles, usedPipes) {
  22512. var _this = this;
  22513. var _a;
  22514. var embeddedViewCount = 0;
  22515. var staticQueryIds = findStaticQueryIds(template);
  22516. var renderComponentVarName = undefined;
  22517. if (!component.isHost) {
  22518. var template_1 = component.template;
  22519. var customRenderData = [];
  22520. if (template_1.animations && template_1.animations.length) {
  22521. customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(outputCtx, template_1.animations), true));
  22522. }
  22523. var renderComponentVar = variable(rendererTypeName(component.type.reference));
  22524. renderComponentVarName = renderComponentVar.name;
  22525. outputCtx.statements.push(renderComponentVar
  22526. .set(importExpr(Identifiers.createRendererType2).callFn([new LiteralMapExpr([
  22527. new LiteralMapEntry('encapsulation', literal(template_1.encapsulation), false),
  22528. new LiteralMapEntry('styles', styles, false),
  22529. new LiteralMapEntry('data', new LiteralMapExpr(customRenderData), false)
  22530. ])]))
  22531. .toDeclStmt(importType(Identifiers.RendererType2), [StmtModifier.Final, StmtModifier.Exported]));
  22532. }
  22533. var viewBuilderFactory = function (parent) {
  22534. var embeddedViewIndex = embeddedViewCount++;
  22535. return new ViewBuilder$1(_this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory);
  22536. };
  22537. var visitor = viewBuilderFactory(null);
  22538. visitor.visitAll([], template);
  22539. (_a = outputCtx.statements).push.apply(_a, __spread(visitor.build()));
  22540. return new ViewCompileResult(visitor.viewName, renderComponentVarName);
  22541. };
  22542. return ViewCompiler;
  22543. }());
  22544. var LOG_VAR$1 = variable('_l');
  22545. var VIEW_VAR = variable('_v');
  22546. var CHECK_VAR = variable('_ck');
  22547. var COMP_VAR = variable('_co');
  22548. var EVENT_NAME_VAR = variable('en');
  22549. var ALLOW_DEFAULT_VAR = variable("ad");
  22550. var ViewBuilder$1 = /** @class */ (function () {
  22551. function ViewBuilder(reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory) {
  22552. this.reflector = reflector;
  22553. this.outputCtx = outputCtx;
  22554. this.parent = parent;
  22555. this.component = component;
  22556. this.embeddedViewIndex = embeddedViewIndex;
  22557. this.usedPipes = usedPipes;
  22558. this.staticQueryIds = staticQueryIds;
  22559. this.viewBuilderFactory = viewBuilderFactory;
  22560. this.nodes = [];
  22561. this.purePipeNodeIndices = Object.create(null);
  22562. // Need Object.create so that we don't have builtin values...
  22563. this.refNodeIndices = Object.create(null);
  22564. this.variables = [];
  22565. this.children = [];
  22566. // TODO(tbosch): The old view compiler used to use an `any` type
  22567. // for the context in any embedded view. We keep this behaivor for now
  22568. // to be able to introduce the new view compiler without too many errors.
  22569. this.compType = this.embeddedViewIndex > 0 ?
  22570. DYNAMIC_TYPE :
  22571. expressionType(outputCtx.importExpr(this.component.type.reference));
  22572. this.viewName = viewClassName(this.component.type.reference, this.embeddedViewIndex);
  22573. }
  22574. ViewBuilder.prototype.visitAll = function (variables, astNodes) {
  22575. var _this = this;
  22576. this.variables = variables;
  22577. // create the pipes for the pure pipes immediately, so that we know their indices.
  22578. if (!this.parent) {
  22579. this.usedPipes.forEach(function (pipe) {
  22580. if (pipe.pure) {
  22581. _this.purePipeNodeIndices[pipe.name] = _this._createPipe(null, pipe);
  22582. }
  22583. });
  22584. }
  22585. if (!this.parent) {
  22586. var queryIds_1 = staticViewQueryIds(this.staticQueryIds);
  22587. this.component.viewQueries.forEach(function (query, queryIndex) {
  22588. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  22589. var queryId = queryIndex + 1;
  22590. var bindingType = query.first ? 0 /* First */ : 1 /* All */;
  22591. var flags = 134217728 /* TypeViewQuery */ | calcStaticDynamicQueryFlags(queryIds_1, queryId, query);
  22592. _this.nodes.push(function () { return ({
  22593. sourceSpan: null,
  22594. nodeFlags: flags,
  22595. nodeDef: importExpr(Identifiers.queryDef).callFn([
  22596. literal(flags), literal(queryId),
  22597. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  22598. ])
  22599. }); });
  22600. });
  22601. }
  22602. templateVisitAll(this, astNodes);
  22603. if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
  22604. // if the view is an embedded view, then we need to add an additional root node in some cases
  22605. this.nodes.push(function () { return ({
  22606. sourceSpan: null,
  22607. nodeFlags: 1 /* TypeElement */,
  22608. nodeDef: importExpr(Identifiers.anchorDef).callFn([
  22609. literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
  22610. ])
  22611. }); });
  22612. }
  22613. };
  22614. ViewBuilder.prototype.build = function (targetStatements) {
  22615. if (targetStatements === void 0) { targetStatements = []; }
  22616. this.children.forEach(function (child) { return child.build(targetStatements); });
  22617. var _a = this._createNodeExpressions(), updateRendererStmts = _a.updateRendererStmts, updateDirectivesStmts = _a.updateDirectivesStmts, nodeDefExprs = _a.nodeDefExprs;
  22618. var updateRendererFn = this._createUpdateFn(updateRendererStmts);
  22619. var updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
  22620. var viewFlags = 0 /* None */;
  22621. if (!this.parent && this.component.changeDetection === ChangeDetectionStrategy.OnPush) {
  22622. viewFlags |= 2 /* OnPush */;
  22623. }
  22624. var viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(LOG_VAR$1.name)], [new ReturnStatement(importExpr(Identifiers.viewDef).callFn([
  22625. literal(viewFlags),
  22626. literalArr(nodeDefExprs),
  22627. updateDirectivesFn,
  22628. updateRendererFn,
  22629. ]))], importType(Identifiers.ViewDefinition), this.embeddedViewIndex === 0 ? [StmtModifier.Exported] : []);
  22630. targetStatements.push(viewFactory);
  22631. return targetStatements;
  22632. };
  22633. ViewBuilder.prototype._createUpdateFn = function (updateStmts) {
  22634. var updateFn;
  22635. if (updateStmts.length > 0) {
  22636. var preStmts = [];
  22637. if (!this.component.isHost && findReadVarNames(updateStmts).has(COMP_VAR.name)) {
  22638. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  22639. }
  22640. updateFn = fn([
  22641. new FnParam(CHECK_VAR.name, INFERRED_TYPE),
  22642. new FnParam(VIEW_VAR.name, INFERRED_TYPE)
  22643. ], __spread(preStmts, updateStmts), INFERRED_TYPE);
  22644. }
  22645. else {
  22646. updateFn = NULL_EXPR;
  22647. }
  22648. return updateFn;
  22649. };
  22650. ViewBuilder.prototype.visitNgContent = function (ast, context) {
  22651. // ngContentDef(ngContentIndex: number, index: number): NodeDef;
  22652. this.nodes.push(function () { return ({
  22653. sourceSpan: ast.sourceSpan,
  22654. nodeFlags: 8 /* TypeNgContent */,
  22655. nodeDef: importExpr(Identifiers.ngContentDef).callFn([
  22656. literal(ast.ngContentIndex), literal(ast.index)
  22657. ])
  22658. }); });
  22659. };
  22660. ViewBuilder.prototype.visitText = function (ast, context) {
  22661. // Static text nodes have no check function
  22662. var checkIndex = -1;
  22663. this.nodes.push(function () { return ({
  22664. sourceSpan: ast.sourceSpan,
  22665. nodeFlags: 2 /* TypeText */,
  22666. nodeDef: importExpr(Identifiers.textDef).callFn([
  22667. literal(checkIndex),
  22668. literal(ast.ngContentIndex),
  22669. literalArr([literal(ast.value)]),
  22670. ])
  22671. }); });
  22672. };
  22673. ViewBuilder.prototype.visitBoundText = function (ast, context) {
  22674. var _this = this;
  22675. var nodeIndex = this.nodes.length;
  22676. // reserve the space in the nodeDefs array
  22677. this.nodes.push(null);
  22678. var astWithSource = ast.value;
  22679. var inter = astWithSource.ast;
  22680. var updateRendererExpressions = inter.expressions.map(function (expr, bindingIndex) { return _this._preprocessUpdateExpression({ nodeIndex: nodeIndex, bindingIndex: bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }); });
  22681. // Check index is the same as the node index during compilation
  22682. // They might only differ at runtime
  22683. var checkIndex = nodeIndex;
  22684. this.nodes[nodeIndex] = function () { return ({
  22685. sourceSpan: ast.sourceSpan,
  22686. nodeFlags: 2 /* TypeText */,
  22687. nodeDef: importExpr(Identifiers.textDef).callFn([
  22688. literal(checkIndex),
  22689. literal(ast.ngContentIndex),
  22690. literalArr(inter.strings.map(function (s) { return literal(s); })),
  22691. ]),
  22692. updateRenderer: updateRendererExpressions
  22693. }); };
  22694. };
  22695. ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
  22696. var _this = this;
  22697. var nodeIndex = this.nodes.length;
  22698. // reserve the space in the nodeDefs array
  22699. this.nodes.push(null);
  22700. var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, queryMatchesExpr = _a.queryMatchesExpr, hostEvents = _a.hostEvents;
  22701. var childVisitor = this.viewBuilderFactory(this);
  22702. this.children.push(childVisitor);
  22703. childVisitor.visitAll(ast.variables, ast.children);
  22704. var childCount = this.nodes.length - nodeIndex - 1;
  22705. // anchorDef(
  22706. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
  22707. // childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
  22708. // ViewDefinitionFactory): NodeDef;
  22709. this.nodes[nodeIndex] = function () { return ({
  22710. sourceSpan: ast.sourceSpan,
  22711. nodeFlags: 1 /* TypeElement */ | flags,
  22712. nodeDef: importExpr(Identifiers.anchorDef).callFn([
  22713. literal(flags),
  22714. queryMatchesExpr,
  22715. literal(ast.ngContentIndex),
  22716. literal(childCount),
  22717. _this._createElementHandleEventFn(nodeIndex, hostEvents),
  22718. variable(childVisitor.viewName),
  22719. ])
  22720. }); };
  22721. };
  22722. ViewBuilder.prototype.visitElement = function (ast, context) {
  22723. var _this = this;
  22724. var nodeIndex = this.nodes.length;
  22725. // reserve the space in the nodeDefs array so we can add children
  22726. this.nodes.push(null);
  22727. // Using a null element name creates an anchor.
  22728. var elName = isNgContainer(ast.name) ? null : ast.name;
  22729. var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, usedEvents = _a.usedEvents, queryMatchesExpr = _a.queryMatchesExpr, dirHostBindings = _a.hostBindings, hostEvents = _a.hostEvents;
  22730. var inputDefs = [];
  22731. var updateRendererExpressions = [];
  22732. var outputDefs = [];
  22733. if (elName) {
  22734. var hostBindings = ast.inputs
  22735. .map(function (inputAst) { return ({
  22736. context: COMP_VAR,
  22737. inputAst: inputAst,
  22738. dirAst: null,
  22739. }); })
  22740. .concat(dirHostBindings);
  22741. if (hostBindings.length) {
  22742. updateRendererExpressions =
  22743. hostBindings.map(function (hostBinding, bindingIndex) { return _this._preprocessUpdateExpression({
  22744. context: hostBinding.context,
  22745. nodeIndex: nodeIndex,
  22746. bindingIndex: bindingIndex,
  22747. sourceSpan: hostBinding.inputAst.sourceSpan,
  22748. value: hostBinding.inputAst.value
  22749. }); });
  22750. inputDefs = hostBindings.map(function (hostBinding) { return elementBindingDef(hostBinding.inputAst, hostBinding.dirAst); });
  22751. }
  22752. outputDefs = usedEvents.map(function (_a) {
  22753. var _b = __read(_a, 2), target = _b[0], eventName = _b[1];
  22754. return literalArr([literal(target), literal(eventName)]);
  22755. });
  22756. }
  22757. templateVisitAll(this, ast.children);
  22758. var childCount = this.nodes.length - nodeIndex - 1;
  22759. var compAst = ast.directives.find(function (dirAst) { return dirAst.directive.isComponent; });
  22760. var compRendererType = NULL_EXPR;
  22761. var compView = NULL_EXPR;
  22762. if (compAst) {
  22763. compView = this.outputCtx.importExpr(compAst.directive.componentViewType);
  22764. compRendererType = this.outputCtx.importExpr(compAst.directive.rendererType);
  22765. }
  22766. // Check index is the same as the node index during compilation
  22767. // They might only differ at runtime
  22768. var checkIndex = nodeIndex;
  22769. this.nodes[nodeIndex] = function () { return ({
  22770. sourceSpan: ast.sourceSpan,
  22771. nodeFlags: 1 /* TypeElement */ | flags,
  22772. nodeDef: importExpr(Identifiers.elementDef).callFn([
  22773. literal(checkIndex),
  22774. literal(flags),
  22775. queryMatchesExpr,
  22776. literal(ast.ngContentIndex),
  22777. literal(childCount),
  22778. literal(elName),
  22779. elName ? fixedAttrsDef(ast) : NULL_EXPR,
  22780. inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
  22781. outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
  22782. _this._createElementHandleEventFn(nodeIndex, hostEvents),
  22783. compView,
  22784. compRendererType,
  22785. ]),
  22786. updateRenderer: updateRendererExpressions
  22787. }); };
  22788. };
  22789. ViewBuilder.prototype._visitElementOrTemplate = function (nodeIndex, ast) {
  22790. var _this = this;
  22791. var flags = 0 /* None */;
  22792. if (ast.hasViewContainer) {
  22793. flags |= 16777216 /* EmbeddedViews */;
  22794. }
  22795. var usedEvents = new Map();
  22796. ast.outputs.forEach(function (event) {
  22797. var _a = elementEventNameAndTarget(event, null), name = _a.name, target = _a.target;
  22798. usedEvents.set(elementEventFullName(target, name), [target, name]);
  22799. });
  22800. ast.directives.forEach(function (dirAst) {
  22801. dirAst.hostEvents.forEach(function (event) {
  22802. var _a = elementEventNameAndTarget(event, dirAst), name = _a.name, target = _a.target;
  22803. usedEvents.set(elementEventFullName(target, name), [target, name]);
  22804. });
  22805. });
  22806. var hostBindings = [];
  22807. var hostEvents = [];
  22808. this._visitComponentFactoryResolverProvider(ast.directives);
  22809. ast.providers.forEach(function (providerAst, providerIndex) {
  22810. var dirAst = undefined;
  22811. var dirIndex = undefined;
  22812. ast.directives.forEach(function (localDirAst, i) {
  22813. if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
  22814. dirAst = localDirAst;
  22815. dirIndex = i;
  22816. }
  22817. });
  22818. if (dirAst) {
  22819. var _a = _this._visitDirective(providerAst, dirAst, dirIndex, nodeIndex, ast.references, ast.queryMatches, usedEvents, _this.staticQueryIds.get(ast)), dirHostBindings = _a.hostBindings, dirHostEvents = _a.hostEvents;
  22820. hostBindings.push.apply(hostBindings, __spread(dirHostBindings));
  22821. hostEvents.push.apply(hostEvents, __spread(dirHostEvents));
  22822. }
  22823. else {
  22824. _this._visitProvider(providerAst, ast.queryMatches);
  22825. }
  22826. });
  22827. var queryMatchExprs = [];
  22828. ast.queryMatches.forEach(function (match) {
  22829. var valueType = undefined;
  22830. if (tokenReference(match.value) ===
  22831. _this.reflector.resolveExternalReference(Identifiers.ElementRef)) {
  22832. valueType = 0 /* ElementRef */;
  22833. }
  22834. else if (tokenReference(match.value) ===
  22835. _this.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  22836. valueType = 3 /* ViewContainerRef */;
  22837. }
  22838. else if (tokenReference(match.value) ===
  22839. _this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  22840. valueType = 2 /* TemplateRef */;
  22841. }
  22842. if (valueType != null) {
  22843. queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
  22844. }
  22845. });
  22846. ast.references.forEach(function (ref) {
  22847. var valueType = undefined;
  22848. if (!ref.value) {
  22849. valueType = 1 /* RenderElement */;
  22850. }
  22851. else if (tokenReference(ref.value) ===
  22852. _this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  22853. valueType = 2 /* TemplateRef */;
  22854. }
  22855. if (valueType != null) {
  22856. _this.refNodeIndices[ref.name] = nodeIndex;
  22857. queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
  22858. }
  22859. });
  22860. ast.outputs.forEach(function (outputAst) {
  22861. hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: null });
  22862. });
  22863. return {
  22864. flags: flags,
  22865. usedEvents: Array.from(usedEvents.values()),
  22866. queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  22867. hostBindings: hostBindings,
  22868. hostEvents: hostEvents
  22869. };
  22870. };
  22871. ViewBuilder.prototype._visitDirective = function (providerAst, dirAst, directiveIndex, elementNodeIndex, refs, queryMatches, usedEvents, queryIds) {
  22872. var _this = this;
  22873. var nodeIndex = this.nodes.length;
  22874. // reserve the space in the nodeDefs array so we can add children
  22875. this.nodes.push(null);
  22876. dirAst.directive.queries.forEach(function (query, queryIndex) {
  22877. var queryId = dirAst.contentQueryStartId + queryIndex;
  22878. var flags = 67108864 /* TypeContentQuery */ | calcStaticDynamicQueryFlags(queryIds, queryId, query);
  22879. var bindingType = query.first ? 0 /* First */ : 1 /* All */;
  22880. _this.nodes.push(function () { return ({
  22881. sourceSpan: dirAst.sourceSpan,
  22882. nodeFlags: flags,
  22883. nodeDef: importExpr(Identifiers.queryDef).callFn([
  22884. literal(flags), literal(queryId),
  22885. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  22886. ]),
  22887. }); });
  22888. });
  22889. // Note: the operation below might also create new nodeDefs,
  22890. // but we don't want them to be a child of a directive,
  22891. // as they might be a provider/pipe on their own.
  22892. // I.e. we only allow queries as children of directives nodes.
  22893. var childCount = this.nodes.length - nodeIndex - 1;
  22894. var _a = this._visitProviderOrDirective(providerAst, queryMatches), flags = _a.flags, queryMatchExprs = _a.queryMatchExprs, providerExpr = _a.providerExpr, depsExpr = _a.depsExpr;
  22895. refs.forEach(function (ref) {
  22896. if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
  22897. _this.refNodeIndices[ref.name] = nodeIndex;
  22898. queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
  22899. }
  22900. });
  22901. if (dirAst.directive.isComponent) {
  22902. flags |= 32768 /* Component */;
  22903. }
  22904. var inputDefs = dirAst.inputs.map(function (inputAst, inputIndex) {
  22905. var mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
  22906. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  22907. return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
  22908. });
  22909. var outputDefs = [];
  22910. var dirMeta = dirAst.directive;
  22911. Object.keys(dirMeta.outputs).forEach(function (propName) {
  22912. var eventName = dirMeta.outputs[propName];
  22913. if (usedEvents.has(eventName)) {
  22914. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  22915. outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
  22916. }
  22917. });
  22918. var updateDirectiveExpressions = [];
  22919. if (dirAst.inputs.length || (flags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0) {
  22920. updateDirectiveExpressions =
  22921. dirAst.inputs.map(function (input, bindingIndex) { return _this._preprocessUpdateExpression({
  22922. nodeIndex: nodeIndex,
  22923. bindingIndex: bindingIndex,
  22924. sourceSpan: input.sourceSpan,
  22925. context: COMP_VAR,
  22926. value: input.value
  22927. }); });
  22928. }
  22929. var dirContextExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  22930. var hostBindings = dirAst.hostProperties.map(function (inputAst) { return ({
  22931. context: dirContextExpr,
  22932. dirAst: dirAst,
  22933. inputAst: inputAst,
  22934. }); });
  22935. var hostEvents = dirAst.hostEvents.map(function (hostEventAst) { return ({
  22936. context: dirContextExpr,
  22937. eventAst: hostEventAst, dirAst: dirAst,
  22938. }); });
  22939. // Check index is the same as the node index during compilation
  22940. // They might only differ at runtime
  22941. var checkIndex = nodeIndex;
  22942. this.nodes[nodeIndex] = function () { return ({
  22943. sourceSpan: dirAst.sourceSpan,
  22944. nodeFlags: 16384 /* TypeDirective */ | flags,
  22945. nodeDef: importExpr(Identifiers.directiveDef).callFn([
  22946. literal(checkIndex),
  22947. literal(flags),
  22948. queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  22949. literal(childCount),
  22950. providerExpr,
  22951. depsExpr,
  22952. inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
  22953. outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR,
  22954. ]),
  22955. updateDirectives: updateDirectiveExpressions,
  22956. directive: dirAst.directive.type,
  22957. }); };
  22958. return { hostBindings: hostBindings, hostEvents: hostEvents };
  22959. };
  22960. ViewBuilder.prototype._visitProvider = function (providerAst, queryMatches) {
  22961. this._addProviderNode(this._visitProviderOrDirective(providerAst, queryMatches));
  22962. };
  22963. ViewBuilder.prototype._visitComponentFactoryResolverProvider = function (directives) {
  22964. var componentDirMeta = directives.find(function (dirAst) { return dirAst.directive.isComponent; });
  22965. if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
  22966. var _a = componentFactoryResolverProviderDef(this.reflector, this.outputCtx, 8192 /* PrivateProvider */, componentDirMeta.directive.entryComponents), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
  22967. this._addProviderNode({
  22968. providerExpr: providerExpr,
  22969. depsExpr: depsExpr,
  22970. flags: flags,
  22971. tokenExpr: tokenExpr,
  22972. queryMatchExprs: [],
  22973. sourceSpan: componentDirMeta.sourceSpan
  22974. });
  22975. }
  22976. };
  22977. ViewBuilder.prototype._addProviderNode = function (data) {
  22978. var nodeIndex = this.nodes.length;
  22979. // providerDef(
  22980. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
  22981. // value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
  22982. this.nodes.push(function () { return ({
  22983. sourceSpan: data.sourceSpan,
  22984. nodeFlags: data.flags,
  22985. nodeDef: importExpr(Identifiers.providerDef).callFn([
  22986. literal(data.flags),
  22987. data.queryMatchExprs.length ? literalArr(data.queryMatchExprs) : NULL_EXPR,
  22988. data.tokenExpr, data.providerExpr, data.depsExpr
  22989. ])
  22990. }); });
  22991. };
  22992. ViewBuilder.prototype._visitProviderOrDirective = function (providerAst, queryMatches) {
  22993. var flags = 0 /* None */;
  22994. var queryMatchExprs = [];
  22995. queryMatches.forEach(function (match) {
  22996. if (tokenReference(match.value) === tokenReference(providerAst.token)) {
  22997. queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
  22998. }
  22999. });
  23000. var _a = providerDef(this.outputCtx, providerAst), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, providerFlags = _a.flags, tokenExpr = _a.tokenExpr;
  23001. return {
  23002. flags: flags | providerFlags,
  23003. queryMatchExprs: queryMatchExprs,
  23004. providerExpr: providerExpr,
  23005. depsExpr: depsExpr,
  23006. tokenExpr: tokenExpr,
  23007. sourceSpan: providerAst.sourceSpan
  23008. };
  23009. };
  23010. ViewBuilder.prototype.getLocal = function (name) {
  23011. if (name == EventHandlerVars.event.name) {
  23012. return EventHandlerVars.event;
  23013. }
  23014. var currViewExpr = VIEW_VAR;
  23015. for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
  23016. currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
  23017. // check references
  23018. var refNodeIndex = currBuilder.refNodeIndices[name];
  23019. if (refNodeIndex != null) {
  23020. return importExpr(Identifiers.nodeValue).callFn([currViewExpr, literal(refNodeIndex)]);
  23021. }
  23022. // check variables
  23023. var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
  23024. if (varAst) {
  23025. var varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
  23026. return currViewExpr.prop('context').prop(varValue);
  23027. }
  23028. }
  23029. return null;
  23030. };
  23031. ViewBuilder.prototype.notifyImplicitReceiverUse = function () {
  23032. // Not needed in View Engine as View Engine walks through the generated
  23033. // expressions to figure out if the implicit receiver is used and needs
  23034. // to be generated as part of the pre-update statements.
  23035. };
  23036. ViewBuilder.prototype._createLiteralArrayConverter = function (sourceSpan, argCount) {
  23037. if (argCount === 0) {
  23038. var valueExpr_1 = importExpr(Identifiers.EMPTY_ARRAY);
  23039. return function () { return valueExpr_1; };
  23040. }
  23041. var checkIndex = this.nodes.length;
  23042. this.nodes.push(function () { return ({
  23043. sourceSpan: sourceSpan,
  23044. nodeFlags: 32 /* TypePureArray */,
  23045. nodeDef: importExpr(Identifiers.pureArrayDef).callFn([
  23046. literal(checkIndex),
  23047. literal(argCount),
  23048. ])
  23049. }); });
  23050. return function (args) { return callCheckStmt(checkIndex, args); };
  23051. };
  23052. ViewBuilder.prototype._createLiteralMapConverter = function (sourceSpan, keys) {
  23053. if (keys.length === 0) {
  23054. var valueExpr_2 = importExpr(Identifiers.EMPTY_MAP);
  23055. return function () { return valueExpr_2; };
  23056. }
  23057. var map = literalMap(keys.map(function (e, i) { return (__assign({}, e, { value: literal(i) })); }));
  23058. var checkIndex = this.nodes.length;
  23059. this.nodes.push(function () { return ({
  23060. sourceSpan: sourceSpan,
  23061. nodeFlags: 64 /* TypePureObject */,
  23062. nodeDef: importExpr(Identifiers.pureObjectDef).callFn([
  23063. literal(checkIndex),
  23064. map,
  23065. ])
  23066. }); });
  23067. return function (args) { return callCheckStmt(checkIndex, args); };
  23068. };
  23069. ViewBuilder.prototype._createPipeConverter = function (expression, name, argCount) {
  23070. var pipe = this.usedPipes.find(function (pipeSummary) { return pipeSummary.name === name; });
  23071. if (pipe.pure) {
  23072. var checkIndex_1 = this.nodes.length;
  23073. this.nodes.push(function () { return ({
  23074. sourceSpan: expression.sourceSpan,
  23075. nodeFlags: 128 /* TypePurePipe */,
  23076. nodeDef: importExpr(Identifiers.purePipeDef).callFn([
  23077. literal(checkIndex_1),
  23078. literal(argCount),
  23079. ])
  23080. }); });
  23081. // find underlying pipe in the component view
  23082. var compViewExpr = VIEW_VAR;
  23083. var compBuilder = this;
  23084. while (compBuilder.parent) {
  23085. compBuilder = compBuilder.parent;
  23086. compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
  23087. }
  23088. var pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
  23089. var pipeValueExpr_1 = importExpr(Identifiers.nodeValue).callFn([compViewExpr, literal(pipeNodeIndex)]);
  23090. return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(checkIndex_1, [pipeValueExpr_1].concat(args))); };
  23091. }
  23092. else {
  23093. var nodeIndex = this._createPipe(expression.sourceSpan, pipe);
  23094. var nodeValueExpr_1 = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  23095. return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr_1.callMethod('transform', args)); };
  23096. }
  23097. };
  23098. ViewBuilder.prototype._createPipe = function (sourceSpan, pipe) {
  23099. var _this = this;
  23100. var nodeIndex = this.nodes.length;
  23101. var flags = 0 /* None */;
  23102. pipe.type.lifecycleHooks.forEach(function (lifecycleHook) {
  23103. // for pipes, we only support ngOnDestroy
  23104. if (lifecycleHook === LifecycleHooks.OnDestroy) {
  23105. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  23106. }
  23107. });
  23108. var depExprs = pipe.type.diDeps.map(function (diDep) { return depDef(_this.outputCtx, diDep); });
  23109. // function pipeDef(
  23110. // flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
  23111. this.nodes.push(function () { return ({
  23112. sourceSpan: sourceSpan,
  23113. nodeFlags: 16 /* TypePipe */,
  23114. nodeDef: importExpr(Identifiers.pipeDef).callFn([
  23115. literal(flags), _this.outputCtx.importExpr(pipe.type.reference), literalArr(depExprs)
  23116. ])
  23117. }); });
  23118. return nodeIndex;
  23119. };
  23120. /**
  23121. * For the AST in `UpdateExpression.value`:
  23122. * - create nodes for pipes, literal arrays and, literal maps,
  23123. * - update the AST to replace pipes, literal arrays and, literal maps with calls to check fn.
  23124. *
  23125. * WARNING: This might create new nodeDefs (for pipes and literal arrays and literal maps)!
  23126. */
  23127. ViewBuilder.prototype._preprocessUpdateExpression = function (expression) {
  23128. var _this = this;
  23129. return {
  23130. nodeIndex: expression.nodeIndex,
  23131. bindingIndex: expression.bindingIndex,
  23132. sourceSpan: expression.sourceSpan,
  23133. context: expression.context,
  23134. value: convertPropertyBindingBuiltins({
  23135. createLiteralArrayConverter: function (argCount) { return _this._createLiteralArrayConverter(expression.sourceSpan, argCount); },
  23136. createLiteralMapConverter: function (keys) {
  23137. return _this._createLiteralMapConverter(expression.sourceSpan, keys);
  23138. },
  23139. createPipeConverter: function (name, argCount) {
  23140. return _this._createPipeConverter(expression, name, argCount);
  23141. }
  23142. }, expression.value)
  23143. };
  23144. };
  23145. ViewBuilder.prototype._createNodeExpressions = function () {
  23146. var self = this;
  23147. var updateBindingCount = 0;
  23148. var updateRendererStmts = [];
  23149. var updateDirectivesStmts = [];
  23150. var nodeDefExprs = this.nodes.map(function (factory, nodeIndex) {
  23151. var _a = factory(), nodeDef = _a.nodeDef, nodeFlags = _a.nodeFlags, updateDirectives = _a.updateDirectives, updateRenderer = _a.updateRenderer, sourceSpan = _a.sourceSpan;
  23152. if (updateRenderer) {
  23153. updateRendererStmts.push.apply(updateRendererStmts, __spread(createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false)));
  23154. }
  23155. if (updateDirectives) {
  23156. updateDirectivesStmts.push.apply(updateDirectivesStmts, __spread(createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0)));
  23157. }
  23158. // We use a comma expression to call the log function before
  23159. // the nodeDef function, but still use the result of the nodeDef function
  23160. // as the value.
  23161. // Note: We only add the logger to elements / text nodes,
  23162. // so we don't generate too much code.
  23163. var logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
  23164. new CommaExpr([LOG_VAR$1.callFn([]).callFn([]), nodeDef]) :
  23165. nodeDef;
  23166. return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
  23167. });
  23168. return { updateRendererStmts: updateRendererStmts, updateDirectivesStmts: updateDirectivesStmts, nodeDefExprs: nodeDefExprs };
  23169. function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
  23170. var updateStmts = [];
  23171. var exprs = expressions.map(function (_a) {
  23172. var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  23173. var bindingId = "" + updateBindingCount++;
  23174. var nameResolver = context === COMP_VAR ? self : null;
  23175. var _b = convertPropertyBinding(nameResolver, context, value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
  23176. updateStmts.push.apply(updateStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
  23177. return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
  23178. });
  23179. if (expressions.length || allowEmptyExprs) {
  23180. updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
  23181. }
  23182. return updateStmts;
  23183. }
  23184. };
  23185. ViewBuilder.prototype._createElementHandleEventFn = function (nodeIndex, handlers) {
  23186. var _this = this;
  23187. var handleEventStmts = [];
  23188. var handleEventBindingCount = 0;
  23189. handlers.forEach(function (_a) {
  23190. var context = _a.context, eventAst = _a.eventAst, dirAst = _a.dirAst;
  23191. var bindingId = "" + handleEventBindingCount++;
  23192. var nameResolver = context === COMP_VAR ? _this : null;
  23193. var _b = convertActionBinding(nameResolver, context, eventAst.handler, bindingId), stmts = _b.stmts, allowDefault = _b.allowDefault;
  23194. var trueStmts = stmts;
  23195. if (allowDefault) {
  23196. trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
  23197. }
  23198. var _c = elementEventNameAndTarget(eventAst, dirAst), eventTarget = _c.target, eventName = _c.name;
  23199. var fullEventName = elementEventFullName(eventTarget, eventName);
  23200. handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
  23201. });
  23202. var handleEventFn;
  23203. if (handleEventStmts.length > 0) {
  23204. var preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
  23205. if (!this.component.isHost && findReadVarNames(handleEventStmts).has(COMP_VAR.name)) {
  23206. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  23207. }
  23208. handleEventFn = fn([
  23209. new FnParam(VIEW_VAR.name, INFERRED_TYPE),
  23210. new FnParam(EVENT_NAME_VAR.name, INFERRED_TYPE),
  23211. new FnParam(EventHandlerVars.event.name, INFERRED_TYPE)
  23212. ], __spread(preStmts, handleEventStmts, [new ReturnStatement(ALLOW_DEFAULT_VAR)]), INFERRED_TYPE);
  23213. }
  23214. else {
  23215. handleEventFn = NULL_EXPR;
  23216. }
  23217. return handleEventFn;
  23218. };
  23219. ViewBuilder.prototype.visitDirective = function (ast, context) { };
  23220. ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
  23221. ViewBuilder.prototype.visitReference = function (ast, context) { };
  23222. ViewBuilder.prototype.visitVariable = function (ast, context) { };
  23223. ViewBuilder.prototype.visitEvent = function (ast, context) { };
  23224. ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
  23225. ViewBuilder.prototype.visitAttr = function (ast, context) { };
  23226. return ViewBuilder;
  23227. }());
  23228. function needsAdditionalRootNode(astNodes) {
  23229. var lastAstNode = astNodes[astNodes.length - 1];
  23230. if (lastAstNode instanceof EmbeddedTemplateAst) {
  23231. return lastAstNode.hasViewContainer;
  23232. }
  23233. if (lastAstNode instanceof ElementAst) {
  23234. if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
  23235. return needsAdditionalRootNode(lastAstNode.children);
  23236. }
  23237. return lastAstNode.hasViewContainer;
  23238. }
  23239. return lastAstNode instanceof NgContentAst;
  23240. }
  23241. function elementBindingDef(inputAst, dirAst) {
  23242. var inputType = inputAst.type;
  23243. switch (inputType) {
  23244. case 1 /* Attribute */:
  23245. return literalArr([
  23246. literal(1 /* TypeElementAttribute */), literal(inputAst.name),
  23247. literal(inputAst.securityContext)
  23248. ]);
  23249. case 0 /* Property */:
  23250. return literalArr([
  23251. literal(8 /* TypeProperty */), literal(inputAst.name),
  23252. literal(inputAst.securityContext)
  23253. ]);
  23254. case 4 /* Animation */:
  23255. var bindingType = 8 /* TypeProperty */ |
  23256. (dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
  23257. 16 /* SyntheticProperty */);
  23258. return literalArr([
  23259. literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
  23260. ]);
  23261. case 2 /* Class */:
  23262. return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
  23263. case 3 /* Style */:
  23264. return literalArr([
  23265. literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
  23266. ]);
  23267. default:
  23268. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  23269. // However Closure Compiler does not understand that and reports an error in typed mode.
  23270. // The `throw new Error` below works around the problem, and the unexpected: never variable
  23271. // makes sure tsc still checks this code is unreachable.
  23272. var unexpected = inputType;
  23273. throw new Error("unexpected " + unexpected);
  23274. }
  23275. }
  23276. function fixedAttrsDef(elementAst) {
  23277. var mapResult = Object.create(null);
  23278. elementAst.attrs.forEach(function (attrAst) { mapResult[attrAst.name] = attrAst.value; });
  23279. elementAst.directives.forEach(function (dirAst) {
  23280. Object.keys(dirAst.directive.hostAttributes).forEach(function (name) {
  23281. var value = dirAst.directive.hostAttributes[name];
  23282. var prevValue = mapResult[name];
  23283. mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
  23284. });
  23285. });
  23286. // Note: We need to sort to get a defined output order
  23287. // for tests and for caching generated artifacts...
  23288. return literalArr(Object.keys(mapResult).sort().map(function (attrName) { return literalArr([literal(attrName), literal(mapResult[attrName])]); }));
  23289. }
  23290. function mergeAttributeValue(attrName, attrValue1, attrValue2) {
  23291. if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
  23292. return attrValue1 + " " + attrValue2;
  23293. }
  23294. else {
  23295. return attrValue2;
  23296. }
  23297. }
  23298. function callCheckStmt(nodeIndex, exprs) {
  23299. if (exprs.length > 10) {
  23300. return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
  23301. }
  23302. else {
  23303. return CHECK_VAR.callFn(__spread([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */)], exprs));
  23304. }
  23305. }
  23306. function callUnwrapValue(nodeIndex, bindingIdx, expr) {
  23307. return importExpr(Identifiers.unwrapValue).callFn([
  23308. VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
  23309. ]);
  23310. }
  23311. function findStaticQueryIds(nodes, result) {
  23312. if (result === void 0) { result = new Map(); }
  23313. nodes.forEach(function (node) {
  23314. var staticQueryIds = new Set();
  23315. var dynamicQueryIds = new Set();
  23316. var queryMatches = undefined;
  23317. if (node instanceof ElementAst) {
  23318. findStaticQueryIds(node.children, result);
  23319. node.children.forEach(function (child) {
  23320. var childData = result.get(child);
  23321. childData.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
  23322. childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23323. });
  23324. queryMatches = node.queryMatches;
  23325. }
  23326. else if (node instanceof EmbeddedTemplateAst) {
  23327. findStaticQueryIds(node.children, result);
  23328. node.children.forEach(function (child) {
  23329. var childData = result.get(child);
  23330. childData.staticQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23331. childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23332. });
  23333. queryMatches = node.queryMatches;
  23334. }
  23335. if (queryMatches) {
  23336. queryMatches.forEach(function (match) { return staticQueryIds.add(match.queryId); });
  23337. }
  23338. dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
  23339. result.set(node, { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds });
  23340. });
  23341. return result;
  23342. }
  23343. function staticViewQueryIds(nodeStaticQueryIds) {
  23344. var staticQueryIds = new Set();
  23345. var dynamicQueryIds = new Set();
  23346. Array.from(nodeStaticQueryIds.values()).forEach(function (entry) {
  23347. entry.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
  23348. entry.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23349. });
  23350. dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
  23351. return { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds };
  23352. }
  23353. function elementEventNameAndTarget(eventAst, dirAst) {
  23354. if (eventAst.isAnimation) {
  23355. return {
  23356. name: "@" + eventAst.name + "." + eventAst.phase,
  23357. target: dirAst && dirAst.directive.isComponent ? 'component' : null
  23358. };
  23359. }
  23360. else {
  23361. return eventAst;
  23362. }
  23363. }
  23364. function calcStaticDynamicQueryFlags(queryIds, queryId, query) {
  23365. var flags = 0 /* None */;
  23366. // Note: We only make queries static that query for a single item.
  23367. // This is because of backwards compatibility with the old view compiler...
  23368. if (query.first && shouldResolveAsStaticQuery(queryIds, queryId, query)) {
  23369. flags |= 268435456 /* StaticQuery */;
  23370. }
  23371. else {
  23372. flags |= 536870912 /* DynamicQuery */;
  23373. }
  23374. return flags;
  23375. }
  23376. function shouldResolveAsStaticQuery(queryIds, queryId, query) {
  23377. // If query.static has been set by the user, use that value to determine whether
  23378. // the query is static. If none has been set, sort the query into static/dynamic
  23379. // based on query results (i.e. dynamic if CD needs to run to get all results).
  23380. return query.static ||
  23381. query.static == null &&
  23382. (queryIds.staticQueryIds.has(queryId) || !queryIds.dynamicQueryIds.has(queryId));
  23383. }
  23384. function elementEventFullName(target, name) {
  23385. return target ? target + ":" + name : name;
  23386. }
  23387. /**
  23388. * @license
  23389. * Copyright Google Inc. All Rights Reserved.
  23390. *
  23391. * Use of this source code is governed by an MIT-style license that can be
  23392. * found in the LICENSE file at https://angular.io/license
  23393. */
  23394. /**
  23395. * A container for message extracted from the templates.
  23396. */
  23397. var MessageBundle = /** @class */ (function () {
  23398. function MessageBundle(_htmlParser, _implicitTags, _implicitAttrs, _locale) {
  23399. if (_locale === void 0) { _locale = null; }
  23400. this._htmlParser = _htmlParser;
  23401. this._implicitTags = _implicitTags;
  23402. this._implicitAttrs = _implicitAttrs;
  23403. this._locale = _locale;
  23404. this._messages = [];
  23405. }
  23406. MessageBundle.prototype.updateFromTemplate = function (html, url, interpolationConfig) {
  23407. var _a;
  23408. var htmlParserResult = this._htmlParser.parse(html, url, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  23409. if (htmlParserResult.errors.length) {
  23410. return htmlParserResult.errors;
  23411. }
  23412. var i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
  23413. if (i18nParserResult.errors.length) {
  23414. return i18nParserResult.errors;
  23415. }
  23416. (_a = this._messages).push.apply(_a, __spread(i18nParserResult.messages));
  23417. return [];
  23418. };
  23419. // Return the message in the internal format
  23420. // The public (serialized) format might be different, see the `write` method.
  23421. MessageBundle.prototype.getMessages = function () { return this._messages; };
  23422. MessageBundle.prototype.write = function (serializer, filterSources) {
  23423. var messages = {};
  23424. var mapperVisitor = new MapPlaceholderNames();
  23425. // Deduplicate messages based on their ID
  23426. this._messages.forEach(function (message) {
  23427. var _a;
  23428. var id = serializer.digest(message);
  23429. if (!messages.hasOwnProperty(id)) {
  23430. messages[id] = message;
  23431. }
  23432. else {
  23433. (_a = messages[id].sources).push.apply(_a, __spread(message.sources));
  23434. }
  23435. });
  23436. // Transform placeholder names using the serializer mapping
  23437. var msgList = Object.keys(messages).map(function (id) {
  23438. var mapper = serializer.createNameMapper(messages[id]);
  23439. var src = messages[id];
  23440. var nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
  23441. var transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
  23442. transformedMessage.sources = src.sources;
  23443. if (filterSources) {
  23444. transformedMessage.sources.forEach(function (source) { return source.filePath = filterSources(source.filePath); });
  23445. }
  23446. return transformedMessage;
  23447. });
  23448. return serializer.write(msgList, this._locale);
  23449. };
  23450. return MessageBundle;
  23451. }());
  23452. // Transform an i18n AST by renaming the placeholder nodes with the given mapper
  23453. var MapPlaceholderNames = /** @class */ (function (_super) {
  23454. __extends(MapPlaceholderNames, _super);
  23455. function MapPlaceholderNames() {
  23456. return _super !== null && _super.apply(this, arguments) || this;
  23457. }
  23458. MapPlaceholderNames.prototype.convert = function (nodes, mapper) {
  23459. var _this = this;
  23460. return mapper ? nodes.map(function (n) { return n.visit(_this, mapper); }) : nodes;
  23461. };
  23462. MapPlaceholderNames.prototype.visitTagPlaceholder = function (ph, mapper) {
  23463. var _this = this;
  23464. var startName = mapper.toPublicName(ph.startName);
  23465. var closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
  23466. var children = ph.children.map(function (n) { return n.visit(_this, mapper); });
  23467. return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan);
  23468. };
  23469. MapPlaceholderNames.prototype.visitPlaceholder = function (ph, mapper) {
  23470. return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  23471. };
  23472. MapPlaceholderNames.prototype.visitIcuPlaceholder = function (ph, mapper) {
  23473. return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  23474. };
  23475. return MapPlaceholderNames;
  23476. }(CloneVisitor));
  23477. /**
  23478. * @license
  23479. * Copyright Google Inc. All Rights Reserved.
  23480. *
  23481. * Use of this source code is governed by an MIT-style license that can be
  23482. * found in the LICENSE file at https://angular.io/license
  23483. */
  23484. var GeneratedFile = /** @class */ (function () {
  23485. function GeneratedFile(srcFileUrl, genFileUrl, sourceOrStmts) {
  23486. this.srcFileUrl = srcFileUrl;
  23487. this.genFileUrl = genFileUrl;
  23488. if (typeof sourceOrStmts === 'string') {
  23489. this.source = sourceOrStmts;
  23490. this.stmts = null;
  23491. }
  23492. else {
  23493. this.source = null;
  23494. this.stmts = sourceOrStmts;
  23495. }
  23496. }
  23497. GeneratedFile.prototype.isEquivalent = function (other) {
  23498. if (this.genFileUrl !== other.genFileUrl) {
  23499. return false;
  23500. }
  23501. if (this.source) {
  23502. return this.source === other.source;
  23503. }
  23504. if (other.stmts == null) {
  23505. return false;
  23506. }
  23507. // Note: the constructor guarantees that if this.source is not filled,
  23508. // then this.stmts is.
  23509. return areAllEquivalent(this.stmts, other.stmts);
  23510. };
  23511. return GeneratedFile;
  23512. }());
  23513. function toTypeScript(file, preamble) {
  23514. if (preamble === void 0) { preamble = ''; }
  23515. if (!file.stmts) {
  23516. throw new Error("Illegal state: No stmts present on GeneratedFile " + file.genFileUrl);
  23517. }
  23518. return new TypeScriptEmitter().emitStatements(file.genFileUrl, file.stmts, preamble);
  23519. }
  23520. /**
  23521. * @license
  23522. * Copyright Google Inc. All Rights Reserved.
  23523. *
  23524. * Use of this source code is governed by an MIT-style license that can be
  23525. * found in the LICENSE file at https://angular.io/license
  23526. */
  23527. function listLazyRoutes(moduleMeta, reflector) {
  23528. var e_1, _a, e_2, _b;
  23529. var allLazyRoutes = [];
  23530. try {
  23531. for (var _c = __values(moduleMeta.transitiveModule.providers), _d = _c.next(); !_d.done; _d = _c.next()) {
  23532. var _e = _d.value, provider = _e.provider, module = _e.module;
  23533. if (tokenReference(provider.token) === reflector.ROUTES) {
  23534. var loadChildren = _collectLoadChildren(provider.useValue);
  23535. try {
  23536. for (var loadChildren_1 = __values(loadChildren), loadChildren_1_1 = loadChildren_1.next(); !loadChildren_1_1.done; loadChildren_1_1 = loadChildren_1.next()) {
  23537. var route = loadChildren_1_1.value;
  23538. allLazyRoutes.push(parseLazyRoute(route, reflector, module.reference));
  23539. }
  23540. }
  23541. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  23542. finally {
  23543. try {
  23544. if (loadChildren_1_1 && !loadChildren_1_1.done && (_b = loadChildren_1.return)) _b.call(loadChildren_1);
  23545. }
  23546. finally { if (e_2) throw e_2.error; }
  23547. }
  23548. }
  23549. }
  23550. }
  23551. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  23552. finally {
  23553. try {
  23554. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  23555. }
  23556. finally { if (e_1) throw e_1.error; }
  23557. }
  23558. return allLazyRoutes;
  23559. }
  23560. function _collectLoadChildren(routes, target) {
  23561. var e_3, _a;
  23562. if (target === void 0) { target = []; }
  23563. if (typeof routes === 'string') {
  23564. target.push(routes);
  23565. }
  23566. else if (Array.isArray(routes)) {
  23567. try {
  23568. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  23569. var route = routes_1_1.value;
  23570. _collectLoadChildren(route, target);
  23571. }
  23572. }
  23573. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  23574. finally {
  23575. try {
  23576. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  23577. }
  23578. finally { if (e_3) throw e_3.error; }
  23579. }
  23580. }
  23581. else if (routes.loadChildren) {
  23582. _collectLoadChildren(routes.loadChildren, target);
  23583. }
  23584. else if (routes.children) {
  23585. _collectLoadChildren(routes.children, target);
  23586. }
  23587. return target;
  23588. }
  23589. function parseLazyRoute(route, reflector, module) {
  23590. var _a = __read(route.split('#'), 2), routePath = _a[0], routeName = _a[1];
  23591. var referencedModule = reflector.resolveExternalReference({
  23592. moduleName: routePath,
  23593. name: routeName,
  23594. }, module ? module.filePath : undefined);
  23595. return { route: route, module: module || referencedModule, referencedModule: referencedModule };
  23596. }
  23597. /**
  23598. * @license
  23599. * Copyright Google Inc. All Rights Reserved.
  23600. *
  23601. * Use of this source code is governed by an MIT-style license that can be
  23602. * found in the LICENSE file at https://angular.io/license
  23603. */
  23604. var TS = /^(?!.*\.d\.ts$).*\.ts$/;
  23605. var ResolvedStaticSymbol = /** @class */ (function () {
  23606. function ResolvedStaticSymbol(symbol, metadata) {
  23607. this.symbol = symbol;
  23608. this.metadata = metadata;
  23609. }
  23610. return ResolvedStaticSymbol;
  23611. }());
  23612. var SUPPORTED_SCHEMA_VERSION = 4;
  23613. /**
  23614. * This class is responsible for loading metadata per symbol,
  23615. * and normalizing references between symbols.
  23616. *
  23617. * Internally, it only uses symbols without members,
  23618. * and deduces the values for symbols with members based
  23619. * on these symbols.
  23620. */
  23621. var StaticSymbolResolver = /** @class */ (function () {
  23622. function StaticSymbolResolver(host, staticSymbolCache, summaryResolver, errorRecorder) {
  23623. this.host = host;
  23624. this.staticSymbolCache = staticSymbolCache;
  23625. this.summaryResolver = summaryResolver;
  23626. this.errorRecorder = errorRecorder;
  23627. this.metadataCache = new Map();
  23628. // Note: this will only contain StaticSymbols without members!
  23629. this.resolvedSymbols = new Map();
  23630. this.resolvedFilePaths = new Set();
  23631. // Note: this will only contain StaticSymbols without members!
  23632. this.importAs = new Map();
  23633. this.symbolResourcePaths = new Map();
  23634. this.symbolFromFile = new Map();
  23635. this.knownFileNameToModuleNames = new Map();
  23636. }
  23637. StaticSymbolResolver.prototype.resolveSymbol = function (staticSymbol) {
  23638. if (staticSymbol.members.length > 0) {
  23639. return this._resolveSymbolMembers(staticSymbol);
  23640. }
  23641. // Note: always ask for a summary first,
  23642. // as we might have read shallow metadata via a .d.ts file
  23643. // for the symbol.
  23644. var resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
  23645. if (resultFromSummary) {
  23646. return resultFromSummary;
  23647. }
  23648. var resultFromCache = this.resolvedSymbols.get(staticSymbol);
  23649. if (resultFromCache) {
  23650. return resultFromCache;
  23651. }
  23652. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  23653. // have summaries, only .d.ts files. So we always need to check both, the summary
  23654. // and metadata.
  23655. this._createSymbolsOf(staticSymbol.filePath);
  23656. return this.resolvedSymbols.get(staticSymbol);
  23657. };
  23658. /**
  23659. * getImportAs produces a symbol that can be used to import the given symbol.
  23660. * The import might be different than the symbol if the symbol is exported from
  23661. * a library with a summary; in which case we want to import the symbol from the
  23662. * ngfactory re-export instead of directly to avoid introducing a direct dependency
  23663. * on an otherwise indirect dependency.
  23664. *
  23665. * @param staticSymbol the symbol for which to generate a import symbol
  23666. */
  23667. StaticSymbolResolver.prototype.getImportAs = function (staticSymbol, useSummaries) {
  23668. if (useSummaries === void 0) { useSummaries = true; }
  23669. if (staticSymbol.members.length) {
  23670. var baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
  23671. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  23672. return baseImportAs ?
  23673. this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
  23674. null;
  23675. }
  23676. var summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
  23677. if (summarizedFileName !== staticSymbol.filePath) {
  23678. var summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
  23679. var baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
  23680. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  23681. return baseImportAs ?
  23682. this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
  23683. null;
  23684. }
  23685. var result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
  23686. if (!result) {
  23687. result = this.importAs.get(staticSymbol);
  23688. }
  23689. return result;
  23690. };
  23691. /**
  23692. * getResourcePath produces the path to the original location of the symbol and should
  23693. * be used to determine the relative location of resource references recorded in
  23694. * symbol metadata.
  23695. */
  23696. StaticSymbolResolver.prototype.getResourcePath = function (staticSymbol) {
  23697. return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
  23698. };
  23699. /**
  23700. * getTypeArity returns the number of generic type parameters the given symbol
  23701. * has. If the symbol is not a type the result is null.
  23702. */
  23703. StaticSymbolResolver.prototype.getTypeArity = function (staticSymbol) {
  23704. // If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
  23705. // cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
  23706. // All references to generated classes must include the correct arity whenever
  23707. // generating code.
  23708. if (isGeneratedFile(staticSymbol.filePath)) {
  23709. return null;
  23710. }
  23711. var resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
  23712. while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
  23713. resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
  23714. }
  23715. return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
  23716. };
  23717. StaticSymbolResolver.prototype.getKnownModuleName = function (filePath) {
  23718. return this.knownFileNameToModuleNames.get(filePath) || null;
  23719. };
  23720. StaticSymbolResolver.prototype.recordImportAs = function (sourceSymbol, targetSymbol) {
  23721. sourceSymbol.assertNoMembers();
  23722. targetSymbol.assertNoMembers();
  23723. this.importAs.set(sourceSymbol, targetSymbol);
  23724. };
  23725. StaticSymbolResolver.prototype.recordModuleNameForFileName = function (fileName, moduleName) {
  23726. this.knownFileNameToModuleNames.set(fileName, moduleName);
  23727. };
  23728. /**
  23729. * Invalidate all information derived from the given file.
  23730. *
  23731. * @param fileName the file to invalidate
  23732. */
  23733. StaticSymbolResolver.prototype.invalidateFile = function (fileName) {
  23734. var e_1, _a;
  23735. this.metadataCache.delete(fileName);
  23736. this.resolvedFilePaths.delete(fileName);
  23737. var symbols = this.symbolFromFile.get(fileName);
  23738. if (symbols) {
  23739. this.symbolFromFile.delete(fileName);
  23740. try {
  23741. for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
  23742. var symbol = symbols_1_1.value;
  23743. this.resolvedSymbols.delete(symbol);
  23744. this.importAs.delete(symbol);
  23745. this.symbolResourcePaths.delete(symbol);
  23746. }
  23747. }
  23748. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  23749. finally {
  23750. try {
  23751. if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
  23752. }
  23753. finally { if (e_1) throw e_1.error; }
  23754. }
  23755. }
  23756. };
  23757. /** @internal */
  23758. StaticSymbolResolver.prototype.ignoreErrorsFor = function (cb) {
  23759. var recorder = this.errorRecorder;
  23760. this.errorRecorder = function () { };
  23761. try {
  23762. return cb();
  23763. }
  23764. finally {
  23765. this.errorRecorder = recorder;
  23766. }
  23767. };
  23768. StaticSymbolResolver.prototype._resolveSymbolMembers = function (staticSymbol) {
  23769. var members = staticSymbol.members;
  23770. var baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
  23771. if (!baseResolvedSymbol) {
  23772. return null;
  23773. }
  23774. var baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
  23775. if (baseMetadata instanceof StaticSymbol) {
  23776. return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
  23777. }
  23778. else if (baseMetadata && baseMetadata.__symbolic === 'class') {
  23779. if (baseMetadata.statics && members.length === 1) {
  23780. return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
  23781. }
  23782. }
  23783. else {
  23784. var value = baseMetadata;
  23785. for (var i = 0; i < members.length && value; i++) {
  23786. value = value[members[i]];
  23787. }
  23788. return new ResolvedStaticSymbol(staticSymbol, value);
  23789. }
  23790. return null;
  23791. };
  23792. StaticSymbolResolver.prototype._resolveSymbolFromSummary = function (staticSymbol) {
  23793. var summary = this.summaryResolver.resolveSummary(staticSymbol);
  23794. return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
  23795. };
  23796. /**
  23797. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  23798. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  23799. *
  23800. * @param declarationFile the absolute path of the file where the symbol is declared
  23801. * @param name the name of the type.
  23802. * @param members a symbol for a static member of the named type
  23803. */
  23804. StaticSymbolResolver.prototype.getStaticSymbol = function (declarationFile, name, members) {
  23805. return this.staticSymbolCache.get(declarationFile, name, members);
  23806. };
  23807. /**
  23808. * hasDecorators checks a file's metadata for the presence of decorators without evaluating the
  23809. * metadata.
  23810. *
  23811. * @param filePath the absolute path to examine for decorators.
  23812. * @returns true if any class in the file has a decorator.
  23813. */
  23814. StaticSymbolResolver.prototype.hasDecorators = function (filePath) {
  23815. var metadata = this.getModuleMetadata(filePath);
  23816. if (metadata['metadata']) {
  23817. return Object.keys(metadata['metadata']).some(function (metadataKey) {
  23818. var entry = metadata['metadata'][metadataKey];
  23819. return entry && entry.__symbolic === 'class' && entry.decorators;
  23820. });
  23821. }
  23822. return false;
  23823. };
  23824. StaticSymbolResolver.prototype.getSymbolsOf = function (filePath) {
  23825. var summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
  23826. if (summarySymbols) {
  23827. return summarySymbols;
  23828. }
  23829. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  23830. // have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
  23831. this._createSymbolsOf(filePath);
  23832. var metadataSymbols = [];
  23833. this.resolvedSymbols.forEach(function (resolvedSymbol) {
  23834. if (resolvedSymbol.symbol.filePath === filePath) {
  23835. metadataSymbols.push(resolvedSymbol.symbol);
  23836. }
  23837. });
  23838. return metadataSymbols;
  23839. };
  23840. StaticSymbolResolver.prototype._createSymbolsOf = function (filePath) {
  23841. var _this = this;
  23842. var e_2, _a;
  23843. if (this.resolvedFilePaths.has(filePath)) {
  23844. return;
  23845. }
  23846. this.resolvedFilePaths.add(filePath);
  23847. var resolvedSymbols = [];
  23848. var metadata = this.getModuleMetadata(filePath);
  23849. if (metadata['importAs']) {
  23850. // Index bundle indices should use the importAs module name defined
  23851. // in the bundle.
  23852. this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
  23853. }
  23854. // handle the symbols in one of the re-export location
  23855. if (metadata['exports']) {
  23856. var _loop_1 = function (moduleExport) {
  23857. // handle the symbols in the list of explicitly re-exported symbols.
  23858. if (moduleExport.export) {
  23859. moduleExport.export.forEach(function (exportSymbol) {
  23860. var symbolName;
  23861. if (typeof exportSymbol === 'string') {
  23862. symbolName = exportSymbol;
  23863. }
  23864. else {
  23865. symbolName = exportSymbol.as;
  23866. }
  23867. symbolName = unescapeIdentifier(symbolName);
  23868. var symName = symbolName;
  23869. if (typeof exportSymbol !== 'string') {
  23870. symName = unescapeIdentifier(exportSymbol.name);
  23871. }
  23872. var resolvedModule = _this.resolveModule(moduleExport.from, filePath);
  23873. if (resolvedModule) {
  23874. var targetSymbol = _this.getStaticSymbol(resolvedModule, symName);
  23875. var sourceSymbol = _this.getStaticSymbol(filePath, symbolName);
  23876. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  23877. }
  23878. });
  23879. }
  23880. else {
  23881. // handle the symbols via export * directives.
  23882. var resolvedModule = this_1.resolveModule(moduleExport.from, filePath);
  23883. if (resolvedModule) {
  23884. var nestedExports = this_1.getSymbolsOf(resolvedModule);
  23885. nestedExports.forEach(function (targetSymbol) {
  23886. var sourceSymbol = _this.getStaticSymbol(filePath, targetSymbol.name);
  23887. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  23888. });
  23889. }
  23890. }
  23891. };
  23892. var this_1 = this;
  23893. try {
  23894. for (var _b = __values(metadata['exports']), _c = _b.next(); !_c.done; _c = _b.next()) {
  23895. var moduleExport = _c.value;
  23896. _loop_1(moduleExport);
  23897. }
  23898. }
  23899. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  23900. finally {
  23901. try {
  23902. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  23903. }
  23904. finally { if (e_2) throw e_2.error; }
  23905. }
  23906. }
  23907. // handle the actual metadata. Has to be after the exports
  23908. // as there might be collisions in the names, and we want the symbols
  23909. // of the current module to win ofter reexports.
  23910. if (metadata['metadata']) {
  23911. // handle direct declarations of the symbol
  23912. var topLevelSymbolNames_1 = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
  23913. var origins_1 = metadata['origins'] || {};
  23914. Object.keys(metadata['metadata']).forEach(function (metadataKey) {
  23915. var symbolMeta = metadata['metadata'][metadataKey];
  23916. var name = unescapeIdentifier(metadataKey);
  23917. var symbol = _this.getStaticSymbol(filePath, name);
  23918. var origin = origins_1.hasOwnProperty(metadataKey) && origins_1[metadataKey];
  23919. if (origin) {
  23920. // If the symbol is from a bundled index, use the declaration location of the
  23921. // symbol so relative references (such as './my.html') will be calculated
  23922. // correctly.
  23923. var originFilePath = _this.resolveModule(origin, filePath);
  23924. if (!originFilePath) {
  23925. _this.reportError(new Error("Couldn't resolve original symbol for " + origin + " from " + _this.host.getOutputName(filePath)));
  23926. }
  23927. else {
  23928. _this.symbolResourcePaths.set(symbol, originFilePath);
  23929. }
  23930. }
  23931. resolvedSymbols.push(_this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames_1, symbolMeta));
  23932. });
  23933. }
  23934. resolvedSymbols.forEach(function (resolvedSymbol) { return _this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol); });
  23935. this.symbolFromFile.set(filePath, resolvedSymbols.map(function (resolvedSymbol) { return resolvedSymbol.symbol; }));
  23936. };
  23937. StaticSymbolResolver.prototype.createResolvedSymbol = function (sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
  23938. var _this = this;
  23939. // For classes that don't have Angular summaries / metadata,
  23940. // we only keep their arity, but nothing else
  23941. // (e.g. their constructor parameters).
  23942. // We do this to prevent introducing deep imports
  23943. // as we didn't generate .ngfactory.ts files with proper reexports.
  23944. var isTsFile = TS.test(sourceSymbol.filePath);
  23945. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
  23946. metadata['__symbolic'] === 'class') {
  23947. var transformedMeta_1 = { __symbolic: 'class', arity: metadata.arity };
  23948. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta_1);
  23949. }
  23950. var _originalFileMemo;
  23951. var getOriginalName = function () {
  23952. if (!_originalFileMemo) {
  23953. // Guess what the original file name is from the reference. If it has a `.d.ts` extension
  23954. // replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
  23955. // .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
  23956. // location as it is not important to finding the file.
  23957. _originalFileMemo =
  23958. _this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
  23959. .replace(/^.*node_modules[/\\]/, ''));
  23960. }
  23961. return _originalFileMemo;
  23962. };
  23963. var self = this;
  23964. var ReferenceTransformer = /** @class */ (function (_super) {
  23965. __extends(ReferenceTransformer, _super);
  23966. function ReferenceTransformer() {
  23967. return _super !== null && _super.apply(this, arguments) || this;
  23968. }
  23969. ReferenceTransformer.prototype.visitStringMap = function (map, functionParams) {
  23970. var symbolic = map['__symbolic'];
  23971. if (symbolic === 'function') {
  23972. var oldLen = functionParams.length;
  23973. functionParams.push.apply(functionParams, __spread((map['parameters'] || [])));
  23974. var result = _super.prototype.visitStringMap.call(this, map, functionParams);
  23975. functionParams.length = oldLen;
  23976. return result;
  23977. }
  23978. else if (symbolic === 'reference') {
  23979. var module = map['module'];
  23980. var name_1 = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
  23981. if (!name_1) {
  23982. return null;
  23983. }
  23984. var filePath = void 0;
  23985. if (module) {
  23986. filePath = self.resolveModule(module, sourceSymbol.filePath);
  23987. if (!filePath) {
  23988. return {
  23989. __symbolic: 'error',
  23990. message: "Could not resolve " + module + " relative to " + self.host.getMetadataFor(sourceSymbol.filePath) + ".",
  23991. line: map['line'],
  23992. character: map['character'],
  23993. fileName: getOriginalName()
  23994. };
  23995. }
  23996. return {
  23997. __symbolic: 'resolved',
  23998. symbol: self.getStaticSymbol(filePath, name_1),
  23999. line: map['line'],
  24000. character: map['character'],
  24001. fileName: getOriginalName()
  24002. };
  24003. }
  24004. else if (functionParams.indexOf(name_1) >= 0) {
  24005. // reference to a function parameter
  24006. return { __symbolic: 'reference', name: name_1 };
  24007. }
  24008. else {
  24009. if (topLevelSymbolNames.has(name_1)) {
  24010. return self.getStaticSymbol(topLevelPath, name_1);
  24011. }
  24012. }
  24013. }
  24014. else if (symbolic === 'error') {
  24015. return __assign({}, map, { fileName: getOriginalName() });
  24016. }
  24017. else {
  24018. return _super.prototype.visitStringMap.call(this, map, functionParams);
  24019. }
  24020. };
  24021. return ReferenceTransformer;
  24022. }(ValueTransformer));
  24023. var transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
  24024. var unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
  24025. if (unwrappedTransformedMeta instanceof StaticSymbol) {
  24026. return this.createExport(sourceSymbol, unwrappedTransformedMeta);
  24027. }
  24028. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
  24029. };
  24030. StaticSymbolResolver.prototype.createExport = function (sourceSymbol, targetSymbol) {
  24031. sourceSymbol.assertNoMembers();
  24032. targetSymbol.assertNoMembers();
  24033. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
  24034. this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
  24035. // This case is for an ng library importing symbols from a plain ts library
  24036. // transitively.
  24037. // Note: We rely on the fact that we discover symbols in the direction
  24038. // from source files to library files
  24039. this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
  24040. }
  24041. return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
  24042. };
  24043. StaticSymbolResolver.prototype.reportError = function (error, context, path) {
  24044. if (this.errorRecorder) {
  24045. this.errorRecorder(error, (context && context.filePath) || path);
  24046. }
  24047. else {
  24048. throw error;
  24049. }
  24050. };
  24051. /**
  24052. * @param module an absolute path to a module file.
  24053. */
  24054. StaticSymbolResolver.prototype.getModuleMetadata = function (module) {
  24055. var moduleMetadata = this.metadataCache.get(module);
  24056. if (!moduleMetadata) {
  24057. var moduleMetadatas = this.host.getMetadataFor(module);
  24058. if (moduleMetadatas) {
  24059. var maxVersion_1 = -1;
  24060. moduleMetadatas.forEach(function (md) {
  24061. if (md && md['version'] > maxVersion_1) {
  24062. maxVersion_1 = md['version'];
  24063. moduleMetadata = md;
  24064. }
  24065. });
  24066. }
  24067. if (!moduleMetadata) {
  24068. moduleMetadata =
  24069. { __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
  24070. }
  24071. if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
  24072. var errorMessage = moduleMetadata['version'] == 2 ?
  24073. "Unsupported metadata version " + moduleMetadata['version'] + " for module " + module + ". This module should be compiled with a newer version of ngc" :
  24074. "Metadata version mismatch for module " + this.host.getOutputName(module) + ", found version " + moduleMetadata['version'] + ", expected " + SUPPORTED_SCHEMA_VERSION;
  24075. this.reportError(new Error(errorMessage));
  24076. }
  24077. this.metadataCache.set(module, moduleMetadata);
  24078. }
  24079. return moduleMetadata;
  24080. };
  24081. StaticSymbolResolver.prototype.getSymbolByModule = function (module, symbolName, containingFile) {
  24082. var filePath = this.resolveModule(module, containingFile);
  24083. if (!filePath) {
  24084. this.reportError(new Error("Could not resolve module " + module + (containingFile ? ' relative to ' +
  24085. this.host.getOutputName(containingFile) : '')));
  24086. return this.getStaticSymbol("ERROR:" + module, symbolName);
  24087. }
  24088. return this.getStaticSymbol(filePath, symbolName);
  24089. };
  24090. StaticSymbolResolver.prototype.resolveModule = function (module, containingFile) {
  24091. try {
  24092. return this.host.moduleNameToFileName(module, containingFile);
  24093. }
  24094. catch (e) {
  24095. console.error("Could not resolve module '" + module + "' relative to file " + containingFile);
  24096. this.reportError(e, undefined, containingFile);
  24097. }
  24098. return null;
  24099. };
  24100. return StaticSymbolResolver;
  24101. }());
  24102. // Remove extra underscore from escaped identifier.
  24103. // See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
  24104. function unescapeIdentifier(identifier) {
  24105. return identifier.startsWith('___') ? identifier.substr(1) : identifier;
  24106. }
  24107. function unwrapResolvedMetadata(metadata) {
  24108. if (metadata && metadata.__symbolic === 'resolved') {
  24109. return metadata.symbol;
  24110. }
  24111. return metadata;
  24112. }
  24113. function serializeSummaries(srcFileName, forJitCtx, summaryResolver, symbolResolver, symbols, types, createExternalSymbolReexports) {
  24114. if (createExternalSymbolReexports === void 0) { createExternalSymbolReexports = false; }
  24115. var toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);
  24116. // for symbols, we use everything except for the class metadata itself
  24117. // (we keep the statics though), as the class metadata is contained in the
  24118. // CompileTypeSummary.
  24119. symbols.forEach(function (resolvedSymbol) { return toJsonSerializer.addSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }); });
  24120. // Add type summaries.
  24121. types.forEach(function (_a) {
  24122. var summary = _a.summary, metadata = _a.metadata;
  24123. toJsonSerializer.addSummary({ symbol: summary.type.reference, metadata: undefined, type: summary });
  24124. });
  24125. var _a = toJsonSerializer.serialize(createExternalSymbolReexports), json = _a.json, exportAs = _a.exportAs;
  24126. if (forJitCtx) {
  24127. var forJitSerializer_1 = new ForJitSerializer(forJitCtx, symbolResolver, summaryResolver);
  24128. types.forEach(function (_a) {
  24129. var summary = _a.summary, metadata = _a.metadata;
  24130. forJitSerializer_1.addSourceType(summary, metadata);
  24131. });
  24132. toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach(function (summary) {
  24133. if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
  24134. forJitSerializer_1.addLibType(summary.type);
  24135. }
  24136. });
  24137. forJitSerializer_1.serialize(exportAs);
  24138. }
  24139. return { json: json, exportAs: exportAs };
  24140. }
  24141. function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
  24142. var deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
  24143. return deserializer.deserialize(libraryFileName, json);
  24144. }
  24145. function createForJitStub(outputCtx, reference) {
  24146. return createSummaryForJitFunction(outputCtx, reference, NULL_EXPR);
  24147. }
  24148. function createSummaryForJitFunction(outputCtx, reference, value) {
  24149. var fnName = summaryForJitName(reference.name);
  24150. outputCtx.statements.push(fn([], [new ReturnStatement(value)], new ArrayType(DYNAMIC_TYPE)).toDeclStmt(fnName, [
  24151. StmtModifier.Final, StmtModifier.Exported
  24152. ]));
  24153. }
  24154. var ToJsonSerializer = /** @class */ (function (_super) {
  24155. __extends(ToJsonSerializer, _super);
  24156. function ToJsonSerializer(symbolResolver, summaryResolver, srcFileName) {
  24157. var _this = _super.call(this) || this;
  24158. _this.symbolResolver = symbolResolver;
  24159. _this.summaryResolver = summaryResolver;
  24160. _this.srcFileName = srcFileName;
  24161. // Note: This only contains symbols without members.
  24162. _this.symbols = [];
  24163. _this.indexBySymbol = new Map();
  24164. _this.reexportedBy = new Map();
  24165. // This now contains a `__symbol: number` in the place of
  24166. // StaticSymbols, but otherwise has the same shape as the original objects.
  24167. _this.processedSummaryBySymbol = new Map();
  24168. _this.processedSummaries = [];
  24169. _this.unprocessedSymbolSummariesBySymbol = new Map();
  24170. _this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
  24171. return _this;
  24172. }
  24173. ToJsonSerializer.prototype.addSummary = function (summary) {
  24174. var _this = this;
  24175. var unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
  24176. var processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
  24177. if (!unprocessedSummary) {
  24178. unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
  24179. this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
  24180. processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
  24181. this.processedSummaries.push(processedSummary);
  24182. this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
  24183. }
  24184. if (!unprocessedSummary.metadata && summary.metadata) {
  24185. var metadata_1 = summary.metadata || {};
  24186. if (metadata_1.__symbolic === 'class') {
  24187. // For classes, we keep everything except their class decorators.
  24188. // We need to keep e.g. the ctor args, method names, method decorators
  24189. // so that the class can be extended in another compilation unit.
  24190. // We don't keep the class decorators as
  24191. // 1) they refer to data
  24192. // that should not cause a rebuild of downstream compilation units
  24193. // (e.g. inline templates of @Component, or @NgModule.declarations)
  24194. // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
  24195. var clone_1 = {};
  24196. Object.keys(metadata_1).forEach(function (propName) {
  24197. if (propName !== 'decorators') {
  24198. clone_1[propName] = metadata_1[propName];
  24199. }
  24200. });
  24201. metadata_1 = clone_1;
  24202. }
  24203. else if (isCall(metadata_1)) {
  24204. if (!isFunctionCall(metadata_1) && !isMethodCallOnVariable(metadata_1)) {
  24205. // Don't store complex calls as we won't be able to simplify them anyways later on.
  24206. metadata_1 = {
  24207. __symbolic: 'error',
  24208. message: 'Complex function calls are not supported.',
  24209. };
  24210. }
  24211. }
  24212. // Note: We need to keep storing ctor calls for e.g.
  24213. // `export const x = new InjectionToken(...)`
  24214. unprocessedSummary.metadata = metadata_1;
  24215. processedSummary.metadata = this.processValue(metadata_1, 1 /* ResolveValue */);
  24216. if (metadata_1 instanceof StaticSymbol &&
  24217. this.summaryResolver.isLibraryFile(metadata_1.filePath)) {
  24218. var declarationSymbol = this.symbols[this.indexBySymbol.get(metadata_1)];
  24219. if (!isLoweredSymbol(declarationSymbol.name)) {
  24220. // Note: symbols that were introduced during codegen in the user file can have a reexport
  24221. // if a user used `export *`. However, we can't rely on this as tsickle will change
  24222. // `export *` into named exports, using only the information from the typechecker.
  24223. // As we introduce the new symbols after typecheck, Tsickle does not know about them,
  24224. // and omits them when expanding `export *`.
  24225. // So we have to keep reexporting these symbols manually via .ngfactory files.
  24226. this.reexportedBy.set(declarationSymbol, summary.symbol);
  24227. }
  24228. }
  24229. }
  24230. if (!unprocessedSummary.type && summary.type) {
  24231. unprocessedSummary.type = summary.type;
  24232. // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
  24233. // as the type summaries already contain the transitive data that they require
  24234. // (in a minimal way).
  24235. processedSummary.type = this.processValue(summary.type, 0 /* None */);
  24236. // except for reexported directives / pipes, so we need to store
  24237. // their summaries explicitly.
  24238. if (summary.type.summaryKind === CompileSummaryKind.NgModule) {
  24239. var ngModuleSummary = summary.type;
  24240. ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach(function (id) {
  24241. var symbol = id.reference;
  24242. if (_this.summaryResolver.isLibraryFile(symbol.filePath) &&
  24243. !_this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
  24244. var summary_1 = _this.summaryResolver.resolveSummary(symbol);
  24245. if (summary_1) {
  24246. _this.addSummary(summary_1);
  24247. }
  24248. }
  24249. });
  24250. }
  24251. }
  24252. };
  24253. /**
  24254. * @param createExternalSymbolReexports Whether external static symbols should be re-exported.
  24255. * This can be enabled if external symbols should be re-exported by the current module in
  24256. * order to avoid dynamically generated module dependencies which can break strict dependency
  24257. * enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
  24258. */
  24259. ToJsonSerializer.prototype.serialize = function (createExternalSymbolReexports) {
  24260. var _this = this;
  24261. var exportAs = [];
  24262. var json = JSON.stringify({
  24263. moduleName: this.moduleName,
  24264. summaries: this.processedSummaries,
  24265. symbols: this.symbols.map(function (symbol, index) {
  24266. symbol.assertNoMembers();
  24267. var importAs = undefined;
  24268. if (_this.summaryResolver.isLibraryFile(symbol.filePath)) {
  24269. var reexportSymbol = _this.reexportedBy.get(symbol);
  24270. if (reexportSymbol) {
  24271. // In case the given external static symbol is already manually exported by the
  24272. // user, we just proxy the external static symbol reference to the manual export.
  24273. // This ensures that the AOT compiler imports the external symbol through the
  24274. // user export and does not introduce another dependency which is not needed.
  24275. importAs = _this.indexBySymbol.get(reexportSymbol);
  24276. }
  24277. else if (createExternalSymbolReexports) {
  24278. // In this case, the given external static symbol is *not* manually exported by
  24279. // the user, and we manually create a re-export in the factory file so that we
  24280. // don't introduce another module dependency. This is useful when running within
  24281. // Bazel so that the AOT compiler does not introduce any module dependencies
  24282. // which can break the strict dependency enforcement. (e.g. as in Google3)
  24283. // Read more about this here: https://github.com/angular/angular/issues/25644
  24284. var summary = _this.unprocessedSymbolSummariesBySymbol.get(symbol);
  24285. if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
  24286. importAs = symbol.name + "_" + index;
  24287. exportAs.push({ symbol: symbol, exportAs: importAs });
  24288. }
  24289. }
  24290. }
  24291. return {
  24292. __symbol: index,
  24293. name: symbol.name,
  24294. filePath: _this.summaryResolver.toSummaryFileName(symbol.filePath, _this.srcFileName),
  24295. importAs: importAs
  24296. };
  24297. })
  24298. });
  24299. return { json: json, exportAs: exportAs };
  24300. };
  24301. ToJsonSerializer.prototype.processValue = function (value, flags) {
  24302. return visitValue(value, this, flags);
  24303. };
  24304. ToJsonSerializer.prototype.visitOther = function (value, context) {
  24305. if (value instanceof StaticSymbol) {
  24306. var baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
  24307. var index = this.visitStaticSymbol(baseSymbol, context);
  24308. return { __symbol: index, members: value.members };
  24309. }
  24310. };
  24311. /**
  24312. * Strip line and character numbers from ngsummaries.
  24313. * Emitting them causes white spaces changes to retrigger upstream
  24314. * recompilations in bazel.
  24315. * TODO: find out a way to have line and character numbers in errors without
  24316. * excessive recompilation in bazel.
  24317. */
  24318. ToJsonSerializer.prototype.visitStringMap = function (map, context) {
  24319. if (map['__symbolic'] === 'resolved') {
  24320. return visitValue(map['symbol'], this, context);
  24321. }
  24322. if (map['__symbolic'] === 'error') {
  24323. delete map['line'];
  24324. delete map['character'];
  24325. }
  24326. return _super.prototype.visitStringMap.call(this, map, context);
  24327. };
  24328. /**
  24329. * Returns null if the options.resolveValue is true, and the summary for the symbol
  24330. * resolved to a type or could not be resolved.
  24331. */
  24332. ToJsonSerializer.prototype.visitStaticSymbol = function (baseSymbol, flags) {
  24333. var index = this.indexBySymbol.get(baseSymbol);
  24334. var summary = null;
  24335. if (flags & 1 /* ResolveValue */ &&
  24336. this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
  24337. if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
  24338. // the summary for this symbol was already added
  24339. // -> nothing to do.
  24340. return index;
  24341. }
  24342. summary = this.loadSummary(baseSymbol);
  24343. if (summary && summary.metadata instanceof StaticSymbol) {
  24344. // The summary is a reexport
  24345. index = this.visitStaticSymbol(summary.metadata, flags);
  24346. // reset the summary as it is just a reexport, so we don't want to store it.
  24347. summary = null;
  24348. }
  24349. }
  24350. else if (index != null) {
  24351. // Note: == on purpose to compare with undefined!
  24352. // No summary and the symbol is already added -> nothing to do.
  24353. return index;
  24354. }
  24355. // Note: == on purpose to compare with undefined!
  24356. if (index == null) {
  24357. index = this.symbols.length;
  24358. this.symbols.push(baseSymbol);
  24359. }
  24360. this.indexBySymbol.set(baseSymbol, index);
  24361. if (summary) {
  24362. this.addSummary(summary);
  24363. }
  24364. return index;
  24365. };
  24366. ToJsonSerializer.prototype.loadSummary = function (symbol) {
  24367. var summary = this.summaryResolver.resolveSummary(symbol);
  24368. if (!summary) {
  24369. // some symbols might originate from a plain typescript library
  24370. // that just exported .d.ts and .metadata.json files, i.e. where no summary
  24371. // files were created.
  24372. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  24373. if (resolvedSymbol) {
  24374. summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
  24375. }
  24376. }
  24377. return summary;
  24378. };
  24379. return ToJsonSerializer;
  24380. }(ValueTransformer));
  24381. var ForJitSerializer = /** @class */ (function () {
  24382. function ForJitSerializer(outputCtx, symbolResolver, summaryResolver) {
  24383. this.outputCtx = outputCtx;
  24384. this.symbolResolver = symbolResolver;
  24385. this.summaryResolver = summaryResolver;
  24386. this.data = [];
  24387. }
  24388. ForJitSerializer.prototype.addSourceType = function (summary, metadata) {
  24389. this.data.push({ summary: summary, metadata: metadata, isLibrary: false });
  24390. };
  24391. ForJitSerializer.prototype.addLibType = function (summary) {
  24392. this.data.push({ summary: summary, metadata: null, isLibrary: true });
  24393. };
  24394. ForJitSerializer.prototype.serialize = function (exportAsArr) {
  24395. var _this = this;
  24396. var e_1, _a, e_2, _b, e_3, _c;
  24397. var exportAsBySymbol = new Map();
  24398. try {
  24399. for (var exportAsArr_1 = __values(exportAsArr), exportAsArr_1_1 = exportAsArr_1.next(); !exportAsArr_1_1.done; exportAsArr_1_1 = exportAsArr_1.next()) {
  24400. var _d = exportAsArr_1_1.value, symbol = _d.symbol, exportAs = _d.exportAs;
  24401. exportAsBySymbol.set(symbol, exportAs);
  24402. }
  24403. }
  24404. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  24405. finally {
  24406. try {
  24407. if (exportAsArr_1_1 && !exportAsArr_1_1.done && (_a = exportAsArr_1.return)) _a.call(exportAsArr_1);
  24408. }
  24409. finally { if (e_1) throw e_1.error; }
  24410. }
  24411. var ngModuleSymbols = new Set();
  24412. try {
  24413. for (var _e = __values(this.data), _f = _e.next(); !_f.done; _f = _e.next()) {
  24414. var _g = _f.value, summary = _g.summary, metadata = _g.metadata, isLibrary = _g.isLibrary;
  24415. if (summary.summaryKind === CompileSummaryKind.NgModule) {
  24416. // collect the symbols that refer to NgModule classes.
  24417. // Note: we can't just rely on `summary.type.summaryKind` to determine this as
  24418. // we don't add the summaries of all referenced symbols when we serialize type summaries.
  24419. // See serializeSummaries for details.
  24420. ngModuleSymbols.add(summary.type.reference);
  24421. var modSummary = summary;
  24422. try {
  24423. for (var _h = __values(modSummary.modules), _j = _h.next(); !_j.done; _j = _h.next()) {
  24424. var mod = _j.value;
  24425. ngModuleSymbols.add(mod.reference);
  24426. }
  24427. }
  24428. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  24429. finally {
  24430. try {
  24431. if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
  24432. }
  24433. finally { if (e_3) throw e_3.error; }
  24434. }
  24435. }
  24436. if (!isLibrary) {
  24437. var fnName = summaryForJitName(summary.type.reference.name);
  24438. createSummaryForJitFunction(this.outputCtx, summary.type.reference, this.serializeSummaryWithDeps(summary, metadata));
  24439. }
  24440. }
  24441. }
  24442. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  24443. finally {
  24444. try {
  24445. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  24446. }
  24447. finally { if (e_2) throw e_2.error; }
  24448. }
  24449. ngModuleSymbols.forEach(function (ngModuleSymbol) {
  24450. if (_this.summaryResolver.isLibraryFile(ngModuleSymbol.filePath)) {
  24451. var exportAs = exportAsBySymbol.get(ngModuleSymbol) || ngModuleSymbol.name;
  24452. var jitExportAsName = summaryForJitName(exportAs);
  24453. _this.outputCtx.statements.push(variable(jitExportAsName)
  24454. .set(_this.serializeSummaryRef(ngModuleSymbol))
  24455. .toDeclStmt(null, [StmtModifier.Exported]));
  24456. }
  24457. });
  24458. };
  24459. ForJitSerializer.prototype.serializeSummaryWithDeps = function (summary, metadata) {
  24460. var _this = this;
  24461. var expressions = [this.serializeSummary(summary)];
  24462. var providers = [];
  24463. if (metadata instanceof CompileNgModuleMetadata) {
  24464. expressions.push.apply(expressions, __spread(
  24465. // For directives / pipes, we only add the declared ones,
  24466. // and rely on transitively importing NgModules to get the transitive
  24467. // summaries.
  24468. metadata.declaredDirectives.concat(metadata.declaredPipes)
  24469. .map(function (type) { return type.reference; })
  24470. // For modules,
  24471. // we also add the summaries for modules
  24472. // from libraries.
  24473. // This is ok as we produce reexports for all transitive modules.
  24474. .concat(metadata.transitiveModule.modules.map(function (type) { return type.reference; })
  24475. .filter(function (ref) { return ref !== metadata.type.reference; }))
  24476. .map(function (ref) { return _this.serializeSummaryRef(ref); })));
  24477. // Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
  24478. // and we already have transitive modules.
  24479. providers = metadata.providers;
  24480. }
  24481. else if (summary.summaryKind === CompileSummaryKind.Directive) {
  24482. var dirSummary = summary;
  24483. providers = dirSummary.providers.concat(dirSummary.viewProviders);
  24484. }
  24485. // Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
  24486. // declaredDirectives / declaredPipes), as we allow
  24487. // providers without ctor arguments to skip the `@Injectable` decorator,
  24488. // i.e. we didn't generate .ngsummary.ts files for these.
  24489. expressions.push.apply(expressions, __spread(providers.filter(function (provider) { return !!provider.useClass; }).map(function (provider) { return _this.serializeSummary({
  24490. summaryKind: CompileSummaryKind.Injectable, type: provider.useClass
  24491. }); })));
  24492. return literalArr(expressions);
  24493. };
  24494. ForJitSerializer.prototype.serializeSummaryRef = function (typeSymbol) {
  24495. var jitImportedSymbol = this.symbolResolver.getStaticSymbol(summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
  24496. return this.outputCtx.importExpr(jitImportedSymbol);
  24497. };
  24498. ForJitSerializer.prototype.serializeSummary = function (data) {
  24499. var outputCtx = this.outputCtx;
  24500. var Transformer = /** @class */ (function () {
  24501. function Transformer() {
  24502. }
  24503. Transformer.prototype.visitArray = function (arr, context) {
  24504. var _this = this;
  24505. return literalArr(arr.map(function (entry) { return visitValue(entry, _this, context); }));
  24506. };
  24507. Transformer.prototype.visitStringMap = function (map, context) {
  24508. var _this = this;
  24509. return new LiteralMapExpr(Object.keys(map).map(function (key) { return new LiteralMapEntry(key, visitValue(map[key], _this, context), false); }));
  24510. };
  24511. Transformer.prototype.visitPrimitive = function (value, context) { return literal(value); };
  24512. Transformer.prototype.visitOther = function (value, context) {
  24513. if (value instanceof StaticSymbol) {
  24514. return outputCtx.importExpr(value);
  24515. }
  24516. else {
  24517. throw new Error("Illegal State: Encountered value " + value);
  24518. }
  24519. };
  24520. return Transformer;
  24521. }());
  24522. return visitValue(data, new Transformer(), null);
  24523. };
  24524. return ForJitSerializer;
  24525. }());
  24526. var FromJsonDeserializer = /** @class */ (function (_super) {
  24527. __extends(FromJsonDeserializer, _super);
  24528. function FromJsonDeserializer(symbolCache, summaryResolver) {
  24529. var _this = _super.call(this) || this;
  24530. _this.symbolCache = symbolCache;
  24531. _this.summaryResolver = summaryResolver;
  24532. return _this;
  24533. }
  24534. FromJsonDeserializer.prototype.deserialize = function (libraryFileName, json) {
  24535. var _this = this;
  24536. var data = JSON.parse(json);
  24537. var allImportAs = [];
  24538. this.symbols = data.symbols.map(function (serializedSymbol) { return _this.symbolCache.get(_this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name); });
  24539. data.symbols.forEach(function (serializedSymbol, index) {
  24540. var symbol = _this.symbols[index];
  24541. var importAs = serializedSymbol.importAs;
  24542. if (typeof importAs === 'number') {
  24543. allImportAs.push({ symbol: symbol, importAs: _this.symbols[importAs] });
  24544. }
  24545. else if (typeof importAs === 'string') {
  24546. allImportAs.push({ symbol: symbol, importAs: _this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
  24547. }
  24548. });
  24549. var summaries = visitValue(data.summaries, this, null);
  24550. return { moduleName: data.moduleName, summaries: summaries, importAs: allImportAs };
  24551. };
  24552. FromJsonDeserializer.prototype.visitStringMap = function (map, context) {
  24553. if ('__symbol' in map) {
  24554. var baseSymbol = this.symbols[map['__symbol']];
  24555. var members = map['members'];
  24556. return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
  24557. baseSymbol;
  24558. }
  24559. else {
  24560. return _super.prototype.visitStringMap.call(this, map, context);
  24561. }
  24562. };
  24563. return FromJsonDeserializer;
  24564. }(ValueTransformer));
  24565. function isCall(metadata) {
  24566. return metadata && metadata.__symbolic === 'call';
  24567. }
  24568. function isFunctionCall(metadata) {
  24569. return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
  24570. }
  24571. function isMethodCallOnVariable(metadata) {
  24572. return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
  24573. unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
  24574. }
  24575. /**
  24576. * @license
  24577. * Copyright Google Inc. All Rights Reserved.
  24578. *
  24579. * Use of this source code is governed by an MIT-style license that can be
  24580. * found in the LICENSE file at https://angular.io/license
  24581. */
  24582. var AotCompiler = /** @class */ (function () {
  24583. function AotCompiler(_config, _options, _host, reflector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _typeCheckCompiler, _ngModuleCompiler, _injectableCompiler, _outputEmitter, _summaryResolver, _symbolResolver) {
  24584. this._config = _config;
  24585. this._options = _options;
  24586. this._host = _host;
  24587. this.reflector = reflector;
  24588. this._metadataResolver = _metadataResolver;
  24589. this._templateParser = _templateParser;
  24590. this._styleCompiler = _styleCompiler;
  24591. this._viewCompiler = _viewCompiler;
  24592. this._typeCheckCompiler = _typeCheckCompiler;
  24593. this._ngModuleCompiler = _ngModuleCompiler;
  24594. this._injectableCompiler = _injectableCompiler;
  24595. this._outputEmitter = _outputEmitter;
  24596. this._summaryResolver = _summaryResolver;
  24597. this._symbolResolver = _symbolResolver;
  24598. this._templateAstCache = new Map();
  24599. this._analyzedFiles = new Map();
  24600. this._analyzedFilesForInjectables = new Map();
  24601. }
  24602. AotCompiler.prototype.clearCache = function () { this._metadataResolver.clearCache(); };
  24603. AotCompiler.prototype.analyzeModulesSync = function (rootFiles) {
  24604. var _this = this;
  24605. var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  24606. analyzeResult.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); });
  24607. return analyzeResult;
  24608. };
  24609. AotCompiler.prototype.analyzeModulesAsync = function (rootFiles) {
  24610. var _this = this;
  24611. var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  24612. return Promise
  24613. .all(analyzeResult.ngModules.map(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
  24614. .then(function () { return analyzeResult; });
  24615. };
  24616. AotCompiler.prototype._analyzeFile = function (fileName) {
  24617. var analyzedFile = this._analyzedFiles.get(fileName);
  24618. if (!analyzedFile) {
  24619. analyzedFile =
  24620. analyzeFile(this._host, this._symbolResolver, this._metadataResolver, fileName);
  24621. this._analyzedFiles.set(fileName, analyzedFile);
  24622. }
  24623. return analyzedFile;
  24624. };
  24625. AotCompiler.prototype._analyzeFileForInjectables = function (fileName) {
  24626. var analyzedFile = this._analyzedFilesForInjectables.get(fileName);
  24627. if (!analyzedFile) {
  24628. analyzedFile = analyzeFileForInjectables(this._host, this._symbolResolver, this._metadataResolver, fileName);
  24629. this._analyzedFilesForInjectables.set(fileName, analyzedFile);
  24630. }
  24631. return analyzedFile;
  24632. };
  24633. AotCompiler.prototype.findGeneratedFileNames = function (fileName) {
  24634. var _this = this;
  24635. var genFileNames = [];
  24636. var file = this._analyzeFile(fileName);
  24637. // Make sure we create a .ngfactory if we have a injectable/directive/pipe/NgModule
  24638. // or a reference to a non source file.
  24639. // Note: This is overestimating the required .ngfactory files as the real calculation is harder.
  24640. // Only do this for StubEmitFlags.Basic, as adding a type check block
  24641. // does not change this file (as we generate type check blocks based on NgModules).
  24642. if (this._options.allowEmptyCodegenFiles || file.directives.length || file.pipes.length ||
  24643. file.injectables.length || file.ngModules.length || file.exportsNonSourceFiles) {
  24644. genFileNames.push(ngfactoryFilePath(file.fileName, true));
  24645. if (this._options.enableSummariesForJit) {
  24646. genFileNames.push(summaryForJitFileName(file.fileName, true));
  24647. }
  24648. }
  24649. var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(file.fileName, true)[1]);
  24650. file.directives.forEach(function (dirSymbol) {
  24651. var compMeta = _this._metadataResolver.getNonNormalizedDirectiveMetadata(dirSymbol).metadata;
  24652. if (!compMeta.isComponent) {
  24653. return;
  24654. }
  24655. // Note: compMeta is a component and therefore template is non null.
  24656. compMeta.template.styleUrls.forEach(function (styleUrl) {
  24657. var normalizedUrl = _this._host.resourceNameToFileName(styleUrl, file.fileName);
  24658. if (!normalizedUrl) {
  24659. throw syntaxError("Couldn't resolve resource " + styleUrl + " relative to " + file.fileName);
  24660. }
  24661. var needsShim = (compMeta.template.encapsulation ||
  24662. _this._config.defaultEncapsulation) === ViewEncapsulation.Emulated;
  24663. genFileNames.push(_stylesModuleUrl(normalizedUrl, needsShim, fileSuffix));
  24664. if (_this._options.allowEmptyCodegenFiles) {
  24665. genFileNames.push(_stylesModuleUrl(normalizedUrl, !needsShim, fileSuffix));
  24666. }
  24667. });
  24668. });
  24669. return genFileNames;
  24670. };
  24671. AotCompiler.prototype.emitBasicStub = function (genFileName, originalFileName) {
  24672. var outputCtx = this._createOutputContext(genFileName);
  24673. if (genFileName.endsWith('.ngfactory.ts')) {
  24674. if (!originalFileName) {
  24675. throw new Error("Assertion error: require the original file for .ngfactory.ts stubs. File: " + genFileName);
  24676. }
  24677. var originalFile = this._analyzeFile(originalFileName);
  24678. this._createNgFactoryStub(outputCtx, originalFile, 1 /* Basic */);
  24679. }
  24680. else if (genFileName.endsWith('.ngsummary.ts')) {
  24681. if (this._options.enableSummariesForJit) {
  24682. if (!originalFileName) {
  24683. throw new Error("Assertion error: require the original file for .ngsummary.ts stubs. File: " + genFileName);
  24684. }
  24685. var originalFile = this._analyzeFile(originalFileName);
  24686. _createEmptyStub(outputCtx);
  24687. originalFile.ngModules.forEach(function (ngModule) {
  24688. // create exports that user code can reference
  24689. createForJitStub(outputCtx, ngModule.type.reference);
  24690. });
  24691. }
  24692. }
  24693. else if (genFileName.endsWith('.ngstyle.ts')) {
  24694. _createEmptyStub(outputCtx);
  24695. }
  24696. // Note: for the stubs, we don't need a property srcFileUrl,
  24697. // as later on in emitAllImpls we will create the proper GeneratedFiles with the
  24698. // correct srcFileUrl.
  24699. // This is good as e.g. for .ngstyle.ts files we can't derive
  24700. // the url of components based on the genFileUrl.
  24701. return this._codegenSourceModule('unknown', outputCtx);
  24702. };
  24703. AotCompiler.prototype.emitTypeCheckStub = function (genFileName, originalFileName) {
  24704. var originalFile = this._analyzeFile(originalFileName);
  24705. var outputCtx = this._createOutputContext(genFileName);
  24706. if (genFileName.endsWith('.ngfactory.ts')) {
  24707. this._createNgFactoryStub(outputCtx, originalFile, 2 /* TypeCheck */);
  24708. }
  24709. return outputCtx.statements.length > 0 ?
  24710. this._codegenSourceModule(originalFile.fileName, outputCtx) :
  24711. null;
  24712. };
  24713. AotCompiler.prototype.loadFilesAsync = function (fileNames, tsFiles) {
  24714. var _this = this;
  24715. var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
  24716. var loadingPromises = [];
  24717. files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) {
  24718. return loadingPromises.push(_this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false));
  24719. }); });
  24720. var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
  24721. return Promise.all(loadingPromises).then(function (_) { return ({
  24722. analyzedModules: mergeAndValidateNgFiles(files),
  24723. analyzedInjectables: analyzedInjectables,
  24724. }); });
  24725. };
  24726. AotCompiler.prototype.loadFilesSync = function (fileNames, tsFiles) {
  24727. var _this = this;
  24728. var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
  24729. files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); }); });
  24730. var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
  24731. return {
  24732. analyzedModules: mergeAndValidateNgFiles(files),
  24733. analyzedInjectables: analyzedInjectables,
  24734. };
  24735. };
  24736. AotCompiler.prototype._createNgFactoryStub = function (outputCtx, file, emitFlags) {
  24737. var _this = this;
  24738. var componentId = 0;
  24739. file.ngModules.forEach(function (ngModuleMeta, ngModuleIndex) {
  24740. // Note: the code below needs to executed for StubEmitFlags.Basic and StubEmitFlags.TypeCheck,
  24741. // so we don't change the .ngfactory file too much when adding the type-check block.
  24742. // create exports that user code can reference
  24743. _this._ngModuleCompiler.createStub(outputCtx, ngModuleMeta.type.reference);
  24744. // add references to the symbols from the metadata.
  24745. // These can be used by the type check block for components,
  24746. // and they also cause TypeScript to include these files into the program too,
  24747. // which will make them part of the analyzedFiles.
  24748. var externalReferences = __spread(ngModuleMeta.transitiveModule.directives.map(function (d) { return d.reference; }), ngModuleMeta.transitiveModule.pipes.map(function (d) { return d.reference; }), ngModuleMeta.importedModules.map(function (m) { return m.type.reference; }), ngModuleMeta.exportedModules.map(function (m) { return m.type.reference; }), _this._externalIdentifierReferences([Identifiers.TemplateRef, Identifiers.ElementRef]));
  24749. var externalReferenceVars = new Map();
  24750. externalReferences.forEach(function (ref, typeIndex) {
  24751. externalReferenceVars.set(ref, "_decl" + ngModuleIndex + "_" + typeIndex);
  24752. });
  24753. externalReferenceVars.forEach(function (varName, reference) {
  24754. outputCtx.statements.push(variable(varName)
  24755. .set(NULL_EXPR.cast(DYNAMIC_TYPE))
  24756. .toDeclStmt(expressionType(outputCtx.importExpr(reference, /* typeParams */ null, /* useSummaries */ false))));
  24757. });
  24758. if (emitFlags & 2 /* TypeCheck */) {
  24759. // add the type-check block for all components of the NgModule
  24760. ngModuleMeta.declaredDirectives.forEach(function (dirId) {
  24761. var compMeta = _this._metadataResolver.getDirectiveMetadata(dirId.reference);
  24762. if (!compMeta.isComponent) {
  24763. return;
  24764. }
  24765. componentId++;
  24766. _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_Host_" + componentId, ngModuleMeta, _this._metadataResolver.getHostComponentMetadata(compMeta), [compMeta.type], externalReferenceVars);
  24767. _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_" + componentId, ngModuleMeta, compMeta, ngModuleMeta.transitiveModule.directives, externalReferenceVars);
  24768. });
  24769. }
  24770. });
  24771. if (outputCtx.statements.length === 0) {
  24772. _createEmptyStub(outputCtx);
  24773. }
  24774. };
  24775. AotCompiler.prototype._externalIdentifierReferences = function (references) {
  24776. var e_1, _a;
  24777. var result = [];
  24778. try {
  24779. for (var references_1 = __values(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
  24780. var reference = references_1_1.value;
  24781. var token = createTokenForExternalReference(this.reflector, reference);
  24782. if (token.identifier) {
  24783. result.push(token.identifier.reference);
  24784. }
  24785. }
  24786. }
  24787. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  24788. finally {
  24789. try {
  24790. if (references_1_1 && !references_1_1.done && (_a = references_1.return)) _a.call(references_1);
  24791. }
  24792. finally { if (e_1) throw e_1.error; }
  24793. }
  24794. return result;
  24795. };
  24796. AotCompiler.prototype._createTypeCheckBlock = function (ctx, componentId, moduleMeta, compMeta, directives, externalReferenceVars) {
  24797. var _a;
  24798. var _b = this._parseTemplate(compMeta, moduleMeta, directives), parsedTemplate = _b.template, usedPipes = _b.pipes;
  24799. (_a = ctx.statements).push.apply(_a, __spread(this._typeCheckCompiler.compileComponent(componentId, compMeta, parsedTemplate, usedPipes, externalReferenceVars, ctx)));
  24800. };
  24801. AotCompiler.prototype.emitMessageBundle = function (analyzeResult, locale) {
  24802. var _this = this;
  24803. var errors = [];
  24804. var htmlParser = new HtmlParser();
  24805. // TODO(vicb): implicit tags & attributes
  24806. var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  24807. analyzeResult.files.forEach(function (file) {
  24808. var compMetas = [];
  24809. file.directives.forEach(function (directiveType) {
  24810. var dirMeta = _this._metadataResolver.getDirectiveMetadata(directiveType);
  24811. if (dirMeta && dirMeta.isComponent) {
  24812. compMetas.push(dirMeta);
  24813. }
  24814. });
  24815. compMetas.forEach(function (compMeta) {
  24816. var html = compMeta.template.template;
  24817. // Template URL points to either an HTML or TS file depending on whether
  24818. // the file is used with `templateUrl:` or `template:`, respectively.
  24819. var templateUrl = compMeta.template.templateUrl;
  24820. var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  24821. errors.push.apply(errors, __spread(messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig)));
  24822. });
  24823. });
  24824. if (errors.length) {
  24825. throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
  24826. }
  24827. return messageBundle;
  24828. };
  24829. AotCompiler.prototype.emitAllPartialModules = function (_a, r3Files) {
  24830. var _this = this;
  24831. var ngModuleByPipeOrDirective = _a.ngModuleByPipeOrDirective, files = _a.files;
  24832. var contextMap = new Map();
  24833. var getContext = function (fileName) {
  24834. if (!contextMap.has(fileName)) {
  24835. contextMap.set(fileName, _this._createOutputContext(fileName));
  24836. }
  24837. return contextMap.get(fileName);
  24838. };
  24839. files.forEach(function (file) { return _this._compilePartialModule(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables, getContext(file.fileName)); });
  24840. r3Files.forEach(function (file) { return _this._compileShallowModules(file.fileName, file.shallowModules, getContext(file.fileName)); });
  24841. return Array.from(contextMap.values())
  24842. .map(function (context) { return ({
  24843. fileName: context.genFilePath,
  24844. statements: __spread(context.constantPool.statements, context.statements),
  24845. }); });
  24846. };
  24847. AotCompiler.prototype._compileShallowModules = function (fileName, shallowModules, context) {
  24848. var _this = this;
  24849. shallowModules.forEach(function (module) { return compileNgModuleFromRender2(context, module, _this._injectableCompiler); });
  24850. };
  24851. AotCompiler.prototype._compilePartialModule = function (fileName, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables, context) {
  24852. var _this = this;
  24853. var errors = [];
  24854. var schemaRegistry = new DomElementSchemaRegistry();
  24855. var hostBindingParser = new BindingParser(this._templateParser.expressionParser, DEFAULT_INTERPOLATION_CONFIG, schemaRegistry, [], errors);
  24856. // Process all components and directives
  24857. directives.forEach(function (directiveType) {
  24858. var directiveMetadata = _this._metadataResolver.getDirectiveMetadata(directiveType);
  24859. if (directiveMetadata.isComponent) {
  24860. var module = ngModuleByPipeOrDirective.get(directiveType);
  24861. module ||
  24862. error("Cannot determine the module for component '" + identifierName(directiveMetadata.type) + "'");
  24863. var htmlAst = directiveMetadata.template.htmlAst;
  24864. var preserveWhitespaces = directiveMetadata.template.preserveWhitespaces;
  24865. if (!preserveWhitespaces) {
  24866. htmlAst = removeWhitespaces(htmlAst);
  24867. }
  24868. var render3Ast = htmlAstToRender3Ast(htmlAst.rootNodes, hostBindingParser);
  24869. // Map of StaticType by directive selectors
  24870. var directiveTypeBySel_1 = new Map();
  24871. var directives_1 = module.transitiveModule.directives.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  24872. directives_1.forEach(function (directive) {
  24873. if (directive.selector) {
  24874. directiveTypeBySel_1.set(directive.selector, directive.type.reference);
  24875. }
  24876. });
  24877. // Map of StaticType by pipe names
  24878. var pipeTypeByName_1 = new Map();
  24879. var pipes_1 = module.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  24880. pipes_1.forEach(function (pipe) { pipeTypeByName_1.set(pipe.name, pipe.type.reference); });
  24881. compileComponentFromRender2(context, directiveMetadata, render3Ast, _this.reflector, hostBindingParser, directiveTypeBySel_1, pipeTypeByName_1);
  24882. }
  24883. else {
  24884. compileDirectiveFromRender2(context, directiveMetadata, _this.reflector, hostBindingParser);
  24885. }
  24886. });
  24887. pipes.forEach(function (pipeType) {
  24888. var pipeMetadata = _this._metadataResolver.getPipeMetadata(pipeType);
  24889. if (pipeMetadata) {
  24890. compilePipeFromRender2(context, pipeMetadata, _this.reflector);
  24891. }
  24892. });
  24893. injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
  24894. };
  24895. AotCompiler.prototype.emitAllPartialModules2 = function (files) {
  24896. var _this = this;
  24897. // Using reduce like this is a select many pattern (where map is a select pattern)
  24898. return files.reduce(function (r, file) {
  24899. r.push.apply(r, __spread(_this._emitPartialModule2(file.fileName, file.injectables)));
  24900. return r;
  24901. }, []);
  24902. };
  24903. AotCompiler.prototype._emitPartialModule2 = function (fileName, injectables) {
  24904. var _this = this;
  24905. var context = this._createOutputContext(fileName);
  24906. injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
  24907. if (context.statements && context.statements.length > 0) {
  24908. return [{ fileName: fileName, statements: __spread(context.constantPool.statements, context.statements) }];
  24909. }
  24910. return [];
  24911. };
  24912. AotCompiler.prototype.emitAllImpls = function (analyzeResult) {
  24913. var _this = this;
  24914. var ngModuleByPipeOrDirective = analyzeResult.ngModuleByPipeOrDirective, files = analyzeResult.files;
  24915. var sourceModules = files.map(function (file) { return _this._compileImplFile(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables); });
  24916. return flatten(sourceModules);
  24917. };
  24918. AotCompiler.prototype._compileImplFile = function (srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
  24919. var _this = this;
  24920. var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
  24921. var generatedFiles = [];
  24922. var outputCtx = this._createOutputContext(ngfactoryFilePath(srcFileUrl, true));
  24923. generatedFiles.push.apply(generatedFiles, __spread(this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, outputCtx)));
  24924. // compile all ng modules
  24925. ngModules.forEach(function (ngModuleMeta) { return _this._compileModule(outputCtx, ngModuleMeta); });
  24926. // compile components
  24927. directives.forEach(function (dirType) {
  24928. var compMeta = _this._metadataResolver.getDirectiveMetadata(dirType);
  24929. if (!compMeta.isComponent) {
  24930. return;
  24931. }
  24932. var ngModule = ngModuleByPipeOrDirective.get(dirType);
  24933. if (!ngModule) {
  24934. throw new Error("Internal Error: cannot determine the module for component " + identifierName(compMeta.type) + "!");
  24935. }
  24936. // compile styles
  24937. var componentStylesheet = _this._styleCompiler.compileComponent(outputCtx, compMeta);
  24938. // Note: compMeta is a component and therefore template is non null.
  24939. compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
  24940. // Note: fill non shim and shim style files as they might
  24941. // be shared by component with and without ViewEncapsulation.
  24942. var shim = _this._styleCompiler.needsStyleShim(compMeta);
  24943. generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, shim, fileSuffix));
  24944. if (_this._options.allowEmptyCodegenFiles) {
  24945. generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, !shim, fileSuffix));
  24946. }
  24947. });
  24948. // compile components
  24949. var compViewVars = _this._compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives, componentStylesheet, fileSuffix);
  24950. _this._compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
  24951. });
  24952. if (outputCtx.statements.length > 0 || this._options.allowEmptyCodegenFiles) {
  24953. var srcModule = this._codegenSourceModule(srcFileUrl, outputCtx);
  24954. generatedFiles.unshift(srcModule);
  24955. }
  24956. return generatedFiles;
  24957. };
  24958. AotCompiler.prototype._createSummary = function (srcFileName, directives, pipes, ngModules, injectables, ngFactoryCtx) {
  24959. var _this = this;
  24960. var symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
  24961. .map(function (symbol) { return _this._symbolResolver.resolveSymbol(symbol); });
  24962. var typeData = __spread(ngModules.map(function (meta) { return ({
  24963. summary: _this._metadataResolver.getNgModuleSummary(meta.type.reference),
  24964. metadata: _this._metadataResolver.getNgModuleMetadata(meta.type.reference)
  24965. }); }), directives.map(function (ref) { return ({
  24966. summary: _this._metadataResolver.getDirectiveSummary(ref),
  24967. metadata: _this._metadataResolver.getDirectiveMetadata(ref)
  24968. }); }), pipes.map(function (ref) { return ({
  24969. summary: _this._metadataResolver.getPipeSummary(ref),
  24970. metadata: _this._metadataResolver.getPipeMetadata(ref)
  24971. }); }), injectables.map(function (ref) { return ({
  24972. summary: _this._metadataResolver.getInjectableSummary(ref.symbol),
  24973. metadata: _this._metadataResolver.getInjectableSummary(ref.symbol).type
  24974. }); }));
  24975. var forJitOutputCtx = this._options.enableSummariesForJit ?
  24976. this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
  24977. null;
  24978. var _a = serializeSummaries(srcFileName, forJitOutputCtx, this._summaryResolver, this._symbolResolver, symbolSummaries, typeData, this._options.createExternalSymbolFactoryReexports), json = _a.json, exportAs = _a.exportAs;
  24979. exportAs.forEach(function (entry) {
  24980. ngFactoryCtx.statements.push(variable(entry.exportAs).set(ngFactoryCtx.importExpr(entry.symbol)).toDeclStmt(null, [
  24981. StmtModifier.Exported
  24982. ]));
  24983. });
  24984. var summaryJson = new GeneratedFile(srcFileName, summaryFileName(srcFileName), json);
  24985. var result = [summaryJson];
  24986. if (forJitOutputCtx) {
  24987. result.push(this._codegenSourceModule(srcFileName, forJitOutputCtx));
  24988. }
  24989. return result;
  24990. };
  24991. AotCompiler.prototype._compileModule = function (outputCtx, ngModule) {
  24992. var providers = [];
  24993. if (this._options.locale) {
  24994. var normalizedLocale = this._options.locale.replace(/_/g, '-');
  24995. providers.push({
  24996. token: createTokenForExternalReference(this.reflector, Identifiers.LOCALE_ID),
  24997. useValue: normalizedLocale,
  24998. });
  24999. }
  25000. if (this._options.i18nFormat) {
  25001. providers.push({
  25002. token: createTokenForExternalReference(this.reflector, Identifiers.TRANSLATIONS_FORMAT),
  25003. useValue: this._options.i18nFormat
  25004. });
  25005. }
  25006. this._ngModuleCompiler.compile(outputCtx, ngModule, providers);
  25007. };
  25008. AotCompiler.prototype._compileComponentFactory = function (outputCtx, compMeta, ngModule, fileSuffix) {
  25009. var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta);
  25010. var hostViewFactoryVar = this._compileComponent(outputCtx, hostMeta, ngModule, [compMeta.type], null, fileSuffix)
  25011. .viewClassVar;
  25012. var compFactoryVar = componentFactoryName(compMeta.type.reference);
  25013. var inputsExprs = [];
  25014. for (var propName in compMeta.inputs) {
  25015. var templateName = compMeta.inputs[propName];
  25016. // Don't quote so that the key gets minified...
  25017. inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  25018. }
  25019. var outputsExprs = [];
  25020. for (var propName in compMeta.outputs) {
  25021. var templateName = compMeta.outputs[propName];
  25022. // Don't quote so that the key gets minified...
  25023. outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  25024. }
  25025. outputCtx.statements.push(variable(compFactoryVar)
  25026. .set(importExpr(Identifiers.createComponentFactory).callFn([
  25027. literal(compMeta.selector), outputCtx.importExpr(compMeta.type.reference),
  25028. variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
  25029. new LiteralMapExpr(outputsExprs),
  25030. literalArr(compMeta.template.ngContentSelectors.map(function (selector) { return literal(selector); }))
  25031. ]))
  25032. .toDeclStmt(importType(Identifiers.ComponentFactory, [expressionType(outputCtx.importExpr(compMeta.type.reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]));
  25033. };
  25034. AotCompiler.prototype._compileComponent = function (outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix) {
  25035. var _a = this._parseTemplate(compMeta, ngModule, directiveIdentifiers), parsedTemplate = _a.template, usedPipes = _a.pipes;
  25036. var stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
  25037. var viewResult = this._viewCompiler.compileComponent(outputCtx, compMeta, parsedTemplate, stylesExpr, usedPipes);
  25038. if (componentStyles) {
  25039. _resolveStyleStatements(this._symbolResolver, componentStyles, this._styleCompiler.needsStyleShim(compMeta), fileSuffix);
  25040. }
  25041. return viewResult;
  25042. };
  25043. AotCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
  25044. var _this = this;
  25045. if (this._templateAstCache.has(compMeta.type.reference)) {
  25046. return this._templateAstCache.get(compMeta.type.reference);
  25047. }
  25048. var preserveWhitespaces = compMeta.template.preserveWhitespaces;
  25049. var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  25050. var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  25051. var result = this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  25052. this._templateAstCache.set(compMeta.type.reference, result);
  25053. return result;
  25054. };
  25055. AotCompiler.prototype._createOutputContext = function (genFilePath) {
  25056. var _this = this;
  25057. var importExpr$1 = function (symbol, typeParams, useSummaries) {
  25058. if (typeParams === void 0) { typeParams = null; }
  25059. if (useSummaries === void 0) { useSummaries = true; }
  25060. if (!(symbol instanceof StaticSymbol)) {
  25061. throw new Error("Internal error: unknown identifier " + JSON.stringify(symbol));
  25062. }
  25063. var arity = _this._symbolResolver.getTypeArity(symbol) || 0;
  25064. var _a = _this._symbolResolver.getImportAs(symbol, useSummaries) || symbol, filePath = _a.filePath, name = _a.name, members = _a.members;
  25065. var importModule = _this._fileNameToModuleName(filePath, genFilePath);
  25066. // It should be good enough to compare filePath to genFilePath and if they are equal
  25067. // there is a self reference. However, ngfactory files generate to .ts but their
  25068. // symbols have .d.ts so a simple compare is insufficient. They should be canonical
  25069. // and is tracked by #17705.
  25070. var selfReference = _this._fileNameToModuleName(genFilePath, genFilePath);
  25071. var moduleName = importModule === selfReference ? null : importModule;
  25072. // If we are in a type expression that refers to a generic type then supply
  25073. // the required type parameters. If there were not enough type parameters
  25074. // supplied, supply any as the type. Outside a type expression the reference
  25075. // should not supply type parameters and be treated as a simple value reference
  25076. // to the constructor function itself.
  25077. var suppliedTypeParams = typeParams || [];
  25078. var missingTypeParamsCount = arity - suppliedTypeParams.length;
  25079. var allTypeParams = suppliedTypeParams.concat(new Array(missingTypeParamsCount).fill(DYNAMIC_TYPE));
  25080. return members.reduce(function (expr, memberName) { return expr.prop(memberName); }, importExpr(new ExternalReference(moduleName, name, null), allTypeParams));
  25081. };
  25082. return { statements: [], genFilePath: genFilePath, importExpr: importExpr$1, constantPool: new ConstantPool() };
  25083. };
  25084. AotCompiler.prototype._fileNameToModuleName = function (importedFilePath, containingFilePath) {
  25085. return this._summaryResolver.getKnownModuleName(importedFilePath) ||
  25086. this._symbolResolver.getKnownModuleName(importedFilePath) ||
  25087. this._host.fileNameToModuleName(importedFilePath, containingFilePath);
  25088. };
  25089. AotCompiler.prototype._codegenStyles = function (srcFileUrl, compMeta, stylesheetMetadata, isShimmed, fileSuffix) {
  25090. var outputCtx = this._createOutputContext(_stylesModuleUrl(stylesheetMetadata.moduleUrl, isShimmed, fileSuffix));
  25091. var compiledStylesheet = this._styleCompiler.compileStyles(outputCtx, compMeta, stylesheetMetadata, isShimmed);
  25092. _resolveStyleStatements(this._symbolResolver, compiledStylesheet, isShimmed, fileSuffix);
  25093. return this._codegenSourceModule(srcFileUrl, outputCtx);
  25094. };
  25095. AotCompiler.prototype._codegenSourceModule = function (srcFileUrl, ctx) {
  25096. return new GeneratedFile(srcFileUrl, ctx.genFilePath, ctx.statements);
  25097. };
  25098. AotCompiler.prototype.listLazyRoutes = function (entryRoute, analyzedModules) {
  25099. var e_2, _a, e_3, _b;
  25100. var self = this;
  25101. if (entryRoute) {
  25102. var symbol = parseLazyRoute(entryRoute, this.reflector).referencedModule;
  25103. return visitLazyRoute(symbol);
  25104. }
  25105. else if (analyzedModules) {
  25106. var allLazyRoutes = [];
  25107. try {
  25108. for (var _c = __values(analyzedModules.ngModules), _d = _c.next(); !_d.done; _d = _c.next()) {
  25109. var ngModule = _d.value;
  25110. var lazyRoutes = listLazyRoutes(ngModule, this.reflector);
  25111. try {
  25112. for (var lazyRoutes_1 = __values(lazyRoutes), lazyRoutes_1_1 = lazyRoutes_1.next(); !lazyRoutes_1_1.done; lazyRoutes_1_1 = lazyRoutes_1.next()) {
  25113. var lazyRoute = lazyRoutes_1_1.value;
  25114. allLazyRoutes.push(lazyRoute);
  25115. }
  25116. }
  25117. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  25118. finally {
  25119. try {
  25120. if (lazyRoutes_1_1 && !lazyRoutes_1_1.done && (_b = lazyRoutes_1.return)) _b.call(lazyRoutes_1);
  25121. }
  25122. finally { if (e_3) throw e_3.error; }
  25123. }
  25124. }
  25125. }
  25126. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  25127. finally {
  25128. try {
  25129. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  25130. }
  25131. finally { if (e_2) throw e_2.error; }
  25132. }
  25133. return allLazyRoutes;
  25134. }
  25135. else {
  25136. throw new Error("Either route or analyzedModules has to be specified!");
  25137. }
  25138. function visitLazyRoute(symbol, seenRoutes, allLazyRoutes) {
  25139. var e_4, _a;
  25140. if (seenRoutes === void 0) { seenRoutes = new Set(); }
  25141. if (allLazyRoutes === void 0) { allLazyRoutes = []; }
  25142. // Support pointing to default exports, but stop recursing there,
  25143. // as the StaticReflector does not yet support default exports.
  25144. if (seenRoutes.has(symbol) || !symbol.name) {
  25145. return allLazyRoutes;
  25146. }
  25147. seenRoutes.add(symbol);
  25148. var lazyRoutes = listLazyRoutes(self._metadataResolver.getNgModuleMetadata(symbol, true), self.reflector);
  25149. try {
  25150. for (var lazyRoutes_2 = __values(lazyRoutes), lazyRoutes_2_1 = lazyRoutes_2.next(); !lazyRoutes_2_1.done; lazyRoutes_2_1 = lazyRoutes_2.next()) {
  25151. var lazyRoute = lazyRoutes_2_1.value;
  25152. allLazyRoutes.push(lazyRoute);
  25153. visitLazyRoute(lazyRoute.referencedModule, seenRoutes, allLazyRoutes);
  25154. }
  25155. }
  25156. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  25157. finally {
  25158. try {
  25159. if (lazyRoutes_2_1 && !lazyRoutes_2_1.done && (_a = lazyRoutes_2.return)) _a.call(lazyRoutes_2);
  25160. }
  25161. finally { if (e_4) throw e_4.error; }
  25162. }
  25163. return allLazyRoutes;
  25164. }
  25165. };
  25166. return AotCompiler;
  25167. }());
  25168. function _createEmptyStub(outputCtx) {
  25169. // Note: We need to produce at least one import statement so that
  25170. // TypeScript knows that the file is an es6 module. Otherwise our generated
  25171. // exports / imports won't be emitted properly by TypeScript.
  25172. outputCtx.statements.push(importExpr(Identifiers.ComponentFactory).toStmt());
  25173. }
  25174. function _resolveStyleStatements(symbolResolver, compileResult, needsShim, fileSuffix) {
  25175. compileResult.dependencies.forEach(function (dep) {
  25176. dep.setValue(symbolResolver.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, needsShim, fileSuffix), dep.name));
  25177. });
  25178. }
  25179. function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
  25180. return "" + stylesheetUrl + (shim ? '.shim' : '') + ".ngstyle" + suffix;
  25181. }
  25182. function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  25183. var files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
  25184. return mergeAnalyzedFiles(files);
  25185. }
  25186. function analyzeAndValidateNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  25187. return validateAnalyzedModules(analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver));
  25188. }
  25189. function validateAnalyzedModules(analyzedModules) {
  25190. if (analyzedModules.symbolsMissingModule && analyzedModules.symbolsMissingModule.length) {
  25191. var messages = analyzedModules.symbolsMissingModule.map(function (s) {
  25192. return "Cannot determine the module for class " + s.name + " in " + s.filePath + "! Add " + s.name + " to the NgModule to fix it.";
  25193. });
  25194. throw syntaxError(messages.join('\n'));
  25195. }
  25196. return analyzedModules;
  25197. }
  25198. // Analyzes all of the program files,
  25199. // including files that are not part of the program
  25200. // but are referenced by an NgModule.
  25201. function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
  25202. var seenFiles = new Set();
  25203. var files = [];
  25204. var visitFile = function (fileName) {
  25205. if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
  25206. return false;
  25207. }
  25208. seenFiles.add(fileName);
  25209. var analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
  25210. files.push(analyzedFile);
  25211. analyzedFile.ngModules.forEach(function (ngModule) {
  25212. ngModule.transitiveModule.modules.forEach(function (modMeta) { return visitFile(modMeta.reference.filePath); });
  25213. });
  25214. };
  25215. fileNames.forEach(function (fileName) { return visitFile(fileName); });
  25216. return files;
  25217. }
  25218. function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
  25219. var directives = [];
  25220. var pipes = [];
  25221. var injectables = [];
  25222. var ngModules = [];
  25223. var hasDecorators = staticSymbolResolver.hasDecorators(fileName);
  25224. var exportsNonSourceFiles = false;
  25225. // Don't analyze .d.ts files that have no decorators as a shortcut
  25226. // to speed up the analysis. This prevents us from
  25227. // resolving the references in these files.
  25228. // Note: exportsNonSourceFiles is only needed when compiling with summaries,
  25229. // which is not the case when .d.ts files are treated as input files.
  25230. if (!fileName.endsWith('.d.ts') || hasDecorators) {
  25231. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  25232. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  25233. var symbolMeta = resolvedSymbol.metadata;
  25234. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  25235. return;
  25236. }
  25237. var isNgSymbol = false;
  25238. if (symbolMeta.__symbolic === 'class') {
  25239. if (metadataResolver.isDirective(symbol)) {
  25240. isNgSymbol = true;
  25241. directives.push(symbol);
  25242. }
  25243. else if (metadataResolver.isPipe(symbol)) {
  25244. isNgSymbol = true;
  25245. pipes.push(symbol);
  25246. }
  25247. else if (metadataResolver.isNgModule(symbol)) {
  25248. var ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
  25249. if (ngModule) {
  25250. isNgSymbol = true;
  25251. ngModules.push(ngModule);
  25252. }
  25253. }
  25254. else if (metadataResolver.isInjectable(symbol)) {
  25255. isNgSymbol = true;
  25256. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  25257. if (injectable) {
  25258. injectables.push(injectable);
  25259. }
  25260. }
  25261. }
  25262. if (!isNgSymbol) {
  25263. exportsNonSourceFiles =
  25264. exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
  25265. }
  25266. });
  25267. }
  25268. return {
  25269. fileName: fileName, directives: directives, pipes: pipes, ngModules: ngModules, injectables: injectables, exportsNonSourceFiles: exportsNonSourceFiles,
  25270. };
  25271. }
  25272. function analyzeFileForInjectables(host, staticSymbolResolver, metadataResolver, fileName) {
  25273. var injectables = [];
  25274. var shallowModules = [];
  25275. if (staticSymbolResolver.hasDecorators(fileName)) {
  25276. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  25277. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  25278. var symbolMeta = resolvedSymbol.metadata;
  25279. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  25280. return;
  25281. }
  25282. if (symbolMeta.__symbolic === 'class') {
  25283. if (metadataResolver.isInjectable(symbol)) {
  25284. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  25285. if (injectable) {
  25286. injectables.push(injectable);
  25287. }
  25288. }
  25289. else if (metadataResolver.isNgModule(symbol)) {
  25290. var module = metadataResolver.getShallowModuleMetadata(symbol);
  25291. if (module) {
  25292. shallowModules.push(module);
  25293. }
  25294. }
  25295. }
  25296. });
  25297. }
  25298. return { fileName: fileName, injectables: injectables, shallowModules: shallowModules };
  25299. }
  25300. function isValueExportingNonSourceFile(host, metadata) {
  25301. var exportsNonSourceFiles = false;
  25302. var Visitor = /** @class */ (function () {
  25303. function Visitor() {
  25304. }
  25305. Visitor.prototype.visitArray = function (arr, context) {
  25306. var _this = this;
  25307. arr.forEach(function (v) { return visitValue(v, _this, context); });
  25308. };
  25309. Visitor.prototype.visitStringMap = function (map, context) {
  25310. var _this = this;
  25311. Object.keys(map).forEach(function (key) { return visitValue(map[key], _this, context); });
  25312. };
  25313. Visitor.prototype.visitPrimitive = function (value, context) { };
  25314. Visitor.prototype.visitOther = function (value, context) {
  25315. if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
  25316. exportsNonSourceFiles = true;
  25317. }
  25318. };
  25319. return Visitor;
  25320. }());
  25321. visitValue(metadata, new Visitor(), null);
  25322. return exportsNonSourceFiles;
  25323. }
  25324. function mergeAnalyzedFiles(analyzedFiles) {
  25325. var allNgModules = [];
  25326. var ngModuleByPipeOrDirective = new Map();
  25327. var allPipesAndDirectives = new Set();
  25328. analyzedFiles.forEach(function (af) {
  25329. af.ngModules.forEach(function (ngModule) {
  25330. allNgModules.push(ngModule);
  25331. ngModule.declaredDirectives.forEach(function (d) { return ngModuleByPipeOrDirective.set(d.reference, ngModule); });
  25332. ngModule.declaredPipes.forEach(function (p) { return ngModuleByPipeOrDirective.set(p.reference, ngModule); });
  25333. });
  25334. af.directives.forEach(function (d) { return allPipesAndDirectives.add(d); });
  25335. af.pipes.forEach(function (p) { return allPipesAndDirectives.add(p); });
  25336. });
  25337. var symbolsMissingModule = [];
  25338. allPipesAndDirectives.forEach(function (ref) {
  25339. if (!ngModuleByPipeOrDirective.has(ref)) {
  25340. symbolsMissingModule.push(ref);
  25341. }
  25342. });
  25343. return {
  25344. ngModules: allNgModules,
  25345. ngModuleByPipeOrDirective: ngModuleByPipeOrDirective,
  25346. symbolsMissingModule: symbolsMissingModule,
  25347. files: analyzedFiles
  25348. };
  25349. }
  25350. function mergeAndValidateNgFiles(files) {
  25351. return validateAnalyzedModules(mergeAnalyzedFiles(files));
  25352. }
  25353. /**
  25354. * @license
  25355. * Copyright Google Inc. All Rights Reserved.
  25356. *
  25357. * Use of this source code is governed by an MIT-style license that can be
  25358. * found in the LICENSE file at https://angular.io/license
  25359. */
  25360. var FORMATTED_MESSAGE = 'ngFormattedMessage';
  25361. function indentStr(level) {
  25362. if (level <= 0)
  25363. return '';
  25364. if (level < 6)
  25365. return ['', ' ', ' ', ' ', ' ', ' '][level];
  25366. var half = indentStr(Math.floor(level / 2));
  25367. return half + half + (level % 2 === 1 ? ' ' : '');
  25368. }
  25369. function formatChain(chain, indent) {
  25370. if (indent === void 0) { indent = 0; }
  25371. if (!chain)
  25372. return '';
  25373. var position = chain.position ?
  25374. chain.position.fileName + "(" + (chain.position.line + 1) + "," + (chain.position.column + 1) + ")" :
  25375. '';
  25376. var prefix = position && indent === 0 ? position + ": " : '';
  25377. var postfix = position && indent !== 0 ? " at " + position : '';
  25378. var message = "" + prefix + chain.message + postfix;
  25379. return "" + indentStr(indent) + message + ((chain.next && ('\n' + formatChain(chain.next, indent + 2))) || '');
  25380. }
  25381. function formattedError(chain) {
  25382. var message = formatChain(chain) + '.';
  25383. var error = syntaxError(message);
  25384. error[FORMATTED_MESSAGE] = true;
  25385. error.chain = chain;
  25386. error.position = chain.position;
  25387. return error;
  25388. }
  25389. function isFormattedError(error) {
  25390. return !!error[FORMATTED_MESSAGE];
  25391. }
  25392. /**
  25393. * @license
  25394. * Copyright Google Inc. All Rights Reserved.
  25395. *
  25396. * Use of this source code is governed by an MIT-style license that can be
  25397. * found in the LICENSE file at https://angular.io/license
  25398. */
  25399. var ANGULAR_CORE = '@angular/core';
  25400. var ANGULAR_ROUTER = '@angular/router';
  25401. var HIDDEN_KEY = /^\$.*\$$/;
  25402. var IGNORE = {
  25403. __symbolic: 'ignore'
  25404. };
  25405. var USE_VALUE$1 = 'useValue';
  25406. var PROVIDE = 'provide';
  25407. var REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
  25408. var TYPEGUARD_POSTFIX = 'TypeGuard';
  25409. var USE_IF = 'UseIf';
  25410. function shouldIgnore(value) {
  25411. return value && value.__symbolic == 'ignore';
  25412. }
  25413. /**
  25414. * A static reflector implements enough of the Reflector API that is necessary to compile
  25415. * templates statically.
  25416. */
  25417. var StaticReflector = /** @class */ (function () {
  25418. function StaticReflector(summaryResolver, symbolResolver, knownMetadataClasses, knownMetadataFunctions, errorRecorder) {
  25419. var _this = this;
  25420. if (knownMetadataClasses === void 0) { knownMetadataClasses = []; }
  25421. if (knownMetadataFunctions === void 0) { knownMetadataFunctions = []; }
  25422. this.summaryResolver = summaryResolver;
  25423. this.symbolResolver = symbolResolver;
  25424. this.errorRecorder = errorRecorder;
  25425. this.annotationCache = new Map();
  25426. this.shallowAnnotationCache = new Map();
  25427. this.propertyCache = new Map();
  25428. this.parameterCache = new Map();
  25429. this.methodCache = new Map();
  25430. this.staticCache = new Map();
  25431. this.conversionMap = new Map();
  25432. this.resolvedExternalReferences = new Map();
  25433. this.annotationForParentClassWithSummaryKind = new Map();
  25434. this.initializeConversionMap();
  25435. knownMetadataClasses.forEach(function (kc) { return _this._registerDecoratorOrConstructor(_this.getStaticSymbol(kc.filePath, kc.name), kc.ctor); });
  25436. knownMetadataFunctions.forEach(function (kf) { return _this._registerFunction(_this.getStaticSymbol(kf.filePath, kf.name), kf.fn); });
  25437. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Directive, [createDirective, createComponent]);
  25438. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Pipe, [createPipe]);
  25439. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.NgModule, [createNgModule]);
  25440. this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
  25441. }
  25442. StaticReflector.prototype.componentModuleUrl = function (typeOrFunc) {
  25443. var staticSymbol = this.findSymbolDeclaration(typeOrFunc);
  25444. return this.symbolResolver.getResourcePath(staticSymbol);
  25445. };
  25446. StaticReflector.prototype.resolveExternalReference = function (ref, containingFile) {
  25447. var key = undefined;
  25448. if (!containingFile) {
  25449. key = ref.moduleName + ":" + ref.name;
  25450. var declarationSymbol_1 = this.resolvedExternalReferences.get(key);
  25451. if (declarationSymbol_1)
  25452. return declarationSymbol_1;
  25453. }
  25454. var refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
  25455. var declarationSymbol = this.findSymbolDeclaration(refSymbol);
  25456. if (!containingFile) {
  25457. this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
  25458. this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
  25459. }
  25460. if (key) {
  25461. this.resolvedExternalReferences.set(key, declarationSymbol);
  25462. }
  25463. return declarationSymbol;
  25464. };
  25465. StaticReflector.prototype.findDeclaration = function (moduleUrl, name, containingFile) {
  25466. return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
  25467. };
  25468. StaticReflector.prototype.tryFindDeclaration = function (moduleUrl, name, containingFile) {
  25469. var _this = this;
  25470. return this.symbolResolver.ignoreErrorsFor(function () { return _this.findDeclaration(moduleUrl, name, containingFile); });
  25471. };
  25472. StaticReflector.prototype.findSymbolDeclaration = function (symbol) {
  25473. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  25474. if (resolvedSymbol) {
  25475. var resolvedMetadata = resolvedSymbol.metadata;
  25476. if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
  25477. resolvedMetadata = resolvedMetadata.symbol;
  25478. }
  25479. if (resolvedMetadata instanceof StaticSymbol) {
  25480. return this.findSymbolDeclaration(resolvedSymbol.metadata);
  25481. }
  25482. }
  25483. return symbol;
  25484. };
  25485. StaticReflector.prototype.tryAnnotations = function (type) {
  25486. var originalRecorder = this.errorRecorder;
  25487. this.errorRecorder = function (error, fileName) { };
  25488. try {
  25489. return this.annotations(type);
  25490. }
  25491. finally {
  25492. this.errorRecorder = originalRecorder;
  25493. }
  25494. };
  25495. StaticReflector.prototype.annotations = function (type) {
  25496. var _this = this;
  25497. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators); }, this.annotationCache);
  25498. };
  25499. StaticReflector.prototype.shallowAnnotations = function (type) {
  25500. var _this = this;
  25501. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators, true); }, this.shallowAnnotationCache);
  25502. };
  25503. StaticReflector.prototype._annotations = function (type, simplify, annotationCache) {
  25504. var annotations = annotationCache.get(type);
  25505. if (!annotations) {
  25506. annotations = [];
  25507. var classMetadata = this.getTypeMetadata(type);
  25508. var parentType = this.findParentType(type, classMetadata);
  25509. if (parentType) {
  25510. var parentAnnotations = this.annotations(parentType);
  25511. annotations.push.apply(annotations, __spread(parentAnnotations));
  25512. }
  25513. var ownAnnotations_1 = [];
  25514. if (classMetadata['decorators']) {
  25515. ownAnnotations_1 = simplify(type, classMetadata['decorators']);
  25516. if (ownAnnotations_1) {
  25517. annotations.push.apply(annotations, __spread(ownAnnotations_1));
  25518. }
  25519. }
  25520. if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
  25521. this.summaryResolver.isLibraryFile(parentType.filePath)) {
  25522. var summary = this.summaryResolver.resolveSummary(parentType);
  25523. if (summary && summary.type) {
  25524. var requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
  25525. var typeHasRequiredAnnotation = requiredAnnotationTypes.some(function (requiredType) { return ownAnnotations_1.some(function (ann) { return requiredType.isTypeOf(ann); }); });
  25526. if (!typeHasRequiredAnnotation) {
  25527. 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",
  25528. /* summary */ undefined, "Please add a " + requiredAnnotationTypes.map(function (type) { return type.ngMetadataName; }).join(' or ') + " decorator to the class"), type), type);
  25529. }
  25530. }
  25531. }
  25532. annotationCache.set(type, annotations.filter(function (ann) { return !!ann; }));
  25533. }
  25534. return annotations;
  25535. };
  25536. StaticReflector.prototype.propMetadata = function (type) {
  25537. var _this = this;
  25538. var propMetadata = this.propertyCache.get(type);
  25539. if (!propMetadata) {
  25540. var classMetadata = this.getTypeMetadata(type);
  25541. propMetadata = {};
  25542. var parentType = this.findParentType(type, classMetadata);
  25543. if (parentType) {
  25544. var parentPropMetadata_1 = this.propMetadata(parentType);
  25545. Object.keys(parentPropMetadata_1).forEach(function (parentProp) {
  25546. propMetadata[parentProp] = parentPropMetadata_1[parentProp];
  25547. });
  25548. }
  25549. var members_1 = classMetadata['members'] || {};
  25550. Object.keys(members_1).forEach(function (propName) {
  25551. var propData = members_1[propName];
  25552. var prop = propData
  25553. .find(function (a) { return a['__symbolic'] == 'property' || a['__symbolic'] == 'method'; });
  25554. var decorators = [];
  25555. if (propMetadata[propName]) {
  25556. decorators.push.apply(decorators, __spread(propMetadata[propName]));
  25557. }
  25558. propMetadata[propName] = decorators;
  25559. if (prop && prop['decorators']) {
  25560. decorators.push.apply(decorators, __spread(_this.simplify(type, prop['decorators'])));
  25561. }
  25562. });
  25563. this.propertyCache.set(type, propMetadata);
  25564. }
  25565. return propMetadata;
  25566. };
  25567. StaticReflector.prototype.parameters = function (type) {
  25568. var _this = this;
  25569. if (!(type instanceof StaticSymbol)) {
  25570. this.reportError(new Error("parameters received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  25571. return [];
  25572. }
  25573. try {
  25574. var parameters_1 = this.parameterCache.get(type);
  25575. if (!parameters_1) {
  25576. var classMetadata = this.getTypeMetadata(type);
  25577. var parentType = this.findParentType(type, classMetadata);
  25578. var members = classMetadata ? classMetadata['members'] : null;
  25579. var ctorData = members ? members['__ctor__'] : null;
  25580. if (ctorData) {
  25581. var ctor = ctorData.find(function (a) { return a['__symbolic'] == 'constructor'; });
  25582. var rawParameterTypes = ctor['parameters'] || [];
  25583. var parameterDecorators_1 = this.simplify(type, ctor['parameterDecorators'] || []);
  25584. parameters_1 = [];
  25585. rawParameterTypes.forEach(function (rawParamType, index) {
  25586. var nestedResult = [];
  25587. var paramType = _this.trySimplify(type, rawParamType);
  25588. if (paramType)
  25589. nestedResult.push(paramType);
  25590. var decorators = parameterDecorators_1 ? parameterDecorators_1[index] : null;
  25591. if (decorators) {
  25592. nestedResult.push.apply(nestedResult, __spread(decorators));
  25593. }
  25594. parameters_1.push(nestedResult);
  25595. });
  25596. }
  25597. else if (parentType) {
  25598. parameters_1 = this.parameters(parentType);
  25599. }
  25600. if (!parameters_1) {
  25601. parameters_1 = [];
  25602. }
  25603. this.parameterCache.set(type, parameters_1);
  25604. }
  25605. return parameters_1;
  25606. }
  25607. catch (e) {
  25608. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  25609. throw e;
  25610. }
  25611. };
  25612. StaticReflector.prototype._methodNames = function (type) {
  25613. var methodNames = this.methodCache.get(type);
  25614. if (!methodNames) {
  25615. var classMetadata = this.getTypeMetadata(type);
  25616. methodNames = {};
  25617. var parentType = this.findParentType(type, classMetadata);
  25618. if (parentType) {
  25619. var parentMethodNames_1 = this._methodNames(parentType);
  25620. Object.keys(parentMethodNames_1).forEach(function (parentProp) {
  25621. methodNames[parentProp] = parentMethodNames_1[parentProp];
  25622. });
  25623. }
  25624. var members_2 = classMetadata['members'] || {};
  25625. Object.keys(members_2).forEach(function (propName) {
  25626. var propData = members_2[propName];
  25627. var isMethod = propData.some(function (a) { return a['__symbolic'] == 'method'; });
  25628. methodNames[propName] = methodNames[propName] || isMethod;
  25629. });
  25630. this.methodCache.set(type, methodNames);
  25631. }
  25632. return methodNames;
  25633. };
  25634. StaticReflector.prototype._staticMembers = function (type) {
  25635. var staticMembers = this.staticCache.get(type);
  25636. if (!staticMembers) {
  25637. var classMetadata = this.getTypeMetadata(type);
  25638. var staticMemberData = classMetadata['statics'] || {};
  25639. staticMembers = Object.keys(staticMemberData);
  25640. this.staticCache.set(type, staticMembers);
  25641. }
  25642. return staticMembers;
  25643. };
  25644. StaticReflector.prototype.findParentType = function (type, classMetadata) {
  25645. var parentType = this.trySimplify(type, classMetadata['extends']);
  25646. if (parentType instanceof StaticSymbol) {
  25647. return parentType;
  25648. }
  25649. };
  25650. StaticReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
  25651. if (!(type instanceof StaticSymbol)) {
  25652. this.reportError(new Error("hasLifecycleHook received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  25653. }
  25654. try {
  25655. return !!this._methodNames(type)[lcProperty];
  25656. }
  25657. catch (e) {
  25658. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  25659. throw e;
  25660. }
  25661. };
  25662. StaticReflector.prototype.guards = function (type) {
  25663. var e_1, _a;
  25664. if (!(type instanceof StaticSymbol)) {
  25665. this.reportError(new Error("guards received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  25666. return {};
  25667. }
  25668. var staticMembers = this._staticMembers(type);
  25669. var result = {};
  25670. try {
  25671. for (var staticMembers_1 = __values(staticMembers), staticMembers_1_1 = staticMembers_1.next(); !staticMembers_1_1.done; staticMembers_1_1 = staticMembers_1.next()) {
  25672. var name_1 = staticMembers_1_1.value;
  25673. if (name_1.endsWith(TYPEGUARD_POSTFIX)) {
  25674. var property = name_1.substr(0, name_1.length - TYPEGUARD_POSTFIX.length);
  25675. var value = void 0;
  25676. if (property.endsWith(USE_IF)) {
  25677. property = name_1.substr(0, property.length - USE_IF.length);
  25678. value = USE_IF;
  25679. }
  25680. else {
  25681. value = this.getStaticSymbol(type.filePath, type.name, [name_1]);
  25682. }
  25683. result[property] = value;
  25684. }
  25685. }
  25686. }
  25687. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  25688. finally {
  25689. try {
  25690. if (staticMembers_1_1 && !staticMembers_1_1.done && (_a = staticMembers_1.return)) _a.call(staticMembers_1);
  25691. }
  25692. finally { if (e_1) throw e_1.error; }
  25693. }
  25694. return result;
  25695. };
  25696. StaticReflector.prototype._registerDecoratorOrConstructor = function (type, ctor) {
  25697. this.conversionMap.set(type, function (context, args) { return new (ctor.bind.apply(ctor, __spread([void 0], args)))(); });
  25698. };
  25699. StaticReflector.prototype._registerFunction = function (type, fn) {
  25700. this.conversionMap.set(type, function (context, args) { return fn.apply(undefined, args); });
  25701. };
  25702. StaticReflector.prototype.initializeConversionMap = function () {
  25703. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
  25704. this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
  25705. this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
  25706. this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
  25707. this.ANALYZE_FOR_ENTRY_COMPONENTS =
  25708. this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
  25709. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  25710. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  25711. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  25712. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
  25713. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  25714. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
  25715. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
  25716. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
  25717. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
  25718. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
  25719. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
  25720. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
  25721. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
  25722. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
  25723. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
  25724. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
  25725. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
  25726. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
  25727. // Note: Some metadata classes can be used directly with Provider.deps.
  25728. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  25729. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  25730. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  25731. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  25732. };
  25733. /**
  25734. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  25735. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  25736. *
  25737. * @param declarationFile the absolute path of the file where the symbol is declared
  25738. * @param name the name of the type.
  25739. */
  25740. StaticReflector.prototype.getStaticSymbol = function (declarationFile, name, members) {
  25741. return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
  25742. };
  25743. /**
  25744. * Simplify but discard any errors
  25745. */
  25746. StaticReflector.prototype.trySimplify = function (context, value) {
  25747. var originalRecorder = this.errorRecorder;
  25748. this.errorRecorder = function (error, fileName) { };
  25749. var result = this.simplify(context, value);
  25750. this.errorRecorder = originalRecorder;
  25751. return result;
  25752. };
  25753. /** @internal */
  25754. StaticReflector.prototype.simplify = function (context, value, lazy) {
  25755. if (lazy === void 0) { lazy = false; }
  25756. var self = this;
  25757. var scope = BindingScope$1.empty;
  25758. var calling = new Map();
  25759. function simplifyInContext(context, value, depth, references) {
  25760. function resolveReferenceValue(staticSymbol) {
  25761. var resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
  25762. return resolvedSymbol ? resolvedSymbol.metadata : null;
  25763. }
  25764. function simplifyEagerly(value) {
  25765. return simplifyInContext(context, value, depth, 0);
  25766. }
  25767. function simplifyLazily(value) {
  25768. return simplifyInContext(context, value, depth, references + 1);
  25769. }
  25770. function simplifyNested(nestedContext, value) {
  25771. if (nestedContext === context) {
  25772. // If the context hasn't changed let the exception propagate unmodified.
  25773. return simplifyInContext(nestedContext, value, depth + 1, references);
  25774. }
  25775. try {
  25776. return simplifyInContext(nestedContext, value, depth + 1, references);
  25777. }
  25778. catch (e) {
  25779. if (isMetadataError(e)) {
  25780. // Propagate the message text up but add a message to the chain that explains how we got
  25781. // here.
  25782. // e.chain implies e.symbol
  25783. var summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
  25784. var summary = "'" + nestedContext.name + "' " + summaryMsg;
  25785. var chain = { message: summary, position: e.position, next: e.chain };
  25786. // TODO(chuckj): retrieve the position information indirectly from the collectors node
  25787. // map if the metadata is from a .ts file.
  25788. self.error({
  25789. message: e.message,
  25790. advise: e.advise,
  25791. context: e.context, chain: chain,
  25792. symbol: nestedContext
  25793. }, context);
  25794. }
  25795. else {
  25796. // It is probably an internal error.
  25797. throw e;
  25798. }
  25799. }
  25800. }
  25801. function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
  25802. if (targetFunction && targetFunction['__symbolic'] == 'function') {
  25803. if (calling.get(functionSymbol)) {
  25804. self.error({
  25805. message: 'Recursion is not supported',
  25806. summary: "called '" + functionSymbol.name + "' recursively",
  25807. value: targetFunction
  25808. }, functionSymbol);
  25809. }
  25810. try {
  25811. var value_1 = targetFunction['value'];
  25812. if (value_1 && (depth != 0 || value_1.__symbolic != 'error')) {
  25813. var parameters = targetFunction['parameters'];
  25814. var defaults = targetFunction.defaults;
  25815. args = args.map(function (arg) { return simplifyNested(context, arg); })
  25816. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  25817. if (defaults && defaults.length > args.length) {
  25818. args.push.apply(args, __spread(defaults.slice(args.length).map(function (value) { return simplify(value); })));
  25819. }
  25820. calling.set(functionSymbol, true);
  25821. var functionScope = BindingScope$1.build();
  25822. for (var i = 0; i < parameters.length; i++) {
  25823. functionScope.define(parameters[i], args[i]);
  25824. }
  25825. var oldScope = scope;
  25826. var result_1;
  25827. try {
  25828. scope = functionScope.done();
  25829. result_1 = simplifyNested(functionSymbol, value_1);
  25830. }
  25831. finally {
  25832. scope = oldScope;
  25833. }
  25834. return result_1;
  25835. }
  25836. }
  25837. finally {
  25838. calling.delete(functionSymbol);
  25839. }
  25840. }
  25841. if (depth === 0) {
  25842. // If depth is 0 we are evaluating the top level expression that is describing element
  25843. // decorator. In this case, it is a decorator we don't understand, such as a custom
  25844. // non-angular decorator, and we should just ignore it.
  25845. return IGNORE;
  25846. }
  25847. var position = undefined;
  25848. if (targetExpression && targetExpression.__symbolic == 'resolved') {
  25849. var line = targetExpression.line;
  25850. var character = targetExpression.character;
  25851. var fileName = targetExpression.fileName;
  25852. if (fileName != null && line != null && character != null) {
  25853. position = { fileName: fileName, line: line, column: character };
  25854. }
  25855. }
  25856. self.error({
  25857. message: FUNCTION_CALL_NOT_SUPPORTED,
  25858. context: functionSymbol,
  25859. value: targetFunction, position: position
  25860. }, context);
  25861. }
  25862. function simplify(expression) {
  25863. var e_2, _a, e_3, _b;
  25864. if (isPrimitive(expression)) {
  25865. return expression;
  25866. }
  25867. if (expression instanceof Array) {
  25868. var result_2 = [];
  25869. try {
  25870. for (var _c = __values(expression), _d = _c.next(); !_d.done; _d = _c.next()) {
  25871. var item = _d.value;
  25872. // Check for a spread expression
  25873. if (item && item.__symbolic === 'spread') {
  25874. // We call with references as 0 because we require the actual value and cannot
  25875. // tolerate a reference here.
  25876. var spreadArray = simplifyEagerly(item.expression);
  25877. if (Array.isArray(spreadArray)) {
  25878. try {
  25879. for (var spreadArray_1 = __values(spreadArray), spreadArray_1_1 = spreadArray_1.next(); !spreadArray_1_1.done; spreadArray_1_1 = spreadArray_1.next()) {
  25880. var spreadItem = spreadArray_1_1.value;
  25881. result_2.push(spreadItem);
  25882. }
  25883. }
  25884. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  25885. finally {
  25886. try {
  25887. if (spreadArray_1_1 && !spreadArray_1_1.done && (_b = spreadArray_1.return)) _b.call(spreadArray_1);
  25888. }
  25889. finally { if (e_3) throw e_3.error; }
  25890. }
  25891. continue;
  25892. }
  25893. }
  25894. var value_2 = simplify(item);
  25895. if (shouldIgnore(value_2)) {
  25896. continue;
  25897. }
  25898. result_2.push(value_2);
  25899. }
  25900. }
  25901. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  25902. finally {
  25903. try {
  25904. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  25905. }
  25906. finally { if (e_2) throw e_2.error; }
  25907. }
  25908. return result_2;
  25909. }
  25910. if (expression instanceof StaticSymbol) {
  25911. // Stop simplification at builtin symbols or if we are in a reference context and
  25912. // the symbol doesn't have members.
  25913. if (expression === self.injectionToken || self.conversionMap.has(expression) ||
  25914. (references > 0 && !expression.members.length)) {
  25915. return expression;
  25916. }
  25917. else {
  25918. var staticSymbol = expression;
  25919. var declarationValue = resolveReferenceValue(staticSymbol);
  25920. if (declarationValue != null) {
  25921. return simplifyNested(staticSymbol, declarationValue);
  25922. }
  25923. else {
  25924. return staticSymbol;
  25925. }
  25926. }
  25927. }
  25928. if (expression) {
  25929. if (expression['__symbolic']) {
  25930. var staticSymbol = void 0;
  25931. switch (expression['__symbolic']) {
  25932. case 'binop':
  25933. var left = simplify(expression['left']);
  25934. if (shouldIgnore(left))
  25935. return left;
  25936. var right = simplify(expression['right']);
  25937. if (shouldIgnore(right))
  25938. return right;
  25939. switch (expression['operator']) {
  25940. case '&&':
  25941. return left && right;
  25942. case '||':
  25943. return left || right;
  25944. case '|':
  25945. return left | right;
  25946. case '^':
  25947. return left ^ right;
  25948. case '&':
  25949. return left & right;
  25950. case '==':
  25951. return left == right;
  25952. case '!=':
  25953. return left != right;
  25954. case '===':
  25955. return left === right;
  25956. case '!==':
  25957. return left !== right;
  25958. case '<':
  25959. return left < right;
  25960. case '>':
  25961. return left > right;
  25962. case '<=':
  25963. return left <= right;
  25964. case '>=':
  25965. return left >= right;
  25966. case '<<':
  25967. return left << right;
  25968. case '>>':
  25969. return left >> right;
  25970. case '+':
  25971. return left + right;
  25972. case '-':
  25973. return left - right;
  25974. case '*':
  25975. return left * right;
  25976. case '/':
  25977. return left / right;
  25978. case '%':
  25979. return left % right;
  25980. }
  25981. return null;
  25982. case 'if':
  25983. var condition = simplify(expression['condition']);
  25984. return condition ? simplify(expression['thenExpression']) :
  25985. simplify(expression['elseExpression']);
  25986. case 'pre':
  25987. var operand = simplify(expression['operand']);
  25988. if (shouldIgnore(operand))
  25989. return operand;
  25990. switch (expression['operator']) {
  25991. case '+':
  25992. return operand;
  25993. case '-':
  25994. return -operand;
  25995. case '!':
  25996. return !operand;
  25997. case '~':
  25998. return ~operand;
  25999. }
  26000. return null;
  26001. case 'index':
  26002. var indexTarget = simplifyEagerly(expression['expression']);
  26003. var index = simplifyEagerly(expression['index']);
  26004. if (indexTarget && isPrimitive(index))
  26005. return indexTarget[index];
  26006. return null;
  26007. case 'select':
  26008. var member = expression['member'];
  26009. var selectContext = context;
  26010. var selectTarget = simplify(expression['expression']);
  26011. if (selectTarget instanceof StaticSymbol) {
  26012. var members = selectTarget.members.concat(member);
  26013. selectContext =
  26014. self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
  26015. var declarationValue = resolveReferenceValue(selectContext);
  26016. if (declarationValue != null) {
  26017. return simplifyNested(selectContext, declarationValue);
  26018. }
  26019. else {
  26020. return selectContext;
  26021. }
  26022. }
  26023. if (selectTarget && isPrimitive(member))
  26024. return simplifyNested(selectContext, selectTarget[member]);
  26025. return null;
  26026. case 'reference':
  26027. // Note: This only has to deal with variable references, as symbol references have
  26028. // been converted into 'resolved'
  26029. // in the StaticSymbolResolver.
  26030. var name_2 = expression['name'];
  26031. var localValue = scope.resolve(name_2);
  26032. if (localValue != BindingScope$1.missing) {
  26033. return localValue;
  26034. }
  26035. break;
  26036. case 'resolved':
  26037. try {
  26038. return simplify(expression.symbol);
  26039. }
  26040. catch (e) {
  26041. // If an error is reported evaluating the symbol record the position of the
  26042. // reference in the error so it can
  26043. // be reported in the error message generated from the exception.
  26044. if (isMetadataError(e) && expression.fileName != null &&
  26045. expression.line != null && expression.character != null) {
  26046. e.position = {
  26047. fileName: expression.fileName,
  26048. line: expression.line,
  26049. column: expression.character
  26050. };
  26051. }
  26052. throw e;
  26053. }
  26054. case 'class':
  26055. return context;
  26056. case 'function':
  26057. return context;
  26058. case 'new':
  26059. case 'call':
  26060. // Determine if the function is a built-in conversion
  26061. staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
  26062. if (staticSymbol instanceof StaticSymbol) {
  26063. if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
  26064. // if somebody calls new InjectionToken, don't create an InjectionToken,
  26065. // but rather return the symbol to which the InjectionToken is assigned to.
  26066. // OpaqueToken is supported too as it is required by the language service to
  26067. // support v4 and prior versions of Angular.
  26068. return context;
  26069. }
  26070. var argExpressions = expression['arguments'] || [];
  26071. var converter = self.conversionMap.get(staticSymbol);
  26072. if (converter) {
  26073. var args = argExpressions.map(function (arg) { return simplifyNested(context, arg); })
  26074. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  26075. return converter(context, args);
  26076. }
  26077. else {
  26078. // Determine if the function is one we can simplify.
  26079. var targetFunction = resolveReferenceValue(staticSymbol);
  26080. return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
  26081. }
  26082. }
  26083. return IGNORE;
  26084. case 'error':
  26085. var message = expression.message;
  26086. if (expression['line'] != null) {
  26087. self.error({
  26088. message: message,
  26089. context: expression.context,
  26090. value: expression,
  26091. position: {
  26092. fileName: expression['fileName'],
  26093. line: expression['line'],
  26094. column: expression['character']
  26095. }
  26096. }, context);
  26097. }
  26098. else {
  26099. self.error({ message: message, context: expression.context }, context);
  26100. }
  26101. return IGNORE;
  26102. case 'ignore':
  26103. return expression;
  26104. }
  26105. return null;
  26106. }
  26107. return mapStringMap(expression, function (value, name) {
  26108. if (REFERENCE_SET.has(name)) {
  26109. if (name === USE_VALUE$1 && PROVIDE in expression) {
  26110. // If this is a provider expression, check for special tokens that need the value
  26111. // during analysis.
  26112. var provide = simplify(expression.provide);
  26113. if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
  26114. return simplify(value);
  26115. }
  26116. }
  26117. return simplifyLazily(value);
  26118. }
  26119. return simplify(value);
  26120. });
  26121. }
  26122. return IGNORE;
  26123. }
  26124. return simplify(value);
  26125. }
  26126. var result;
  26127. try {
  26128. result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
  26129. }
  26130. catch (e) {
  26131. if (this.errorRecorder) {
  26132. this.reportError(e, context);
  26133. }
  26134. else {
  26135. throw formatMetadataError(e, context);
  26136. }
  26137. }
  26138. if (shouldIgnore(result)) {
  26139. return undefined;
  26140. }
  26141. return result;
  26142. };
  26143. StaticReflector.prototype.getTypeMetadata = function (type) {
  26144. var resolvedSymbol = this.symbolResolver.resolveSymbol(type);
  26145. return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
  26146. { __symbolic: 'class' };
  26147. };
  26148. StaticReflector.prototype.reportError = function (error, context, path) {
  26149. if (this.errorRecorder) {
  26150. this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
  26151. }
  26152. else {
  26153. throw error;
  26154. }
  26155. };
  26156. StaticReflector.prototype.error = function (_a, reportingContext) {
  26157. var message = _a.message, summary = _a.summary, advise = _a.advise, position = _a.position, context = _a.context, value = _a.value, symbol = _a.symbol, chain = _a.chain;
  26158. this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
  26159. };
  26160. return StaticReflector;
  26161. }());
  26162. var METADATA_ERROR = 'ngMetadataError';
  26163. function metadataError(message, summary, advise, position, symbol, context, chain) {
  26164. var error = syntaxError(message);
  26165. error[METADATA_ERROR] = true;
  26166. if (advise)
  26167. error.advise = advise;
  26168. if (position)
  26169. error.position = position;
  26170. if (summary)
  26171. error.summary = summary;
  26172. if (context)
  26173. error.context = context;
  26174. if (chain)
  26175. error.chain = chain;
  26176. if (symbol)
  26177. error.symbol = symbol;
  26178. return error;
  26179. }
  26180. function isMetadataError(error) {
  26181. return !!error[METADATA_ERROR];
  26182. }
  26183. var REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
  26184. var VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
  26185. var DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
  26186. var COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
  26187. var FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
  26188. var REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
  26189. var LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
  26190. function expandedMessage(message, context) {
  26191. switch (message) {
  26192. case REFERENCE_TO_NONEXPORTED_CLASS:
  26193. if (context && context.className) {
  26194. return "References to a non-exported class are not supported in decorators but " + context.className + " was referenced.";
  26195. }
  26196. break;
  26197. case VARIABLE_NOT_INITIALIZED:
  26198. return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
  26199. case DESTRUCTURE_NOT_SUPPORTED:
  26200. return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
  26201. case COULD_NOT_RESOLVE_TYPE:
  26202. if (context && context.typeName) {
  26203. return "Could not resolve type " + context.typeName;
  26204. }
  26205. break;
  26206. case FUNCTION_CALL_NOT_SUPPORTED:
  26207. if (context && context.name) {
  26208. return "Function calls are not supported in decorators but '" + context.name + "' was called";
  26209. }
  26210. return 'Function calls are not supported in decorators';
  26211. case REFERENCE_TO_LOCAL_SYMBOL:
  26212. if (context && context.name) {
  26213. return "Reference to a local (non-exported) symbols are not supported in decorators but '" + context.name + "' was referenced";
  26214. }
  26215. break;
  26216. case LAMBDA_NOT_SUPPORTED:
  26217. return "Function expressions are not supported in decorators";
  26218. }
  26219. return message;
  26220. }
  26221. function messageAdvise(message, context) {
  26222. switch (message) {
  26223. case REFERENCE_TO_NONEXPORTED_CLASS:
  26224. if (context && context.className) {
  26225. return "Consider exporting '" + context.className + "'";
  26226. }
  26227. break;
  26228. case DESTRUCTURE_NOT_SUPPORTED:
  26229. return 'Consider simplifying to avoid destructuring';
  26230. case REFERENCE_TO_LOCAL_SYMBOL:
  26231. if (context && context.name) {
  26232. return "Consider exporting '" + context.name + "'";
  26233. }
  26234. break;
  26235. case LAMBDA_NOT_SUPPORTED:
  26236. return "Consider changing the function expression into an exported function";
  26237. }
  26238. return undefined;
  26239. }
  26240. function errorSummary(error) {
  26241. if (error.summary) {
  26242. return error.summary;
  26243. }
  26244. switch (error.message) {
  26245. case REFERENCE_TO_NONEXPORTED_CLASS:
  26246. if (error.context && error.context.className) {
  26247. return "references non-exported class " + error.context.className;
  26248. }
  26249. break;
  26250. case VARIABLE_NOT_INITIALIZED:
  26251. return 'is not initialized';
  26252. case DESTRUCTURE_NOT_SUPPORTED:
  26253. return 'is a destructured variable';
  26254. case COULD_NOT_RESOLVE_TYPE:
  26255. return 'could not be resolved';
  26256. case FUNCTION_CALL_NOT_SUPPORTED:
  26257. if (error.context && error.context.name) {
  26258. return "calls '" + error.context.name + "'";
  26259. }
  26260. return "calls a function";
  26261. case REFERENCE_TO_LOCAL_SYMBOL:
  26262. if (error.context && error.context.name) {
  26263. return "references local variable " + error.context.name;
  26264. }
  26265. return "references a local variable";
  26266. }
  26267. return 'contains the error';
  26268. }
  26269. function mapStringMap(input, transform) {
  26270. if (!input)
  26271. return {};
  26272. var result = {};
  26273. Object.keys(input).forEach(function (key) {
  26274. var value = transform(input[key], key);
  26275. if (!shouldIgnore(value)) {
  26276. if (HIDDEN_KEY.test(key)) {
  26277. Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
  26278. }
  26279. else {
  26280. result[key] = value;
  26281. }
  26282. }
  26283. });
  26284. return result;
  26285. }
  26286. function isPrimitive(o) {
  26287. return o === null || (typeof o !== 'function' && typeof o !== 'object');
  26288. }
  26289. var BindingScope$1 = /** @class */ (function () {
  26290. function BindingScope() {
  26291. }
  26292. BindingScope.build = function () {
  26293. var current = new Map();
  26294. return {
  26295. define: function (name, value) {
  26296. current.set(name, value);
  26297. return this;
  26298. },
  26299. done: function () {
  26300. return current.size > 0 ? new PopulatedScope(current) : BindingScope.empty;
  26301. }
  26302. };
  26303. };
  26304. BindingScope.missing = {};
  26305. BindingScope.empty = { resolve: function (name) { return BindingScope.missing; } };
  26306. return BindingScope;
  26307. }());
  26308. var PopulatedScope = /** @class */ (function (_super) {
  26309. __extends(PopulatedScope, _super);
  26310. function PopulatedScope(bindings) {
  26311. var _this = _super.call(this) || this;
  26312. _this.bindings = bindings;
  26313. return _this;
  26314. }
  26315. PopulatedScope.prototype.resolve = function (name) {
  26316. return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
  26317. };
  26318. return PopulatedScope;
  26319. }(BindingScope$1));
  26320. function formatMetadataMessageChain(chain, advise) {
  26321. var expanded = expandedMessage(chain.message, chain.context);
  26322. var nesting = chain.symbol ? " in '" + chain.symbol.name + "'" : '';
  26323. var message = "" + expanded + nesting;
  26324. var position = chain.position;
  26325. var next = chain.next ?
  26326. formatMetadataMessageChain(chain.next, advise) :
  26327. advise ? { message: advise } : undefined;
  26328. return { message: message, position: position, next: next };
  26329. }
  26330. function formatMetadataError(e, context) {
  26331. if (isMetadataError(e)) {
  26332. // Produce a formatted version of the and leaving enough information in the original error
  26333. // to recover the formatting information to eventually produce a diagnostic error message.
  26334. var position = e.position;
  26335. var chain = {
  26336. message: "Error during template compile of '" + context.name + "'",
  26337. position: position,
  26338. next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
  26339. };
  26340. var advise = e.advise || messageAdvise(e.message, e.context);
  26341. return formattedError(formatMetadataMessageChain(chain, advise));
  26342. }
  26343. return e;
  26344. }
  26345. /**
  26346. * @license
  26347. * Copyright Google Inc. All Rights Reserved.
  26348. *
  26349. * Use of this source code is governed by an MIT-style license that can be
  26350. * found in the LICENSE file at https://angular.io/license
  26351. */
  26352. var AotSummaryResolver = /** @class */ (function () {
  26353. function AotSummaryResolver(host, staticSymbolCache) {
  26354. this.host = host;
  26355. this.staticSymbolCache = staticSymbolCache;
  26356. // Note: this will only contain StaticSymbols without members!
  26357. this.summaryCache = new Map();
  26358. this.loadedFilePaths = new Map();
  26359. // Note: this will only contain StaticSymbols without members!
  26360. this.importAs = new Map();
  26361. this.knownFileNameToModuleNames = new Map();
  26362. }
  26363. AotSummaryResolver.prototype.isLibraryFile = function (filePath) {
  26364. // Note: We need to strip the .ngfactory. file path,
  26365. // so this method also works for generated files
  26366. // (for which host.isSourceFile will always return false).
  26367. return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
  26368. };
  26369. AotSummaryResolver.prototype.toSummaryFileName = function (filePath, referringSrcFileName) {
  26370. return this.host.toSummaryFileName(filePath, referringSrcFileName);
  26371. };
  26372. AotSummaryResolver.prototype.fromSummaryFileName = function (fileName, referringLibFileName) {
  26373. return this.host.fromSummaryFileName(fileName, referringLibFileName);
  26374. };
  26375. AotSummaryResolver.prototype.resolveSummary = function (staticSymbol) {
  26376. var rootSymbol = staticSymbol.members.length ?
  26377. this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
  26378. staticSymbol;
  26379. var summary = this.summaryCache.get(rootSymbol);
  26380. if (!summary) {
  26381. this._loadSummaryFile(staticSymbol.filePath);
  26382. summary = this.summaryCache.get(staticSymbol);
  26383. }
  26384. return (rootSymbol === staticSymbol && summary) || null;
  26385. };
  26386. AotSummaryResolver.prototype.getSymbolsOf = function (filePath) {
  26387. if (this._loadSummaryFile(filePath)) {
  26388. return Array.from(this.summaryCache.keys()).filter(function (symbol) { return symbol.filePath === filePath; });
  26389. }
  26390. return null;
  26391. };
  26392. AotSummaryResolver.prototype.getImportAs = function (staticSymbol) {
  26393. staticSymbol.assertNoMembers();
  26394. return this.importAs.get(staticSymbol);
  26395. };
  26396. /**
  26397. * Converts a file path to a module name that can be used as an `import`.
  26398. */
  26399. AotSummaryResolver.prototype.getKnownModuleName = function (importedFilePath) {
  26400. return this.knownFileNameToModuleNames.get(importedFilePath) || null;
  26401. };
  26402. AotSummaryResolver.prototype.addSummary = function (summary) { this.summaryCache.set(summary.symbol, summary); };
  26403. AotSummaryResolver.prototype._loadSummaryFile = function (filePath) {
  26404. var _this = this;
  26405. var hasSummary = this.loadedFilePaths.get(filePath);
  26406. if (hasSummary != null) {
  26407. return hasSummary;
  26408. }
  26409. var json = null;
  26410. if (this.isLibraryFile(filePath)) {
  26411. var summaryFilePath = summaryFileName(filePath);
  26412. try {
  26413. json = this.host.loadSummary(summaryFilePath);
  26414. }
  26415. catch (e) {
  26416. console.error("Error loading summary file " + summaryFilePath);
  26417. throw e;
  26418. }
  26419. }
  26420. hasSummary = json != null;
  26421. this.loadedFilePaths.set(filePath, hasSummary);
  26422. if (json) {
  26423. var _a = deserializeSummaries(this.staticSymbolCache, this, filePath, json), moduleName = _a.moduleName, summaries = _a.summaries, importAs = _a.importAs;
  26424. summaries.forEach(function (summary) { return _this.summaryCache.set(summary.symbol, summary); });
  26425. if (moduleName) {
  26426. this.knownFileNameToModuleNames.set(filePath, moduleName);
  26427. }
  26428. importAs.forEach(function (importAs) { _this.importAs.set(importAs.symbol, importAs.importAs); });
  26429. }
  26430. return hasSummary;
  26431. };
  26432. return AotSummaryResolver;
  26433. }());
  26434. /**
  26435. * @license
  26436. * Copyright Google Inc. All Rights Reserved.
  26437. *
  26438. * Use of this source code is governed by an MIT-style license that can be
  26439. * found in the LICENSE file at https://angular.io/license
  26440. */
  26441. function createAotUrlResolver(host) {
  26442. return {
  26443. resolve: function (basePath, url) {
  26444. var filePath = host.resourceNameToFileName(url, basePath);
  26445. if (!filePath) {
  26446. throw syntaxError("Couldn't resolve resource " + url + " from " + basePath);
  26447. }
  26448. return filePath;
  26449. }
  26450. };
  26451. }
  26452. /**
  26453. * Creates a new AotCompiler based on options and a host.
  26454. */
  26455. function createAotCompiler(compilerHost, options, errorCollector) {
  26456. var translations = options.translations || '';
  26457. var urlResolver = createAotUrlResolver(compilerHost);
  26458. var symbolCache = new StaticSymbolCache();
  26459. var summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
  26460. var symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
  26461. var staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector);
  26462. var htmlParser;
  26463. if (!!options.enableIvy) {
  26464. // Ivy handles i18n at the compiler level so we must use a regular parser
  26465. htmlParser = new HtmlParser();
  26466. }
  26467. else {
  26468. htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console);
  26469. }
  26470. var config = new CompilerConfig({
  26471. defaultEncapsulation: ViewEncapsulation.Emulated,
  26472. useJit: false,
  26473. missingTranslation: options.missingTranslation,
  26474. preserveWhitespaces: options.preserveWhitespaces,
  26475. strictInjectionParameters: options.strictInjectionParameters,
  26476. });
  26477. var normalizer = new DirectiveNormalizer({ get: function (url) { return compilerHost.loadResource(url); } }, urlResolver, htmlParser, config);
  26478. var expressionParser = new Parser$1(new Lexer());
  26479. var elementSchemaRegistry = new DomElementSchemaRegistry();
  26480. var tmplParser = new TemplateParser(config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []);
  26481. var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector);
  26482. // TODO(vicb): do not pass options.i18nFormat here
  26483. var viewCompiler = new ViewCompiler(staticReflector);
  26484. var typeCheckCompiler = new TypeCheckCompiler(options, staticReflector);
  26485. var 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);
  26486. return { compiler: compiler, reflector: staticReflector };
  26487. }
  26488. var SummaryResolver = /** @class */ (function () {
  26489. function SummaryResolver() {
  26490. }
  26491. return SummaryResolver;
  26492. }());
  26493. var JitSummaryResolver = /** @class */ (function () {
  26494. function JitSummaryResolver() {
  26495. this._summaries = new Map();
  26496. }
  26497. JitSummaryResolver.prototype.isLibraryFile = function () { return false; };
  26498. JitSummaryResolver.prototype.toSummaryFileName = function (fileName) { return fileName; };
  26499. JitSummaryResolver.prototype.fromSummaryFileName = function (fileName) { return fileName; };
  26500. JitSummaryResolver.prototype.resolveSummary = function (reference) {
  26501. return this._summaries.get(reference) || null;
  26502. };
  26503. JitSummaryResolver.prototype.getSymbolsOf = function () { return []; };
  26504. JitSummaryResolver.prototype.getImportAs = function (reference) { return reference; };
  26505. JitSummaryResolver.prototype.getKnownModuleName = function (fileName) { return null; };
  26506. JitSummaryResolver.prototype.addSummary = function (summary) { this._summaries.set(summary.symbol, summary); };
  26507. return JitSummaryResolver;
  26508. }());
  26509. /**
  26510. * @license
  26511. * Copyright Google Inc. All Rights Reserved.
  26512. *
  26513. * Use of this source code is governed by an MIT-style license that can be
  26514. * found in the LICENSE file at https://angular.io/license
  26515. */
  26516. function interpretStatements(statements, reflector) {
  26517. var ctx = new _ExecutionContext(null, null, null, new Map());
  26518. var visitor = new StatementInterpreter(reflector);
  26519. visitor.visitAllStatements(statements, ctx);
  26520. var result = {};
  26521. ctx.exports.forEach(function (exportName) { result[exportName] = ctx.vars.get(exportName); });
  26522. return result;
  26523. }
  26524. function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
  26525. var childCtx = ctx.createChildWihtLocalVars();
  26526. for (var i = 0; i < varNames.length; i++) {
  26527. childCtx.vars.set(varNames[i], varValues[i]);
  26528. }
  26529. var result = visitor.visitAllStatements(statements, childCtx);
  26530. return result ? result.value : null;
  26531. }
  26532. var _ExecutionContext = /** @class */ (function () {
  26533. function _ExecutionContext(parent, instance, className, vars) {
  26534. this.parent = parent;
  26535. this.instance = instance;
  26536. this.className = className;
  26537. this.vars = vars;
  26538. this.exports = [];
  26539. }
  26540. _ExecutionContext.prototype.createChildWihtLocalVars = function () {
  26541. return new _ExecutionContext(this, this.instance, this.className, new Map());
  26542. };
  26543. return _ExecutionContext;
  26544. }());
  26545. var ReturnValue = /** @class */ (function () {
  26546. function ReturnValue(value) {
  26547. this.value = value;
  26548. }
  26549. return ReturnValue;
  26550. }());
  26551. function createDynamicClass(_classStmt, _ctx, _visitor) {
  26552. var propertyDescriptors = {};
  26553. _classStmt.getters.forEach(function (getter) {
  26554. // Note: use `function` instead of arrow function to capture `this`
  26555. propertyDescriptors[getter.name] = {
  26556. configurable: false,
  26557. get: function () {
  26558. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  26559. return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
  26560. }
  26561. };
  26562. });
  26563. _classStmt.methods.forEach(function (method) {
  26564. var paramNames = method.params.map(function (param) { return param.name; });
  26565. // Note: use `function` instead of arrow function to capture `this`
  26566. propertyDescriptors[method.name] = {
  26567. writable: false,
  26568. configurable: false,
  26569. value: function () {
  26570. var args = [];
  26571. for (var _i = 0; _i < arguments.length; _i++) {
  26572. args[_i] = arguments[_i];
  26573. }
  26574. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  26575. return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
  26576. }
  26577. };
  26578. });
  26579. var ctorParamNames = _classStmt.constructorMethod.params.map(function (param) { return param.name; });
  26580. // Note: use `function` instead of arrow function to capture `this`
  26581. var ctor = function () {
  26582. var _this = this;
  26583. var args = [];
  26584. for (var _i = 0; _i < arguments.length; _i++) {
  26585. args[_i] = arguments[_i];
  26586. }
  26587. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  26588. _classStmt.fields.forEach(function (field) { _this[field.name] = undefined; });
  26589. _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
  26590. };
  26591. var superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
  26592. ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
  26593. return ctor;
  26594. }
  26595. var StatementInterpreter = /** @class */ (function () {
  26596. function StatementInterpreter(reflector) {
  26597. this.reflector = reflector;
  26598. }
  26599. StatementInterpreter.prototype.debugAst = function (ast) { return debugOutputAstAsTypeScript(ast); };
  26600. StatementInterpreter.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  26601. var initialValue = stmt.value ? stmt.value.visitExpression(this, ctx) : undefined;
  26602. ctx.vars.set(stmt.name, initialValue);
  26603. if (stmt.hasModifier(StmtModifier.Exported)) {
  26604. ctx.exports.push(stmt.name);
  26605. }
  26606. return null;
  26607. };
  26608. StatementInterpreter.prototype.visitWriteVarExpr = function (expr, ctx) {
  26609. var value = expr.value.visitExpression(this, ctx);
  26610. var currCtx = ctx;
  26611. while (currCtx != null) {
  26612. if (currCtx.vars.has(expr.name)) {
  26613. currCtx.vars.set(expr.name, value);
  26614. return value;
  26615. }
  26616. currCtx = currCtx.parent;
  26617. }
  26618. throw new Error("Not declared variable " + expr.name);
  26619. };
  26620. StatementInterpreter.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  26621. throw new Error('Cannot interpret a WrappedNodeExpr.');
  26622. };
  26623. StatementInterpreter.prototype.visitTypeofExpr = function (ast, ctx) {
  26624. throw new Error('Cannot interpret a TypeofExpr');
  26625. };
  26626. StatementInterpreter.prototype.visitReadVarExpr = function (ast, ctx) {
  26627. var varName = ast.name;
  26628. if (ast.builtin != null) {
  26629. switch (ast.builtin) {
  26630. case BuiltinVar.Super:
  26631. return ctx.instance.__proto__;
  26632. case BuiltinVar.This:
  26633. return ctx.instance;
  26634. case BuiltinVar.CatchError:
  26635. varName = CATCH_ERROR_VAR$2;
  26636. break;
  26637. case BuiltinVar.CatchStack:
  26638. varName = CATCH_STACK_VAR$2;
  26639. break;
  26640. default:
  26641. throw new Error("Unknown builtin variable " + ast.builtin);
  26642. }
  26643. }
  26644. var currCtx = ctx;
  26645. while (currCtx != null) {
  26646. if (currCtx.vars.has(varName)) {
  26647. return currCtx.vars.get(varName);
  26648. }
  26649. currCtx = currCtx.parent;
  26650. }
  26651. throw new Error("Not declared variable " + varName);
  26652. };
  26653. StatementInterpreter.prototype.visitWriteKeyExpr = function (expr, ctx) {
  26654. var receiver = expr.receiver.visitExpression(this, ctx);
  26655. var index = expr.index.visitExpression(this, ctx);
  26656. var value = expr.value.visitExpression(this, ctx);
  26657. receiver[index] = value;
  26658. return value;
  26659. };
  26660. StatementInterpreter.prototype.visitWritePropExpr = function (expr, ctx) {
  26661. var receiver = expr.receiver.visitExpression(this, ctx);
  26662. var value = expr.value.visitExpression(this, ctx);
  26663. receiver[expr.name] = value;
  26664. return value;
  26665. };
  26666. StatementInterpreter.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  26667. var receiver = expr.receiver.visitExpression(this, ctx);
  26668. var args = this.visitAllExpressions(expr.args, ctx);
  26669. var result;
  26670. if (expr.builtin != null) {
  26671. switch (expr.builtin) {
  26672. case BuiltinMethod.ConcatArray:
  26673. result = receiver.concat.apply(receiver, __spread(args));
  26674. break;
  26675. case BuiltinMethod.SubscribeObservable:
  26676. result = receiver.subscribe({ next: args[0] });
  26677. break;
  26678. case BuiltinMethod.Bind:
  26679. result = receiver.bind.apply(receiver, __spread(args));
  26680. break;
  26681. default:
  26682. throw new Error("Unknown builtin method " + expr.builtin);
  26683. }
  26684. }
  26685. else {
  26686. result = receiver[expr.name].apply(receiver, args);
  26687. }
  26688. return result;
  26689. };
  26690. StatementInterpreter.prototype.visitInvokeFunctionExpr = function (stmt, ctx) {
  26691. var args = this.visitAllExpressions(stmt.args, ctx);
  26692. var fnExpr = stmt.fn;
  26693. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
  26694. ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
  26695. return null;
  26696. }
  26697. else {
  26698. var fn = stmt.fn.visitExpression(this, ctx);
  26699. return fn.apply(null, args);
  26700. }
  26701. };
  26702. StatementInterpreter.prototype.visitReturnStmt = function (stmt, ctx) {
  26703. return new ReturnValue(stmt.value.visitExpression(this, ctx));
  26704. };
  26705. StatementInterpreter.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  26706. var clazz = createDynamicClass(stmt, ctx, this);
  26707. ctx.vars.set(stmt.name, clazz);
  26708. if (stmt.hasModifier(StmtModifier.Exported)) {
  26709. ctx.exports.push(stmt.name);
  26710. }
  26711. return null;
  26712. };
  26713. StatementInterpreter.prototype.visitExpressionStmt = function (stmt, ctx) {
  26714. return stmt.expr.visitExpression(this, ctx);
  26715. };
  26716. StatementInterpreter.prototype.visitIfStmt = function (stmt, ctx) {
  26717. var condition = stmt.condition.visitExpression(this, ctx);
  26718. if (condition) {
  26719. return this.visitAllStatements(stmt.trueCase, ctx);
  26720. }
  26721. else if (stmt.falseCase != null) {
  26722. return this.visitAllStatements(stmt.falseCase, ctx);
  26723. }
  26724. return null;
  26725. };
  26726. StatementInterpreter.prototype.visitTryCatchStmt = function (stmt, ctx) {
  26727. try {
  26728. return this.visitAllStatements(stmt.bodyStmts, ctx);
  26729. }
  26730. catch (e) {
  26731. var childCtx = ctx.createChildWihtLocalVars();
  26732. childCtx.vars.set(CATCH_ERROR_VAR$2, e);
  26733. childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
  26734. return this.visitAllStatements(stmt.catchStmts, childCtx);
  26735. }
  26736. };
  26737. StatementInterpreter.prototype.visitThrowStmt = function (stmt, ctx) {
  26738. throw stmt.error.visitExpression(this, ctx);
  26739. };
  26740. StatementInterpreter.prototype.visitCommentStmt = function (stmt, context) { return null; };
  26741. StatementInterpreter.prototype.visitJSDocCommentStmt = function (stmt, context) { return null; };
  26742. StatementInterpreter.prototype.visitInstantiateExpr = function (ast, ctx) {
  26743. var args = this.visitAllExpressions(ast.args, ctx);
  26744. var clazz = ast.classExpr.visitExpression(this, ctx);
  26745. return new (clazz.bind.apply(clazz, __spread([void 0], args)))();
  26746. };
  26747. StatementInterpreter.prototype.visitLiteralExpr = function (ast, ctx) { return ast.value; };
  26748. StatementInterpreter.prototype.visitExternalExpr = function (ast, ctx) {
  26749. return this.reflector.resolveExternalReference(ast.value);
  26750. };
  26751. StatementInterpreter.prototype.visitConditionalExpr = function (ast, ctx) {
  26752. if (ast.condition.visitExpression(this, ctx)) {
  26753. return ast.trueCase.visitExpression(this, ctx);
  26754. }
  26755. else if (ast.falseCase != null) {
  26756. return ast.falseCase.visitExpression(this, ctx);
  26757. }
  26758. return null;
  26759. };
  26760. StatementInterpreter.prototype.visitNotExpr = function (ast, ctx) {
  26761. return !ast.condition.visitExpression(this, ctx);
  26762. };
  26763. StatementInterpreter.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  26764. return ast.condition.visitExpression(this, ctx);
  26765. };
  26766. StatementInterpreter.prototype.visitCastExpr = function (ast, ctx) {
  26767. return ast.value.visitExpression(this, ctx);
  26768. };
  26769. StatementInterpreter.prototype.visitFunctionExpr = function (ast, ctx) {
  26770. var paramNames = ast.params.map(function (param) { return param.name; });
  26771. return _declareFn(paramNames, ast.statements, ctx, this);
  26772. };
  26773. StatementInterpreter.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  26774. var paramNames = stmt.params.map(function (param) { return param.name; });
  26775. ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
  26776. if (stmt.hasModifier(StmtModifier.Exported)) {
  26777. ctx.exports.push(stmt.name);
  26778. }
  26779. return null;
  26780. };
  26781. StatementInterpreter.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  26782. var _this = this;
  26783. var lhs = function () { return ast.lhs.visitExpression(_this, ctx); };
  26784. var rhs = function () { return ast.rhs.visitExpression(_this, ctx); };
  26785. switch (ast.operator) {
  26786. case BinaryOperator.Equals:
  26787. return lhs() == rhs();
  26788. case BinaryOperator.Identical:
  26789. return lhs() === rhs();
  26790. case BinaryOperator.NotEquals:
  26791. return lhs() != rhs();
  26792. case BinaryOperator.NotIdentical:
  26793. return lhs() !== rhs();
  26794. case BinaryOperator.And:
  26795. return lhs() && rhs();
  26796. case BinaryOperator.Or:
  26797. return lhs() || rhs();
  26798. case BinaryOperator.Plus:
  26799. return lhs() + rhs();
  26800. case BinaryOperator.Minus:
  26801. return lhs() - rhs();
  26802. case BinaryOperator.Divide:
  26803. return lhs() / rhs();
  26804. case BinaryOperator.Multiply:
  26805. return lhs() * rhs();
  26806. case BinaryOperator.Modulo:
  26807. return lhs() % rhs();
  26808. case BinaryOperator.Lower:
  26809. return lhs() < rhs();
  26810. case BinaryOperator.LowerEquals:
  26811. return lhs() <= rhs();
  26812. case BinaryOperator.Bigger:
  26813. return lhs() > rhs();
  26814. case BinaryOperator.BiggerEquals:
  26815. return lhs() >= rhs();
  26816. default:
  26817. throw new Error("Unknown operator " + ast.operator);
  26818. }
  26819. };
  26820. StatementInterpreter.prototype.visitReadPropExpr = function (ast, ctx) {
  26821. var result;
  26822. var receiver = ast.receiver.visitExpression(this, ctx);
  26823. result = receiver[ast.name];
  26824. return result;
  26825. };
  26826. StatementInterpreter.prototype.visitReadKeyExpr = function (ast, ctx) {
  26827. var receiver = ast.receiver.visitExpression(this, ctx);
  26828. var prop = ast.index.visitExpression(this, ctx);
  26829. return receiver[prop];
  26830. };
  26831. StatementInterpreter.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  26832. return this.visitAllExpressions(ast.entries, ctx);
  26833. };
  26834. StatementInterpreter.prototype.visitLiteralMapExpr = function (ast, ctx) {
  26835. var _this = this;
  26836. var result = {};
  26837. ast.entries.forEach(function (entry) { return result[entry.key] = entry.value.visitExpression(_this, ctx); });
  26838. return result;
  26839. };
  26840. StatementInterpreter.prototype.visitCommaExpr = function (ast, context) {
  26841. var values = this.visitAllExpressions(ast.parts, context);
  26842. return values[values.length - 1];
  26843. };
  26844. StatementInterpreter.prototype.visitAllExpressions = function (expressions, ctx) {
  26845. var _this = this;
  26846. return expressions.map(function (expr) { return expr.visitExpression(_this, ctx); });
  26847. };
  26848. StatementInterpreter.prototype.visitAllStatements = function (statements, ctx) {
  26849. for (var i = 0; i < statements.length; i++) {
  26850. var stmt = statements[i];
  26851. var val = stmt.visitStatement(this, ctx);
  26852. if (val instanceof ReturnValue) {
  26853. return val;
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. return StatementInterpreter;
  26859. }());
  26860. function _declareFn(varNames, statements, ctx, visitor) {
  26861. return function () {
  26862. var args = [];
  26863. for (var _i = 0; _i < arguments.length; _i++) {
  26864. args[_i] = arguments[_i];
  26865. }
  26866. return _executeFunctionStatements(varNames, args, statements, ctx, visitor);
  26867. };
  26868. }
  26869. var CATCH_ERROR_VAR$2 = 'error';
  26870. var CATCH_STACK_VAR$2 = 'stack';
  26871. /**
  26872. * @license
  26873. * Copyright Google Inc. All Rights Reserved.
  26874. *
  26875. * Use of this source code is governed by an MIT-style license that can be
  26876. * found in the LICENSE file at https://angular.io/license
  26877. */
  26878. /**
  26879. * An internal module of the Angular compiler that begins with component types,
  26880. * extracts templates, and eventually produces a compiled version of the component
  26881. * ready for linking into an application.
  26882. *
  26883. * @security When compiling templates at runtime, you must ensure that the entire template comes
  26884. * from a trusted source. Attacker-controlled data introduced by a template could expose your
  26885. * application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
  26886. */
  26887. var JitCompiler = /** @class */ (function () {
  26888. function JitCompiler(_metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _summaryResolver, _reflector, _jitEvaluator, _compilerConfig, _console, getExtraNgModuleProviders) {
  26889. this._metadataResolver = _metadataResolver;
  26890. this._templateParser = _templateParser;
  26891. this._styleCompiler = _styleCompiler;
  26892. this._viewCompiler = _viewCompiler;
  26893. this._ngModuleCompiler = _ngModuleCompiler;
  26894. this._summaryResolver = _summaryResolver;
  26895. this._reflector = _reflector;
  26896. this._jitEvaluator = _jitEvaluator;
  26897. this._compilerConfig = _compilerConfig;
  26898. this._console = _console;
  26899. this.getExtraNgModuleProviders = getExtraNgModuleProviders;
  26900. this._compiledTemplateCache = new Map();
  26901. this._compiledHostTemplateCache = new Map();
  26902. this._compiledDirectiveWrapperCache = new Map();
  26903. this._compiledNgModuleCache = new Map();
  26904. this._sharedStylesheetCount = 0;
  26905. this._addedAotSummaries = new Set();
  26906. }
  26907. JitCompiler.prototype.compileModuleSync = function (moduleType) {
  26908. return SyncAsync.assertSync(this._compileModuleAndComponents(moduleType, true));
  26909. };
  26910. JitCompiler.prototype.compileModuleAsync = function (moduleType) {
  26911. return Promise.resolve(this._compileModuleAndComponents(moduleType, false));
  26912. };
  26913. JitCompiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
  26914. return SyncAsync.assertSync(this._compileModuleAndAllComponents(moduleType, true));
  26915. };
  26916. JitCompiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
  26917. return Promise.resolve(this._compileModuleAndAllComponents(moduleType, false));
  26918. };
  26919. JitCompiler.prototype.getComponentFactory = function (component) {
  26920. var summary = this._metadataResolver.getDirectiveSummary(component);
  26921. return summary.componentFactory;
  26922. };
  26923. JitCompiler.prototype.loadAotSummaries = function (summaries) {
  26924. this.clearCache();
  26925. this._addAotSummaries(summaries);
  26926. };
  26927. JitCompiler.prototype._addAotSummaries = function (fn) {
  26928. if (this._addedAotSummaries.has(fn)) {
  26929. return;
  26930. }
  26931. this._addedAotSummaries.add(fn);
  26932. var summaries = fn();
  26933. for (var i = 0; i < summaries.length; i++) {
  26934. var entry = summaries[i];
  26935. if (typeof entry === 'function') {
  26936. this._addAotSummaries(entry);
  26937. }
  26938. else {
  26939. var summary = entry;
  26940. this._summaryResolver.addSummary({ symbol: summary.type.reference, metadata: null, type: summary });
  26941. }
  26942. }
  26943. };
  26944. JitCompiler.prototype.hasAotSummary = function (ref) { return !!this._summaryResolver.resolveSummary(ref); };
  26945. JitCompiler.prototype._filterJitIdentifiers = function (ids) {
  26946. var _this = this;
  26947. return ids.map(function (mod) { return mod.reference; }).filter(function (ref) { return !_this.hasAotSummary(ref); });
  26948. };
  26949. JitCompiler.prototype._compileModuleAndComponents = function (moduleType, isSync) {
  26950. var _this = this;
  26951. return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
  26952. _this._compileComponents(moduleType, null);
  26953. return _this._compileModule(moduleType);
  26954. });
  26955. };
  26956. JitCompiler.prototype._compileModuleAndAllComponents = function (moduleType, isSync) {
  26957. var _this = this;
  26958. return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
  26959. var componentFactories = [];
  26960. _this._compileComponents(moduleType, componentFactories);
  26961. return {
  26962. ngModuleFactory: _this._compileModule(moduleType),
  26963. componentFactories: componentFactories
  26964. };
  26965. });
  26966. };
  26967. JitCompiler.prototype._loadModules = function (mainModule, isSync) {
  26968. var _this = this;
  26969. var loading = [];
  26970. var mainNgModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  26971. // Note: for runtime compilation, we want to transitively compile all modules,
  26972. // so we also need to load the declared directives / pipes for all nested modules.
  26973. this._filterJitIdentifiers(mainNgModule.transitiveModule.modules).forEach(function (nestedNgModule) {
  26974. // getNgModuleMetadata only returns null if the value passed in is not an NgModule
  26975. var moduleMeta = _this._metadataResolver.getNgModuleMetadata(nestedNgModule);
  26976. _this._filterJitIdentifiers(moduleMeta.declaredDirectives).forEach(function (ref) {
  26977. var promise = _this._metadataResolver.loadDirectiveMetadata(moduleMeta.type.reference, ref, isSync);
  26978. if (promise) {
  26979. loading.push(promise);
  26980. }
  26981. });
  26982. _this._filterJitIdentifiers(moduleMeta.declaredPipes)
  26983. .forEach(function (ref) { return _this._metadataResolver.getOrLoadPipeMetadata(ref); });
  26984. });
  26985. return SyncAsync.all(loading);
  26986. };
  26987. JitCompiler.prototype._compileModule = function (moduleType) {
  26988. var ngModuleFactory = this._compiledNgModuleCache.get(moduleType);
  26989. if (!ngModuleFactory) {
  26990. var moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
  26991. // Always provide a bound Compiler
  26992. var extraProviders = this.getExtraNgModuleProviders(moduleMeta.type.reference);
  26993. var outputCtx = createOutputContext();
  26994. var compileResult = this._ngModuleCompiler.compile(outputCtx, moduleMeta, extraProviders);
  26995. ngModuleFactory = this._interpretOrJit(ngModuleJitUrl(moduleMeta), outputCtx.statements)[compileResult.ngModuleFactoryVar];
  26996. this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
  26997. }
  26998. return ngModuleFactory;
  26999. };
  27000. /**
  27001. * @internal
  27002. */
  27003. JitCompiler.prototype._compileComponents = function (mainModule, allComponentFactories) {
  27004. var _this = this;
  27005. var ngModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  27006. var moduleByJitDirective = new Map();
  27007. var templates = new Set();
  27008. var transJitModules = this._filterJitIdentifiers(ngModule.transitiveModule.modules);
  27009. transJitModules.forEach(function (localMod) {
  27010. var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
  27011. _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
  27012. moduleByJitDirective.set(dirRef, localModuleMeta);
  27013. var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
  27014. if (dirMeta.isComponent) {
  27015. templates.add(_this._createCompiledTemplate(dirMeta, localModuleMeta));
  27016. if (allComponentFactories) {
  27017. var template = _this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
  27018. templates.add(template);
  27019. allComponentFactories.push(dirMeta.componentFactory);
  27020. }
  27021. }
  27022. });
  27023. });
  27024. transJitModules.forEach(function (localMod) {
  27025. var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
  27026. _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
  27027. var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
  27028. if (dirMeta.isComponent) {
  27029. dirMeta.entryComponents.forEach(function (entryComponentType) {
  27030. var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  27031. templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  27032. });
  27033. }
  27034. });
  27035. localModuleMeta.entryComponents.forEach(function (entryComponentType) {
  27036. if (!_this.hasAotSummary(entryComponentType.componentType)) {
  27037. var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  27038. templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  27039. }
  27040. });
  27041. });
  27042. templates.forEach(function (template) { return _this._compileTemplate(template); });
  27043. };
  27044. JitCompiler.prototype.clearCacheFor = function (type) {
  27045. this._compiledNgModuleCache.delete(type);
  27046. this._metadataResolver.clearCacheFor(type);
  27047. this._compiledHostTemplateCache.delete(type);
  27048. var compiledTemplate = this._compiledTemplateCache.get(type);
  27049. if (compiledTemplate) {
  27050. this._compiledTemplateCache.delete(type);
  27051. }
  27052. };
  27053. JitCompiler.prototype.clearCache = function () {
  27054. // Note: don't clear the _addedAotSummaries, as they don't change!
  27055. this._metadataResolver.clearCache();
  27056. this._compiledTemplateCache.clear();
  27057. this._compiledHostTemplateCache.clear();
  27058. this._compiledNgModuleCache.clear();
  27059. };
  27060. JitCompiler.prototype._createCompiledHostTemplate = function (compType, ngModule) {
  27061. if (!ngModule) {
  27062. throw new Error("Component " + stringify(compType) + " is not part of any NgModule or the module has not been imported into your module.");
  27063. }
  27064. var compiledTemplate = this._compiledHostTemplateCache.get(compType);
  27065. if (!compiledTemplate) {
  27066. var compMeta = this._metadataResolver.getDirectiveMetadata(compType);
  27067. assertComponent(compMeta);
  27068. var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta, compMeta.componentFactory.viewDefFactory);
  27069. compiledTemplate =
  27070. new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
  27071. this._compiledHostTemplateCache.set(compType, compiledTemplate);
  27072. }
  27073. return compiledTemplate;
  27074. };
  27075. JitCompiler.prototype._createCompiledTemplate = function (compMeta, ngModule) {
  27076. var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
  27077. if (!compiledTemplate) {
  27078. assertComponent(compMeta);
  27079. compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
  27080. this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
  27081. }
  27082. return compiledTemplate;
  27083. };
  27084. JitCompiler.prototype._compileTemplate = function (template) {
  27085. var _this = this;
  27086. if (template.isCompiled) {
  27087. return;
  27088. }
  27089. var compMeta = template.compMeta;
  27090. var externalStylesheetsByModuleUrl = new Map();
  27091. var outputContext = createOutputContext();
  27092. var componentStylesheet = this._styleCompiler.compileComponent(outputContext, compMeta);
  27093. compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
  27094. var compiledStylesheet = _this._styleCompiler.compileStyles(createOutputContext(), compMeta, stylesheetMeta);
  27095. externalStylesheetsByModuleUrl.set(stylesheetMeta.moduleUrl, compiledStylesheet);
  27096. });
  27097. this._resolveStylesCompileResult(componentStylesheet, externalStylesheetsByModuleUrl);
  27098. var pipes = template.ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  27099. var _a = this._parseTemplate(compMeta, template.ngModule, template.directives), parsedTemplate = _a.template, usedPipes = _a.pipes;
  27100. var compileResult = this._viewCompiler.compileComponent(outputContext, compMeta, parsedTemplate, variable(componentStylesheet.stylesVar), usedPipes);
  27101. var evalResult = this._interpretOrJit(templateJitUrl(template.ngModule.type, template.compMeta), outputContext.statements);
  27102. var viewClass = evalResult[compileResult.viewClassVar];
  27103. var rendererType = evalResult[compileResult.rendererTypeVar];
  27104. template.compiled(viewClass, rendererType);
  27105. };
  27106. JitCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
  27107. var _this = this;
  27108. // Note: ! is ok here as components always have a template.
  27109. var preserveWhitespaces = compMeta.template.preserveWhitespaces;
  27110. var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  27111. var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  27112. return this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  27113. };
  27114. JitCompiler.prototype._resolveStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
  27115. var _this = this;
  27116. result.dependencies.forEach(function (dep, i) {
  27117. var nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
  27118. var nestedStylesArr = _this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
  27119. dep.setValue(nestedStylesArr);
  27120. });
  27121. };
  27122. JitCompiler.prototype._resolveAndEvalStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
  27123. this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
  27124. return this._interpretOrJit(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.outputCtx.statements)[result.stylesVar];
  27125. };
  27126. JitCompiler.prototype._interpretOrJit = function (sourceUrl, statements) {
  27127. if (!this._compilerConfig.useJit) {
  27128. return interpretStatements(statements, this._reflector);
  27129. }
  27130. else {
  27131. return this._jitEvaluator.evaluateStatements(sourceUrl, statements, this._reflector, this._compilerConfig.jitDevMode);
  27132. }
  27133. };
  27134. return JitCompiler;
  27135. }());
  27136. var CompiledTemplate = /** @class */ (function () {
  27137. function CompiledTemplate(isHost, compType, compMeta, ngModule, directives) {
  27138. this.isHost = isHost;
  27139. this.compType = compType;
  27140. this.compMeta = compMeta;
  27141. this.ngModule = ngModule;
  27142. this.directives = directives;
  27143. this._viewClass = null;
  27144. this.isCompiled = false;
  27145. }
  27146. CompiledTemplate.prototype.compiled = function (viewClass, rendererType) {
  27147. this._viewClass = viewClass;
  27148. this.compMeta.componentViewType.setDelegate(viewClass);
  27149. for (var prop in rendererType) {
  27150. this.compMeta.rendererType[prop] = rendererType[prop];
  27151. }
  27152. this.isCompiled = true;
  27153. };
  27154. return CompiledTemplate;
  27155. }());
  27156. function assertComponent(meta) {
  27157. if (!meta.isComponent) {
  27158. throw new Error("Could not compile '" + identifierName(meta.type) + "' because it is not a component.");
  27159. }
  27160. }
  27161. function createOutputContext() {
  27162. var importExpr$1 = function (symbol) {
  27163. return importExpr({ name: identifierName(symbol), moduleName: null, runtime: symbol });
  27164. };
  27165. return { statements: [], genFilePath: '', importExpr: importExpr$1, constantPool: new ConstantPool() };
  27166. }
  27167. /**
  27168. * @license
  27169. * Copyright Google Inc. All Rights Reserved.
  27170. *
  27171. * Use of this source code is governed by an MIT-style license that can be
  27172. * found in the LICENSE file at https://angular.io/license
  27173. */
  27174. /**
  27175. * Provides access to reflection data about symbols that the compiler needs.
  27176. */
  27177. var CompileReflector = /** @class */ (function () {
  27178. function CompileReflector() {
  27179. }
  27180. return CompileReflector;
  27181. }());
  27182. /**
  27183. * @license
  27184. * Copyright Google Inc. All Rights Reserved.
  27185. *
  27186. * Use of this source code is governed by an MIT-style license that can be
  27187. * found in the LICENSE file at https://angular.io/license
  27188. */
  27189. /**
  27190. * Create a {@link UrlResolver} with no package prefix.
  27191. */
  27192. function createUrlResolverWithoutPackagePrefix() {
  27193. return new UrlResolver();
  27194. }
  27195. function createOfflineCompileUrlResolver() {
  27196. return new UrlResolver('.');
  27197. }
  27198. var UrlResolver = /** @class */ (function () {
  27199. function UrlResolverImpl(_packagePrefix) {
  27200. if (_packagePrefix === void 0) { _packagePrefix = null; }
  27201. this._packagePrefix = _packagePrefix;
  27202. }
  27203. /**
  27204. * Resolves the `url` given the `baseUrl`:
  27205. * - when the `url` is null, the `baseUrl` is returned,
  27206. * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
  27207. * `baseUrl` and `url`,
  27208. * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
  27209. * returned as is (ignoring the `baseUrl`)
  27210. */
  27211. UrlResolverImpl.prototype.resolve = function (baseUrl, url) {
  27212. var resolvedUrl = url;
  27213. if (baseUrl != null && baseUrl.length > 0) {
  27214. resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
  27215. }
  27216. var resolvedParts = _split(resolvedUrl);
  27217. var prefix = this._packagePrefix;
  27218. if (prefix != null && resolvedParts != null &&
  27219. resolvedParts[_ComponentIndex.Scheme] == 'package') {
  27220. var path = resolvedParts[_ComponentIndex.Path];
  27221. prefix = prefix.replace(/\/+$/, '');
  27222. path = path.replace(/^\/+/, '');
  27223. return prefix + "/" + path;
  27224. }
  27225. return resolvedUrl;
  27226. };
  27227. return UrlResolverImpl;
  27228. }());
  27229. /**
  27230. * Extract the scheme of a URL.
  27231. */
  27232. function getUrlScheme(url) {
  27233. var match = _split(url);
  27234. return (match && match[_ComponentIndex.Scheme]) || '';
  27235. }
  27236. // The code below is adapted from Traceur:
  27237. // https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
  27238. /**
  27239. * Builds a URI string from already-encoded parts.
  27240. *
  27241. * No encoding is performed. Any component may be omitted as either null or
  27242. * undefined.
  27243. *
  27244. * @param opt_scheme The scheme such as 'http'.
  27245. * @param opt_userInfo The user name before the '@'.
  27246. * @param opt_domain The domain such as 'www.google.com', already
  27247. * URI-encoded.
  27248. * @param opt_port The port number.
  27249. * @param opt_path The path, already URI-encoded. If it is not
  27250. * empty, it must begin with a slash.
  27251. * @param opt_queryData The URI-encoded query data.
  27252. * @param opt_fragment The URI-encoded fragment identifier.
  27253. * @return The fully combined URI.
  27254. */
  27255. function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
  27256. var out = [];
  27257. if (opt_scheme != null) {
  27258. out.push(opt_scheme + ':');
  27259. }
  27260. if (opt_domain != null) {
  27261. out.push('//');
  27262. if (opt_userInfo != null) {
  27263. out.push(opt_userInfo + '@');
  27264. }
  27265. out.push(opt_domain);
  27266. if (opt_port != null) {
  27267. out.push(':' + opt_port);
  27268. }
  27269. }
  27270. if (opt_path != null) {
  27271. out.push(opt_path);
  27272. }
  27273. if (opt_queryData != null) {
  27274. out.push('?' + opt_queryData);
  27275. }
  27276. if (opt_fragment != null) {
  27277. out.push('#' + opt_fragment);
  27278. }
  27279. return out.join('');
  27280. }
  27281. /**
  27282. * A regular expression for breaking a URI into its component parts.
  27283. *
  27284. * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
  27285. * As the "first-match-wins" algorithm is identical to the "greedy"
  27286. * disambiguation method used by POSIX regular expressions, it is natural and
  27287. * commonplace to use a regular expression for parsing the potential five
  27288. * components of a URI reference.
  27289. *
  27290. * The following line is the regular expression for breaking-down a
  27291. * well-formed URI reference into its components.
  27292. *
  27293. * <pre>
  27294. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  27295. * 12 3 4 5 6 7 8 9
  27296. * </pre>
  27297. *
  27298. * The numbers in the second line above are only to assist readability; they
  27299. * indicate the reference points for each subexpression (i.e., each paired
  27300. * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
  27301. * For example, matching the above expression to
  27302. * <pre>
  27303. * http://www.ics.uci.edu/pub/ietf/uri/#Related
  27304. * </pre>
  27305. * results in the following subexpression matches:
  27306. * <pre>
  27307. * $1 = http:
  27308. * $2 = http
  27309. * $3 = //www.ics.uci.edu
  27310. * $4 = www.ics.uci.edu
  27311. * $5 = /pub/ietf/uri/
  27312. * $6 = <undefined>
  27313. * $7 = <undefined>
  27314. * $8 = #Related
  27315. * $9 = Related
  27316. * </pre>
  27317. * where <undefined> indicates that the component is not present, as is the
  27318. * case for the query component in the above example. Therefore, we can
  27319. * determine the value of the five components as
  27320. * <pre>
  27321. * scheme = $2
  27322. * authority = $4
  27323. * path = $5
  27324. * query = $7
  27325. * fragment = $9
  27326. * </pre>
  27327. *
  27328. * The regular expression has been modified slightly to expose the
  27329. * userInfo, domain, and port separately from the authority.
  27330. * The modified version yields
  27331. * <pre>
  27332. * $1 = http scheme
  27333. * $2 = <undefined> userInfo -\
  27334. * $3 = www.ics.uci.edu domain | authority
  27335. * $4 = <undefined> port -/
  27336. * $5 = /pub/ietf/uri/ path
  27337. * $6 = <undefined> query without ?
  27338. * $7 = Related fragment without #
  27339. * </pre>
  27340. * @internal
  27341. */
  27342. var _splitRe = new RegExp('^' +
  27343. '(?:' +
  27344. '([^:/?#.]+)' + // scheme - ignore special characters
  27345. // used by other URL parts such as :,
  27346. // ?, /, #, and .
  27347. ':)?' +
  27348. '(?://' +
  27349. '(?:([^/?#]*)@)?' + // userInfo
  27350. '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
  27351. // digits, dashes, dots, percent
  27352. // escapes, and unicode characters.
  27353. '(?::([0-9]+))?' + // port
  27354. ')?' +
  27355. '([^?#]+)?' + // path
  27356. '(?:\\?([^#]*))?' + // query
  27357. '(?:#(.*))?' + // fragment
  27358. '$');
  27359. /**
  27360. * The index of each URI component in the return value of goog.uri.utils.split.
  27361. * @enum {number}
  27362. */
  27363. var _ComponentIndex;
  27364. (function (_ComponentIndex) {
  27365. _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
  27366. _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
  27367. _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
  27368. _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
  27369. _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
  27370. _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
  27371. _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
  27372. })(_ComponentIndex || (_ComponentIndex = {}));
  27373. /**
  27374. * Splits a URI into its component parts.
  27375. *
  27376. * Each component can be accessed via the component indices; for example:
  27377. * <pre>
  27378. * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
  27379. * </pre>
  27380. *
  27381. * @param uri The URI string to examine.
  27382. * @return Each component still URI-encoded.
  27383. * Each component that is present will contain the encoded value, whereas
  27384. * components that are not present will be undefined or empty, depending
  27385. * on the browser's regular expression implementation. Never null, since
  27386. * arbitrary strings may still look like path names.
  27387. */
  27388. function _split(uri) {
  27389. return uri.match(_splitRe);
  27390. }
  27391. /**
  27392. * Removes dot segments in given path component, as described in
  27393. * RFC 3986, section 5.2.4.
  27394. *
  27395. * @param path A non-empty path component.
  27396. * @return Path component with removed dot segments.
  27397. */
  27398. function _removeDotSegments(path) {
  27399. if (path == '/')
  27400. return '/';
  27401. var leadingSlash = path[0] == '/' ? '/' : '';
  27402. var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
  27403. var segments = path.split('/');
  27404. var out = [];
  27405. var up = 0;
  27406. for (var pos = 0; pos < segments.length; pos++) {
  27407. var segment = segments[pos];
  27408. switch (segment) {
  27409. case '':
  27410. case '.':
  27411. break;
  27412. case '..':
  27413. if (out.length > 0) {
  27414. out.pop();
  27415. }
  27416. else {
  27417. up++;
  27418. }
  27419. break;
  27420. default:
  27421. out.push(segment);
  27422. }
  27423. }
  27424. if (leadingSlash == '') {
  27425. while (up-- > 0) {
  27426. out.unshift('..');
  27427. }
  27428. if (out.length === 0)
  27429. out.push('.');
  27430. }
  27431. return leadingSlash + out.join('/') + trailingSlash;
  27432. }
  27433. /**
  27434. * Takes an array of the parts from split and canonicalizes the path part
  27435. * and then joins all the parts.
  27436. */
  27437. function _joinAndCanonicalizePath(parts) {
  27438. var path = parts[_ComponentIndex.Path];
  27439. path = path == null ? '' : _removeDotSegments(path);
  27440. parts[_ComponentIndex.Path] = path;
  27441. return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
  27442. }
  27443. /**
  27444. * Resolves a URL.
  27445. * @param base The URL acting as the base URL.
  27446. * @param to The URL to resolve.
  27447. */
  27448. function _resolveUrl(base, url) {
  27449. var parts = _split(encodeURI(url));
  27450. var baseParts = _split(base);
  27451. if (parts[_ComponentIndex.Scheme] != null) {
  27452. return _joinAndCanonicalizePath(parts);
  27453. }
  27454. else {
  27455. parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
  27456. }
  27457. for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
  27458. if (parts[i] == null) {
  27459. parts[i] = baseParts[i];
  27460. }
  27461. }
  27462. if (parts[_ComponentIndex.Path][0] == '/') {
  27463. return _joinAndCanonicalizePath(parts);
  27464. }
  27465. var path = baseParts[_ComponentIndex.Path];
  27466. if (path == null)
  27467. path = '/';
  27468. var index = path.lastIndexOf('/');
  27469. path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
  27470. parts[_ComponentIndex.Path] = path;
  27471. return _joinAndCanonicalizePath(parts);
  27472. }
  27473. /**
  27474. * @license
  27475. * Copyright Google Inc. All Rights Reserved.
  27476. *
  27477. * Use of this source code is governed by an MIT-style license that can be
  27478. * found in the LICENSE file at https://angular.io/license
  27479. */
  27480. var Extractor = /** @class */ (function () {
  27481. function Extractor(host, staticSymbolResolver, messageBundle, metadataResolver) {
  27482. this.host = host;
  27483. this.staticSymbolResolver = staticSymbolResolver;
  27484. this.messageBundle = messageBundle;
  27485. this.metadataResolver = metadataResolver;
  27486. }
  27487. Extractor.prototype.extract = function (rootFiles) {
  27488. var _this = this;
  27489. var _a = analyzeAndValidateNgModules(rootFiles, this.host, this.staticSymbolResolver, this.metadataResolver), files = _a.files, ngModules = _a.ngModules;
  27490. return Promise
  27491. .all(ngModules.map(function (ngModule) { return _this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
  27492. .then(function () {
  27493. var errors = [];
  27494. files.forEach(function (file) {
  27495. var compMetas = [];
  27496. file.directives.forEach(function (directiveType) {
  27497. var dirMeta = _this.metadataResolver.getDirectiveMetadata(directiveType);
  27498. if (dirMeta && dirMeta.isComponent) {
  27499. compMetas.push(dirMeta);
  27500. }
  27501. });
  27502. compMetas.forEach(function (compMeta) {
  27503. var html = compMeta.template.template;
  27504. // Template URL points to either an HTML or TS file depending on
  27505. // whether the file is used with `templateUrl:` or `template:`,
  27506. // respectively.
  27507. var templateUrl = compMeta.template.templateUrl;
  27508. var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  27509. errors.push.apply(errors, __spread(_this.messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig)));
  27510. });
  27511. });
  27512. if (errors.length) {
  27513. throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
  27514. }
  27515. return _this.messageBundle;
  27516. });
  27517. };
  27518. Extractor.create = function (host, locale) {
  27519. var htmlParser = new HtmlParser();
  27520. var urlResolver = createAotUrlResolver(host);
  27521. var symbolCache = new StaticSymbolCache();
  27522. var summaryResolver = new AotSummaryResolver(host, symbolCache);
  27523. var staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
  27524. var staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
  27525. var config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false });
  27526. var normalizer = new DirectiveNormalizer({ get: function (url) { return host.loadResource(url); } }, urlResolver, htmlParser, config);
  27527. var elementSchemaRegistry = new DomElementSchemaRegistry();
  27528. var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
  27529. // TODO(vicb): implicit tags & attributes
  27530. var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  27531. var extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
  27532. return { extractor: extractor, staticReflector: staticReflector };
  27533. };
  27534. return Extractor;
  27535. }());
  27536. /**
  27537. * @license
  27538. * Copyright Google Inc. All Rights Reserved.
  27539. *
  27540. * Use of this source code is governed by an MIT-style license that can be
  27541. * found in the LICENSE file at https://angular.io/license
  27542. */
  27543. /**
  27544. * @license
  27545. * Copyright Google Inc. All Rights Reserved.
  27546. *
  27547. * Use of this source code is governed by an MIT-style license that can be
  27548. * found in the LICENSE file at https://angular.io/license
  27549. */
  27550. /**
  27551. * Processes `Target`s with a given set of directives and performs a binding operation, which
  27552. * returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
  27553. * target.
  27554. */
  27555. var R3TargetBinder = /** @class */ (function () {
  27556. function R3TargetBinder(directiveMatcher) {
  27557. this.directiveMatcher = directiveMatcher;
  27558. }
  27559. /**
  27560. * Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
  27561. * metadata about the types referenced in the template.
  27562. */
  27563. R3TargetBinder.prototype.bind = function (target) {
  27564. if (!target.template) {
  27565. // TODO(alxhub): handle targets which contain things like HostBindings, etc.
  27566. throw new Error('Binding without a template not yet supported');
  27567. }
  27568. // First, parse the template into a `Scope` structure. This operation captures the syntactic
  27569. // scopes in the template and makes them available for later use.
  27570. var scope = Scope.apply(target.template);
  27571. // Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
  27572. // - directives: Map of nodes (elements & ng-templates) to the directives on them.
  27573. // - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
  27574. // them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
  27575. // - references: Map of #references to their targets.
  27576. var _a = DirectiveBinder.apply(target.template, this.directiveMatcher), directives = _a.directives, bindings = _a.bindings, references = _a.references;
  27577. // Finally, run the TemplateBinder to bind references, variables, and other entities within the
  27578. // template. This extracts all the metadata that doesn't depend on directive matching.
  27579. var _b = TemplateBinder.apply(target.template, scope), expressions = _b.expressions, symbols = _b.symbols, nestingLevel = _b.nestingLevel, usedPipes = _b.usedPipes;
  27580. return new R3BoundTarget(target, directives, bindings, references, expressions, symbols, nestingLevel, usedPipes);
  27581. };
  27582. return R3TargetBinder;
  27583. }());
  27584. /**
  27585. * Represents a binding scope within a template.
  27586. *
  27587. * Any variables, references, or other named entities declared within the template will
  27588. * be captured and available by name in `namedEntities`. Additionally, child templates will
  27589. * be analyzed and have their child `Scope`s available in `childScopes`.
  27590. */
  27591. var Scope = /** @class */ (function () {
  27592. function Scope(parentScope) {
  27593. this.parentScope = parentScope;
  27594. /**
  27595. * Named members of the `Scope`, such as `Reference`s or `Variable`s.
  27596. */
  27597. this.namedEntities = new Map();
  27598. /**
  27599. * Child `Scope`s for immediately nested `Template`s.
  27600. */
  27601. this.childScopes = new Map();
  27602. }
  27603. /**
  27604. * Process a template (either as a `Template` sub-template with variables, or a plain array of
  27605. * template `Node`s) and construct its `Scope`.
  27606. */
  27607. Scope.apply = function (template) {
  27608. var scope = new Scope();
  27609. scope.ingest(template);
  27610. return scope;
  27611. };
  27612. /**
  27613. * Internal method to process the template and populate the `Scope`.
  27614. */
  27615. Scope.prototype.ingest = function (template) {
  27616. var _this = this;
  27617. if (template instanceof Template) {
  27618. // Variables on an <ng-template> are defined in the inner scope.
  27619. template.variables.forEach(function (node) { return _this.visitVariable(node); });
  27620. // Process the nodes of the template.
  27621. template.children.forEach(function (node) { return node.visit(_this); });
  27622. }
  27623. else {
  27624. // No overarching `Template` instance, so process the nodes directly.
  27625. template.forEach(function (node) { return node.visit(_this); });
  27626. }
  27627. };
  27628. Scope.prototype.visitElement = function (element) {
  27629. var _this = this;
  27630. // `Element`s in the template may have `Reference`s which are captured in the scope.
  27631. element.references.forEach(function (node) { return _this.visitReference(node); });
  27632. // Recurse into the `Element`'s children.
  27633. element.children.forEach(function (node) { return node.visit(_this); });
  27634. };
  27635. Scope.prototype.visitTemplate = function (template) {
  27636. var _this = this;
  27637. // References on a <ng-template> are defined in the outer scope, so capture them before
  27638. // processing the template's child scope.
  27639. template.references.forEach(function (node) { return _this.visitReference(node); });
  27640. // Next, create an inner scope and process the template within it.
  27641. var scope = new Scope(this);
  27642. scope.ingest(template);
  27643. this.childScopes.set(template, scope);
  27644. };
  27645. Scope.prototype.visitVariable = function (variable) {
  27646. // Declare the variable if it's not already.
  27647. this.maybeDeclare(variable);
  27648. };
  27649. Scope.prototype.visitReference = function (reference) {
  27650. // Declare the variable if it's not already.
  27651. this.maybeDeclare(reference);
  27652. };
  27653. // Unused visitors.
  27654. Scope.prototype.visitContent = function (content) { };
  27655. Scope.prototype.visitBoundAttribute = function (attr) { };
  27656. Scope.prototype.visitBoundEvent = function (event) { };
  27657. Scope.prototype.visitBoundText = function (text) { };
  27658. Scope.prototype.visitText = function (text) { };
  27659. Scope.prototype.visitTextAttribute = function (attr) { };
  27660. Scope.prototype.visitIcu = function (icu) { };
  27661. Scope.prototype.maybeDeclare = function (thing) {
  27662. // Declare something with a name, as long as that name isn't taken.
  27663. if (!this.namedEntities.has(thing.name)) {
  27664. this.namedEntities.set(thing.name, thing);
  27665. }
  27666. };
  27667. /**
  27668. * Look up a variable within this `Scope`.
  27669. *
  27670. * This can recurse into a parent `Scope` if it's available.
  27671. */
  27672. Scope.prototype.lookup = function (name) {
  27673. if (this.namedEntities.has(name)) {
  27674. // Found in the local scope.
  27675. return this.namedEntities.get(name);
  27676. }
  27677. else if (this.parentScope !== undefined) {
  27678. // Not in the local scope, but there's a parent scope so check there.
  27679. return this.parentScope.lookup(name);
  27680. }
  27681. else {
  27682. // At the top level and it wasn't found.
  27683. return null;
  27684. }
  27685. };
  27686. /**
  27687. * Get the child scope for a `Template`.
  27688. *
  27689. * This should always be defined.
  27690. */
  27691. Scope.prototype.getChildScope = function (template) {
  27692. var res = this.childScopes.get(template);
  27693. if (res === undefined) {
  27694. throw new Error("Assertion error: child scope for " + template + " not found");
  27695. }
  27696. return res;
  27697. };
  27698. return Scope;
  27699. }());
  27700. /**
  27701. * Processes a template and matches directives on nodes (elements and templates).
  27702. *
  27703. * Usually used via the static `apply()` method.
  27704. */
  27705. var DirectiveBinder = /** @class */ (function () {
  27706. function DirectiveBinder(matcher, directives, bindings, references) {
  27707. this.matcher = matcher;
  27708. this.directives = directives;
  27709. this.bindings = bindings;
  27710. this.references = references;
  27711. }
  27712. /**
  27713. * Process a template (list of `Node`s) and perform directive matching against each node.
  27714. *
  27715. * @param template the list of template `Node`s to match (recursively).
  27716. * @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
  27717. * this template.
  27718. * @returns three maps which contain information about directives in the template: the
  27719. * `directives` map which lists directives matched on each node, the `bindings` map which
  27720. * indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
  27721. * map which resolves #references (`Reference`s) within the template to the named directive or
  27722. * template node.
  27723. */
  27724. DirectiveBinder.apply = function (template, selectorMatcher) {
  27725. var directives = new Map();
  27726. var bindings = new Map();
  27727. var references = new Map();
  27728. var matcher = new DirectiveBinder(selectorMatcher, directives, bindings, references);
  27729. matcher.ingest(template);
  27730. return { directives: directives, bindings: bindings, references: references };
  27731. };
  27732. DirectiveBinder.prototype.ingest = function (template) {
  27733. var _this = this;
  27734. template.forEach(function (node) { return node.visit(_this); });
  27735. };
  27736. DirectiveBinder.prototype.visitElement = function (element) { this.visitElementOrTemplate(element.name, element); };
  27737. DirectiveBinder.prototype.visitTemplate = function (template) { this.visitElementOrTemplate('ng-template', template); };
  27738. DirectiveBinder.prototype.visitElementOrTemplate = function (tag, node) {
  27739. var _this = this;
  27740. // First, determine the HTML shape of the node for the purpose of directive matching.
  27741. // Do this by building up a `CssSelector` for the node.
  27742. var cssSelector = new CssSelector();
  27743. cssSelector.setElement(tag);
  27744. // Add attributes to the CSS selector.
  27745. var attrs = getAttrsForDirectiveMatching(node);
  27746. Object.getOwnPropertyNames(attrs).forEach(function (name) {
  27747. var value = attrs[name];
  27748. cssSelector.addAttribute(name, value);
  27749. // Treat the 'class' attribute specially.
  27750. if (name.toLowerCase() === 'class') {
  27751. var classes = value.trim().split(/\s+/g);
  27752. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  27753. }
  27754. });
  27755. // Next, use the `SelectorMatcher` to get the list of directives on the node.
  27756. var directives = [];
  27757. this.matcher.match(cssSelector, function (_, directive) { return directives.push(directive); });
  27758. if (directives.length > 0) {
  27759. this.directives.set(node, directives);
  27760. }
  27761. // Resolve any references that are created on this node.
  27762. node.references.forEach(function (ref) {
  27763. var dirTarget = null;
  27764. // If the reference expression is empty, then it matches the "primary" directive on the node
  27765. // (if there is one). Otherwise it matches the host node itself (either an element or
  27766. // <ng-template> node).
  27767. if (ref.value.trim() === '') {
  27768. // This could be a reference to a component if there is one.
  27769. dirTarget = directives.find(function (dir) { return dir.isComponent; }) || null;
  27770. }
  27771. else {
  27772. // This is a reference to a directive exported via exportAs. One should exist.
  27773. dirTarget =
  27774. directives.find(function (dir) { return dir.exportAs !== null && dir.exportAs.some(function (value) { return value === ref.value; }); }) ||
  27775. null;
  27776. // Check if a matching directive was found, and error if it wasn't.
  27777. if (dirTarget === null) {
  27778. // TODO(alxhub): Return an error value here that can be used for template validation.
  27779. throw new Error("Assertion error: failed to find directive with exportAs: " + ref.value);
  27780. }
  27781. }
  27782. if (dirTarget !== null) {
  27783. // This reference points to a directive.
  27784. _this.references.set(ref, { directive: dirTarget, node: node });
  27785. }
  27786. else {
  27787. // This reference points to the node itself.
  27788. _this.references.set(ref, node);
  27789. }
  27790. });
  27791. // Associate attributes/bindings on the node with directives or with the node itself.
  27792. var processAttribute = function (attribute) {
  27793. var dir = directives.find(function (dir) { return dir.inputs.hasOwnProperty(attribute.name); });
  27794. if (dir !== undefined) {
  27795. _this.bindings.set(attribute, dir);
  27796. }
  27797. else {
  27798. _this.bindings.set(attribute, node);
  27799. }
  27800. };
  27801. node.attributes.forEach(processAttribute);
  27802. node.inputs.forEach(processAttribute);
  27803. node.outputs.forEach(processAttribute);
  27804. if (node instanceof Template) {
  27805. node.templateAttrs.forEach(processAttribute);
  27806. }
  27807. // Recurse into the node's children.
  27808. node.children.forEach(function (child) { return child.visit(_this); });
  27809. };
  27810. // Unused visitors.
  27811. DirectiveBinder.prototype.visitContent = function (content) { };
  27812. DirectiveBinder.prototype.visitVariable = function (variable) { };
  27813. DirectiveBinder.prototype.visitReference = function (reference) { };
  27814. DirectiveBinder.prototype.visitTextAttribute = function (attribute) { };
  27815. DirectiveBinder.prototype.visitBoundAttribute = function (attribute) { };
  27816. DirectiveBinder.prototype.visitBoundEvent = function (attribute) { };
  27817. DirectiveBinder.prototype.visitBoundAttributeOrEvent = function (node) { };
  27818. DirectiveBinder.prototype.visitText = function (text) { };
  27819. DirectiveBinder.prototype.visitBoundText = function (text) { };
  27820. DirectiveBinder.prototype.visitIcu = function (icu) { };
  27821. return DirectiveBinder;
  27822. }());
  27823. /**
  27824. * Processes a template and extract metadata about expressions and symbols within.
  27825. *
  27826. * This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
  27827. * within the template in order to operate.
  27828. *
  27829. * Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
  27830. * by overridden methods from that visitor.
  27831. */
  27832. var TemplateBinder = /** @class */ (function (_super) {
  27833. __extends(TemplateBinder, _super);
  27834. function TemplateBinder(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
  27835. var _this = _super.call(this) || this;
  27836. _this.bindings = bindings;
  27837. _this.symbols = symbols;
  27838. _this.usedPipes = usedPipes;
  27839. _this.nestingLevel = nestingLevel;
  27840. _this.scope = scope;
  27841. _this.template = template;
  27842. _this.level = level;
  27843. _this.pipesUsed = [];
  27844. // Save a bit of processing time by constructing this closure in advance.
  27845. _this.visitNode = function (node) { return node.visit(_this); };
  27846. return _this;
  27847. }
  27848. /**
  27849. * Process a template and extract metadata about expressions and symbols within.
  27850. *
  27851. * @param template the nodes of the template to process
  27852. * @param scope the `Scope` of the template being processed.
  27853. * @returns three maps which contain metadata about the template: `expressions` which interprets
  27854. * special `AST` nodes in expressions as pointing to references or variables declared within the
  27855. * template, `symbols` which maps those variables and references to the nested `Template` which
  27856. * declares them, if any, and `nestingLevel` which associates each `Template` with a integer
  27857. * nesting level (how many levels deep within the template structure the `Template` is), starting
  27858. * at 1.
  27859. */
  27860. TemplateBinder.apply = function (template, scope) {
  27861. var expressions = new Map();
  27862. var symbols = new Map();
  27863. var nestingLevel = new Map();
  27864. var usedPipes = new Set();
  27865. // The top-level template has nesting level 0.
  27866. var binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
  27867. binder.ingest(template);
  27868. return { expressions: expressions, symbols: symbols, nestingLevel: nestingLevel, usedPipes: usedPipes };
  27869. };
  27870. TemplateBinder.prototype.ingest = function (template) {
  27871. if (template instanceof Template) {
  27872. // For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
  27873. // and references were all processed in the scope of the containing template.
  27874. template.variables.forEach(this.visitNode);
  27875. template.children.forEach(this.visitNode);
  27876. // Set the nesting level.
  27877. this.nestingLevel.set(template, this.level);
  27878. }
  27879. else {
  27880. // Visit each node from the top-level template.
  27881. template.forEach(this.visitNode);
  27882. }
  27883. };
  27884. TemplateBinder.prototype.visitElement = function (element) {
  27885. // Visit the inputs, outputs, and children of the element.
  27886. element.inputs.forEach(this.visitNode);
  27887. element.outputs.forEach(this.visitNode);
  27888. element.children.forEach(this.visitNode);
  27889. };
  27890. TemplateBinder.prototype.visitTemplate = function (template) {
  27891. // First, visit inputs, outputs and template attributes of the template node.
  27892. template.inputs.forEach(this.visitNode);
  27893. template.outputs.forEach(this.visitNode);
  27894. template.templateAttrs.forEach(this.visitNode);
  27895. // References are also evaluated in the outer context.
  27896. template.references.forEach(this.visitNode);
  27897. // Next, recurse into the template using its scope, and bumping the nesting level up by one.
  27898. var childScope = this.scope.getChildScope(template);
  27899. var binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
  27900. binder.ingest(template);
  27901. };
  27902. TemplateBinder.prototype.visitVariable = function (variable) {
  27903. // Register the `Variable` as a symbol in the current `Template`.
  27904. if (this.template !== null) {
  27905. this.symbols.set(variable, this.template);
  27906. }
  27907. };
  27908. TemplateBinder.prototype.visitReference = function (reference) {
  27909. // Register the `Reference` as a symbol in the current `Template`.
  27910. if (this.template !== null) {
  27911. this.symbols.set(reference, this.template);
  27912. }
  27913. };
  27914. // Unused template visitors
  27915. TemplateBinder.prototype.visitText = function (text) { };
  27916. TemplateBinder.prototype.visitContent = function (content) { };
  27917. TemplateBinder.prototype.visitTextAttribute = function (attribute) { };
  27918. TemplateBinder.prototype.visitIcu = function (icu) { };
  27919. // The remaining visitors are concerned with processing AST expressions within template bindings
  27920. TemplateBinder.prototype.visitBoundAttribute = function (attribute) { attribute.value.visit(this); };
  27921. TemplateBinder.prototype.visitBoundEvent = function (event) { event.handler.visit(this); };
  27922. TemplateBinder.prototype.visitBoundText = function (text) { text.value.visit(this); };
  27923. TemplateBinder.prototype.visitPipe = function (ast, context) {
  27924. this.usedPipes.add(ast.name);
  27925. return _super.prototype.visitPipe.call(this, ast, context);
  27926. };
  27927. // These five types of AST expressions can refer to expression roots, which could be variables
  27928. // or references in the current scope.
  27929. TemplateBinder.prototype.visitPropertyRead = function (ast, context) {
  27930. this.maybeMap(context, ast, ast.name);
  27931. return _super.prototype.visitPropertyRead.call(this, ast, context);
  27932. };
  27933. TemplateBinder.prototype.visitSafePropertyRead = function (ast, context) {
  27934. this.maybeMap(context, ast, ast.name);
  27935. return _super.prototype.visitSafePropertyRead.call(this, ast, context);
  27936. };
  27937. TemplateBinder.prototype.visitPropertyWrite = function (ast, context) {
  27938. this.maybeMap(context, ast, ast.name);
  27939. return _super.prototype.visitPropertyWrite.call(this, ast, context);
  27940. };
  27941. TemplateBinder.prototype.visitMethodCall = function (ast, context) {
  27942. this.maybeMap(context, ast, ast.name);
  27943. return _super.prototype.visitMethodCall.call(this, ast, context);
  27944. };
  27945. TemplateBinder.prototype.visitSafeMethodCall = function (ast, context) {
  27946. this.maybeMap(context, ast, ast.name);
  27947. return _super.prototype.visitSafeMethodCall.call(this, ast, context);
  27948. };
  27949. TemplateBinder.prototype.maybeMap = function (scope, ast, name) {
  27950. // If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
  27951. // `AST` expression that maps to a `Variable` or `Reference`.
  27952. if (!(ast.receiver instanceof ImplicitReceiver)) {
  27953. return;
  27954. }
  27955. // Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
  27956. // probably a property on the top-level component context.
  27957. var target = this.scope.lookup(name);
  27958. if (target !== null) {
  27959. this.bindings.set(ast, target);
  27960. }
  27961. };
  27962. return TemplateBinder;
  27963. }(RecursiveAstVisitor$1));
  27964. /**
  27965. * Metadata container for a `Target` that allows queries for specific bits of metadata.
  27966. *
  27967. * See `BoundTarget` for documentation on the individual methods.
  27968. */
  27969. var R3BoundTarget = /** @class */ (function () {
  27970. function R3BoundTarget(target, directives, bindings, references, exprTargets, symbols, nestingLevel, usedPipes) {
  27971. this.target = target;
  27972. this.directives = directives;
  27973. this.bindings = bindings;
  27974. this.references = references;
  27975. this.exprTargets = exprTargets;
  27976. this.symbols = symbols;
  27977. this.nestingLevel = nestingLevel;
  27978. this.usedPipes = usedPipes;
  27979. }
  27980. R3BoundTarget.prototype.getDirectivesOfNode = function (node) {
  27981. return this.directives.get(node) || null;
  27982. };
  27983. R3BoundTarget.prototype.getReferenceTarget = function (ref) {
  27984. return this.references.get(ref) || null;
  27985. };
  27986. R3BoundTarget.prototype.getConsumerOfBinding = function (binding) {
  27987. return this.bindings.get(binding) || null;
  27988. };
  27989. R3BoundTarget.prototype.getExpressionTarget = function (expr) {
  27990. return this.exprTargets.get(expr) || null;
  27991. };
  27992. R3BoundTarget.prototype.getTemplateOfSymbol = function (symbol) {
  27993. return this.symbols.get(symbol) || null;
  27994. };
  27995. R3BoundTarget.prototype.getNestingLevel = function (template) { return this.nestingLevel.get(template) || 0; };
  27996. R3BoundTarget.prototype.getUsedDirectives = function () {
  27997. var set = new Set();
  27998. this.directives.forEach(function (dirs) { return dirs.forEach(function (dir) { return set.add(dir); }); });
  27999. return Array.from(set.values());
  28000. };
  28001. R3BoundTarget.prototype.getUsedPipes = function () { return Array.from(this.usedPipes); };
  28002. return R3BoundTarget;
  28003. }());
  28004. /**
  28005. * @license
  28006. * Copyright Google Inc. All Rights Reserved.
  28007. *
  28008. * Use of this source code is governed by an MIT-style license that can be
  28009. * found in the LICENSE file at https://angular.io/license
  28010. */
  28011. // This file only reexports content of the `src` folder. Keep it that way.
  28012. // This function call has a global side effects and publishes the compiler into global namespace for
  28013. // the late binding of the Compiler to the @angular/core for jit compilation.
  28014. publishFacade(_global);
  28015. /**
  28016. * @license
  28017. * Copyright Google Inc. All Rights Reserved.
  28018. *
  28019. * Use of this source code is governed by an MIT-style license that can be
  28020. * found in the LICENSE file at https://angular.io/license
  28021. */
  28022. // This file only reexports content of the `src` folder. Keep it that way.
  28023. /**
  28024. * @license
  28025. * Copyright Google Inc. All Rights Reserved.
  28026. *
  28027. * Use of this source code is governed by an MIT-style license that can be
  28028. * found in the LICENSE file at https://angular.io/license
  28029. */
  28030. /**
  28031. * @license
  28032. * Copyright Google Inc. All Rights Reserved.
  28033. *
  28034. * Use of this source code is governed by an MIT-style license that can be
  28035. * found in the LICENSE file at https://angular.io/license
  28036. */
  28037. 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 };
  28038. //# sourceMappingURL=compiler.js.map